| 1 | use axum::Json; |
| 2 | use axum::extract::{Request, State}; |
| 3 | use axum::http::StatusCode; |
| 4 | use axum::middleware::{self, Next}; |
| 5 | use axum_extra::extract::CookieJar; |
| 6 | use axum_extra::extract::cookie::{Cookie, SameSite}; |
| 7 | use serde::{Deserialize, Serialize}; |
| 8 | use utoipa::ToSchema; |
| 9 | use utoipa_axum::router::OpenApiRouter; |
| 10 | use utoipa_axum::routes; |
| 11 | |
| 12 | use crate::constant::{RESERVED_USERNAMES, SESSION_DURATION_DAYS}; |
| 13 | use crate::domain::role::Role as DomainRole; |
| 14 | use crate::domain::user::{Password, PasswordHash, Username}; |
| 15 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 16 | use crate::rate_limit::{RateLimitConfig, RateLimiter}; |
| 17 | use crate::service; |
| 18 | use crate::state::AppState; |
| 19 | use crate::tenant::Slug; |
| 20 | |
| 21 | use super::dto::Role; |
| 22 | use super::tenant_state::split_cookie; |
| 23 | use super::{BUILDER_COOKIE_PREFIX, CurrentUser, PERSON_COOKIE_PREFIX, UserResponse}; |
| 24 | |
| 25 | pub fn routes(state: &AppState) -> OpenApiRouter<AppState> { |
| 26 | |
| 27 | |
| 28 | |
| 29 | |
| 30 | let rate_limit: &RateLimitConfig = &state.rate_limit; |
| 31 | let limiter = RateLimiter::per_minute(rate_limit.auth_per_minute, rate_limit.trust_proxy); |
| 32 | |
| 33 | |
| 34 | limiter.share("auth", state.db.clone()); |
| 35 | OpenApiRouter::new() |
| 36 | .routes(routes!(register)) |
| 37 | .routes(routes!(login)) |
| 38 | |
| 39 | .route_layer(middleware::from_fn(move |req: Request, next: Next| { |
| 40 | let limiter = limiter.clone(); |
| 41 | async move { limiter.enforce(req, next).await } |
| 42 | })) |
| 43 | .routes(routes!(select_school)) |
| 44 | .routes(routes!(logout)) |
| 45 | .routes(routes!(me)) |
| 46 | } |
| 47 | |
| 48 | |
| 49 | |
| 50 | |
| 51 | |
| 52 | #[derive(Deserialize, ToSchema)] |
| 53 | struct RegisterCredentials { |
| 54 | |
| 55 | |
| 56 | #[schema(example = "demo", min_length = 2, max_length = 32)] |
| 57 | school: String, |
| 58 | #[schema(example = "ada", min_length = 3, max_length = 32)] |
| 59 | username: String, |
| 60 | #[schema(example = "correct horse battery", min_length = 6, max_length = 128)] |
| 61 | password: String, |
| 62 | } |
| 63 | |
| 64 | |
| 65 | |
| 66 | |
| 67 | #[derive(Deserialize, ToSchema)] |
| 68 | struct LoginCredentials { |
| 69 | #[schema(example = "ada", min_length = 3, max_length = 32)] |
| 70 | username: String, |
| 71 | #[schema(example = "correct horse battery", min_length = 6, max_length = 128)] |
| 72 | password: String, |
| 73 | } |
| 74 | |
| 75 | |
| 76 | #[derive(Serialize, ToSchema)] |
| 77 | struct SchoolChoice { |
| 78 | #[schema(example = "demo")] |
| 79 | slug: String, |
| 80 | #[schema(example = "Demo")] |
| 81 | name: String, |
| 82 | } |
| 83 | |
| 84 | |
| 85 | |
| 86 | |
| 87 | |
| 88 | #[derive(Serialize, ToSchema)] |
| 89 | struct SchoolChoiceResponse { |
| 90 | #[schema(example = "ada")] |
| 91 | username: String, |
| 92 | schools: Vec<SchoolChoice>, |
| 93 | } |
| 94 | |
| 95 | |
| 96 | |
| 97 | |
| 98 | |
| 99 | #[derive(Serialize, ToSchema)] |
| 100 | #[serde(untagged)] |
| 101 | enum LoginResponse { |
| 102 | LoggedIn(Box<UserResponse>), |
| 103 | ChooseSchool(SchoolChoiceResponse), |
| 104 | } |
| 105 | |
| 106 | |
| 107 | #[derive(Deserialize, ToSchema)] |
| 108 | struct SelectSchool { |
| 109 | #[schema(example = "demo", min_length = 2, max_length = 32)] |
| 110 | school: String, |
| 111 | } |
| 112 | |
| 113 | |
| 114 | |
| 115 | |
| 116 | |
| 117 | |
| 118 | |
| 119 | #[derive(Serialize, ToSchema)] |
| 120 | struct RegisterResponse { |
| 121 | #[schema(example = "ada")] |
| 122 | username: String, |
| 123 | role: Role, |
| 124 | } |
| 125 | |
| 126 | |
| 127 | |
| 128 | |
| 129 | |
| 130 | |
| 131 | |
| 132 | |
| 133 | |
| 134 | |
| 135 | |
| 136 | |
| 137 | |
| 138 | |
| 139 | |
| 140 | |
| 141 | |
| 142 | |
| 143 | #[utoipa::path( |
| 144 | post, |
| 145 | path = "/register", |
| 146 | tag = "auth", |
| 147 | request_body = RegisterCredentials, |
| 148 | responses( |
| 149 | (status = 201, description = "Account created, the username was already taken, or an existing person was attached to this school — deliberately indistinguishable. Carries no `id`: on the taken path there is no row to name, so log in to learn who you are", body = RegisterResponse), |
| 150 | (status = 400, description = "Invalid username or password", body = ErrorResponse), |
| 151 | (status = 401, description = "No such school — deliberately the same answer a bad credential gets", body = ErrorResponse), |
| 152 | (status = 403, description = "The school is suspended", body = ErrorResponse), |
| 153 | (status = 429, description = "Too many attempts from this address; see Retry-After", body = ErrorResponse), |
| 154 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 155 | ), |
| 156 | )] |
| 157 | async fn register( |
| 158 | State(st): State<AppState>, |
| 159 | Json(req): Json<RegisterCredentials>, |
| 160 | ) -> Result<(StatusCode, Json<RegisterResponse>), AppError> { |
| 161 | |
| 162 | |
| 163 | |
| 164 | |
| 165 | let school = Slug::try_new(&req.school).map_err(|_| AppError::Unauthorized)?; |
| 166 | let db = st.tenants.get(&school).await?; |
| 167 | let username = Username::try_new(&req.username)?; |
| 168 | |
| 169 | |
| 170 | |
| 171 | if RESERVED_USERNAMES.contains(&username.as_str()) { |
| 172 | return Err(ValidationError::Invalid { |
| 173 | field: "username", |
| 174 | reason: "this username is reserved", |
| 175 | } |
| 176 | .into()); |
| 177 | } |
| 178 | |
| 179 | |
| 180 | |
| 181 | let password = Password::try_new(&req.password)?; |
| 182 | let password_hash = password.hash_async().await?; |
| 183 | |
| 184 | |
| 185 | |
| 186 | |
| 187 | let body = RegisterResponse { |
| 188 | username: username.as_str().to_string(), |
| 189 | role: DomainRole::Student.into(), |
| 190 | }; |
| 191 | |
| 192 | |
| 193 | |
| 194 | |
| 195 | let person = |
| 196 | service::person::create_or_load(&st.db, username.clone(), password_hash.clone()).await?; |
| 197 | if person.get_password_hash().verify_async(&password).await { |
| 198 | |
| 199 | |
| 200 | |
| 201 | |
| 202 | |
| 203 | match service::user::create(&db, username, Some(*person.get_id())).await { |
| 204 | Ok(_) => {} |
| 205 | Err(AppError::Conflict(_)) => { |
| 206 | tracing::info!("register: school username already taken, answering 201"); |
| 207 | } |
| 208 | Err(err) => return Err(err), |
| 209 | } |
| 210 | service::person::link_school(&st.db, person.get_id(), &school).await?; |
| 211 | } else { |
| 212 | tracing::info!("register: username taken, password does not match, answering 201"); |
| 213 | } |
| 214 | Ok((StatusCode::CREATED, Json(body))) |
| 215 | } |
| 216 | |
| 217 | |
| 218 | |
| 219 | |
| 220 | |
| 221 | |
| 222 | #[utoipa::path( |
| 223 | post, |
| 224 | path = "/login", |
| 225 | tag = "auth", |
| 226 | request_body = LoginCredentials, |
| 227 | responses( |
| 228 | (status = 200, description = "Logged in — either straight into the one school (a `UserResponse` and a `<slug>.<token>` cookie), or as a multi-school person (a `{username, schools}` choice list and a `person.<token>` cookie to bind with `POST /auth/school`). Suspended schools appear in neither shape", body = LoginResponse), |
| 229 | (status = 401, description = "Bad credentials — unknown username, wrong password, or no school membership left to enter, all deliberately indistinguishable", body = ErrorResponse), |
| 230 | (status = 403, description = "Every school the person belongs to is suspended", body = ErrorResponse), |
| 231 | (status = 429, description = "Too many attempts from this address; see Retry-After", body = ErrorResponse), |
| 232 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 233 | ), |
| 234 | )] |
| 235 | async fn login( |
| 236 | State(st): State<AppState>, |
| 237 | jar: CookieJar, |
| 238 | Json(req): Json<LoginCredentials>, |
| 239 | ) -> Result<(CookieJar, Json<LoginResponse>), AppError> { |
| 240 | |
| 241 | |
| 242 | |
| 243 | let password = Password::try_new(&req.password).map_err(|_| AppError::Unauthorized)?; |
| 244 | |
| 245 | |
| 246 | |
| 247 | |
| 248 | let person = match service::person::find_by_username(&st.db, req.username.trim()).await? { |
| 249 | |
| 250 | |
| 251 | |
| 252 | Some(person) => { |
| 253 | if !person.get_password_hash().verify_async(&password).await { |
| 254 | return Err(AppError::Unauthorized); |
| 255 | } |
| 256 | person |
| 257 | } |
| 258 | None => { |
| 259 | |
| 260 | |
| 261 | |
| 262 | PasswordHash::verify_decoy_async(&password).await; |
| 263 | return Err(AppError::Unauthorized); |
| 264 | } |
| 265 | }; |
| 266 | |
| 267 | let memberships = service::person::memberships(&st.db, person.get_id()).await?; |
| 268 | let active: Vec<_> = memberships.iter().filter(|m| m.is_active()).collect(); |
| 269 | match active.as_slice() { |
| 270 | |
| 271 | |
| 272 | |
| 273 | [] if memberships.is_empty() => Err(AppError::Unauthorized), |
| 274 | |
| 275 | |
| 276 | [] => Err(AppError::Forbidden("school is suspended")), |
| 277 | [only] => { |
| 278 | let db = st.tenants.get(only.slug()).await?; |
| 279 | |
| 280 | |
| 281 | |
| 282 | let Some(user) = |
| 283 | service::user::find_by_username(&db, person.get_username().as_str()).await? |
| 284 | else { |
| 285 | return Err(AppError::Unauthorized); |
| 286 | }; |
| 287 | |
| 288 | let _ = service::session::purge_expired(&db).await; |
| 289 | let session = service::session::create(&db, user.get_id()).await?; |
| 290 | |
| 291 | |
| 292 | |
| 293 | let cookie = session_cookie( |
| 294 | format!("{}.{}", only.slug(), session.token().as_str()), |
| 295 | st.cookie_secure, |
| 296 | ); |
| 297 | Ok(( |
| 298 | jar.add(cookie), |
| 299 | Json(LoginResponse::LoggedIn(Box::new(UserResponse::new(&user)))), |
| 300 | )) |
| 301 | } |
| 302 | many => { |
| 303 | |
| 304 | |
| 305 | |
| 306 | let session = service::person::create_session(&st.db, person.get_id()).await?; |
| 307 | let cookie = session_cookie( |
| 308 | format!("{PERSON_COOKIE_PREFIX}.{}", session.token().as_str()), |
| 309 | st.cookie_secure, |
| 310 | ); |
| 311 | let schools = many |
| 312 | .iter() |
| 313 | .map(|m| SchoolChoice { |
| 314 | slug: m.slug().as_str().to_string(), |
| 315 | name: m.name().to_string(), |
| 316 | }) |
| 317 | .collect(); |
| 318 | Ok(( |
| 319 | jar.add(cookie), |
| 320 | Json(LoginResponse::ChooseSchool(SchoolChoiceResponse { |
| 321 | username: person.get_username().as_str().to_string(), |
| 322 | schools, |
| 323 | })), |
| 324 | )) |
| 325 | } |
| 326 | } |
| 327 | } |
| 328 | |
| 329 | |
| 330 | |
| 331 | |
| 332 | |
| 333 | #[utoipa::path( |
| 334 | post, |
| 335 | path = "/school", |
| 336 | tag = "auth", |
| 337 | request_body = SelectSchool, |
| 338 | responses( |
| 339 | (status = 200, description = "School selected; the person cookie is replaced by the school session cookie", body = UserResponse), |
| 340 | (status = 401, description = "No person session, or the school is not among the caller's memberships — deliberately indistinguishable (no cookie at all, a school or builder cookie, and a slug the person does not hold all answer the same)", body = ErrorResponse), |
| 341 | (status = 403, description = "The school is suspended", body = ErrorResponse), |
| 342 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 343 | ), |
| 344 | )] |
| 345 | async fn select_school( |
| 346 | State(st): State<AppState>, |
| 347 | jar: CookieJar, |
| 348 | Json(req): Json<SelectSchool>, |
| 349 | ) -> Result<(CookieJar, Json<UserResponse>), AppError> { |
| 350 | |
| 351 | |
| 352 | |
| 353 | let Some((prefix, token)) = jar.get("session").and_then(|c| split_cookie(c.value())) else { |
| 354 | return Err(AppError::Unauthorized); |
| 355 | }; |
| 356 | if prefix != PERSON_COOKIE_PREFIX { |
| 357 | return Err(AppError::Unauthorized); |
| 358 | } |
| 359 | let session = service::person::find_session_by_token(&st.db, token) |
| 360 | .await? |
| 361 | .filter(|s| !s.is_expired()) |
| 362 | .ok_or(AppError::Unauthorized)?; |
| 363 | |
| 364 | |
| 365 | |
| 366 | let slug = Slug::try_new(&req.school).map_err(|_| AppError::Unauthorized)?; |
| 367 | service::person::membership_of(&st.db, session.person(), &slug) |
| 368 | .await? |
| 369 | .ok_or(AppError::Unauthorized)?; |
| 370 | |
| 371 | let db = st.tenants.get(&slug).await?; |
| 372 | let person = service::person::read(&st.db, session.person()) |
| 373 | .await? |
| 374 | .ok_or(AppError::Unauthorized)?; |
| 375 | let Some(user) = service::user::find_by_username(&db, person.get_username().as_str()).await? |
| 376 | else { |
| 377 | return Err(AppError::Unauthorized); |
| 378 | }; |
| 379 | |
| 380 | |
| 381 | |
| 382 | let school_session = service::session::create(&db, user.get_id()).await?; |
| 383 | service::person::delete_session_by_token(&st.db, token).await?; |
| 384 | let cookie = session_cookie( |
| 385 | format!("{slug}.{}", school_session.token().as_str()), |
| 386 | st.cookie_secure, |
| 387 | ); |
| 388 | Ok((jar.add(cookie), Json(UserResponse::new(&user)))) |
| 389 | } |
| 390 | |
| 391 | |
| 392 | |
| 393 | |
| 394 | |
| 395 | pub(crate) fn session_cookie(value: String, secure: bool) -> Cookie<'static> { |
| 396 | Cookie::build(("session", value)) |
| 397 | .path("/") |
| 398 | .http_only(true) |
| 399 | .secure(secure) |
| 400 | |
| 401 | |
| 402 | |
| 403 | .same_site(SameSite::Lax) |
| 404 | .max_age(time::Duration::days(SESSION_DURATION_DAYS)) |
| 405 | .build() |
| 406 | } |
| 407 | |
| 408 | |
| 409 | |
| 410 | #[utoipa::path( |
| 411 | post, |
| 412 | path = "/logout", |
| 413 | tag = "auth", |
| 414 | responses((status = 204, description = "Logged out (no-op without a session)")), |
| 415 | )] |
| 416 | async fn logout( |
| 417 | State(st): State<AppState>, |
| 418 | jar: CookieJar, |
| 419 | ) -> Result<(CookieJar, StatusCode), AppError> { |
| 420 | |
| 421 | |
| 422 | |
| 423 | if let Some((prefix, token)) = jar.get("session").and_then(|c| split_cookie(c.value())) { |
| 424 | if prefix == BUILDER_COOKIE_PREFIX { |
| 425 | crate::service::builder::delete_by_token(&st.db, token).await?; |
| 426 | } else if prefix == PERSON_COOKIE_PREFIX { |
| 427 | service::person::delete_session_by_token(&st.db, token).await?; |
| 428 | } else if let Ok(slug) = Slug::try_new(prefix) |
| 429 | && let Ok(db) = st.tenants.get(&slug).await |
| 430 | { |
| 431 | service::session::delete_by_token(&db, token).await?; |
| 432 | } |
| 433 | } |
| 434 | let jar = jar.remove(Cookie::build(("session", "")).path("/").build()); |
| 435 | Ok((jar, StatusCode::NO_CONTENT)) |
| 436 | } |
| 437 | |
| 438 | |
| 439 | #[utoipa::path( |
| 440 | get, |
| 441 | path = "/me", |
| 442 | tag = "auth", |
| 443 | security(("session_cookie" = [])), |
| 444 | responses( |
| 445 | (status = 200, description = "The current user", body = UserResponse), |
| 446 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 447 | ), |
| 448 | )] |
| 449 | async fn me(CurrentUser(user): CurrentUser) -> Json<UserResponse> { |
| 450 | Json(UserResponse::new(&user)) |
| 451 | } |