forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

auth.rs474 lines, 22.1 KiBHistoryRawDownload
1use axum::Json;
2use axum::extract::{Request, State};
3use axum::http::StatusCode;
4use axum::middleware::{self, Next};
5use axum_extra::extract::CookieJar;
6use axum_extra::extract::cookie::{Cookie, SameSite};
7use serde::{Deserialize, Serialize};
8use utoipa::ToSchema;
9use utoipa_axum::router::OpenApiRouter;
10use utoipa_axum::routes;
11
12use crate::constant::{RESERVED_USERNAMES, SESSION_DURATION_DAYS};
13use crate::domain::role::Role as DomainRole;
14use crate::domain::user::{Password, PasswordHash, Username};
15use crate::error::{AppError, ErrorResponse, ValidationError};
16use crate::rate_limit::{RateLimitConfig, RateLimiter};
17use crate::service;
18use crate::state::AppState;
19use crate::tenant::SchoolId;
20
21use super::dto::Role;
22use super::tenant_state::split_cookie;
23use super::{BUILDER_COOKIE_PREFIX, CurrentUser, PERSON_COOKIE_PREFIX, UserResponse};
24
25pub fn routes(state: &AppState) -> OpenApiRouter<AppState> {
26 // Strict per-IP limit on the two credential endpoints only — the
27 // brute-force and username-enumeration surface. `me` and `logout` stay
28 // outside it: browser frontends poll `me` on every page load, and being
29 // over the auth limit must never block an intentional logout.
30 let rate_limit: &RateLimitConfig = &state.rate_limit;
31 let limiter = RateLimiter::per_minute(rate_limit.auth_per_minute, rate_limit.trust_proxy);
32 // The budget survives a restart — the tier only means something if a
33 // brute-forcer cannot reset it by waiting out a deploy.
34 limiter.share("auth", state.db.clone());
35 OpenApiRouter::new()
36 .routes(routes!(register))
37 .routes(routes!(login))
38 // `route_layer` wraps only the routes registered above it.
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!(list_schools))
44 .routes(routes!(select_school))
45 .routes(routes!(logout))
46 .routes(routes!(me))
47}
48
49/// What `POST /auth/register` takes: registration is still aimed at a school.
50/// Split from the login body — a login names no school, it picks the school
51/// afterwards. Serde ignores unknown fields, so a frontend that still sends
52/// `school` to login is merely ignored, not broken.
53#[derive(Deserialize, ToSchema)]
54struct RegisterCredentials {
55 /// The school's uuid — where the new account (or the new membership of an
56 /// existing person) lives. Hyphenated, as `GET /auth/schools` publishes it.
57 #[schema(example = "01a0b0a5-ffb5-7682-8726-7e4ef1a5c68d")]
58 school: String,
59 #[schema(example = "ada", min_length = 3, max_length = 32)]
60 username: String,
61 #[schema(example = "correct horse battery", min_length = 6, max_length = 128)]
62 password: String,
63}
64
65/// What `POST /auth/login` takes. The account is a **person**: one global
66/// username + password, no school — a person with several memberships chooses
67/// one afterwards (`POST /auth/school`).
68#[derive(Deserialize, ToSchema)]
69struct LoginCredentials {
70 #[schema(example = "ada", min_length = 3, max_length = 32)]
71 username: String,
72 #[schema(example = "correct horse battery", min_length = 6, max_length = 128)]
73 password: String,
74}
75
76/// One school offered to a multi-school person.
77#[derive(Serialize, ToSchema)]
78struct SchoolChoice {
79 #[schema(example = "01a0b0a5-ffb5-7682-8726-7e4ef1a5c68d")]
80 id: String,
81 #[schema(example = "Demo")]
82 name: String,
83}
84
85/// What `POST /auth/login` answers when the person belongs to more than one
86/// active school: no `id` (no school is entered yet, so there is no school
87/// row to speak of), and no school cookie. The `schools` list is in name
88/// order and omits suspended schools.
89#[derive(Serialize, ToSchema)]
90struct SchoolChoiceResponse {
91 #[schema(example = "ada")]
92 username: String,
93 schools: Vec<SchoolChoice>,
94}
95
96/// The two login outcomes, told apart by shape: a school was entered (a
97/// [`UserResponse`] and a `<uuid>.<token>` cookie), or one must be chosen (a
98/// [`SchoolChoiceResponse`] and a `person.<token>` cookie). Disjoint by the
99/// `id` field, so an untagged `oneOf` is unambiguous on the wire.
100#[derive(Serialize, ToSchema)]
101#[serde(untagged)]
102enum LoginResponse {
103 LoggedIn(Box<UserResponse>),
104 ChooseSchool(SchoolChoiceResponse),
105}
106
107/// What `POST /auth/school` takes: which of the person's memberships to bind.
108#[derive(Deserialize, ToSchema)]
109struct SelectSchool {
110 #[schema(example = "01a0b0a5-ffb5-7682-8726-7e4ef1a5c68d")]
111 school: String,
112}
113
114/// What `POST /auth/register` answers with — deliberately *not* [`UserResponse`].
115/// It carries only what is true of both outcomes (created, and already-taken):
116/// the echoed username and the role every fresh account gets. No `id`, because
117/// the taken path has no row to name and a fabricated one would be a lie the
118/// client stores; no profile fields, because a fresh account has none. Anything
119/// added here must hold for both paths, or the reply starts leaking existence.
120#[derive(Serialize, ToSchema)]
121struct RegisterResponse {
122 #[schema(example = "ada")]
123 username: String,
124 role: Role,
125}
126
127/// Active schools open for registration. Unauthenticated, like register:
128/// the picker has no session yet. Sorted by name; empty when none are active.
129#[utoipa::path(
130 get,
131 path = "/schools",
132 tag = "auth",
133 responses(
134 (status = 200, description = "Active schools, id and display name, sorted by name", body = Vec<SchoolChoice>),
135 ),
136)]
137async fn list_schools(State(st): State<AppState>) -> Result<Json<Vec<SchoolChoice>>, AppError> {
138 let rows = crate::db::person::list_active_schools(&st.db).await?;
139 Ok(Json(
140 rows.into_iter()
141 .map(|(id, name)| SchoolChoice {
142 id: id.to_string(),
143 name,
144 })
145 .collect(),
146 ))
147}
148
149/// Register a new user account, or attach an existing person to one more
150/// school: `{school, username, password}` in, `{username, role}` back (no
151/// `id`; new accounts are `student`). Always `201` — see below.
152///
153/// The account is a **person**: a global username in the control plane that
154/// can hold memberships in many schools. Registering a username that is new
155/// everywhere creates the person and the school's `app_user` (student). A
156/// person who already exists is attached to this school too — but only when
157/// the password matches the person credential; a wrong password is the same
158/// `201` and joins nothing.
159///
160/// Every outcome answers `201` with the *same* body, built once before the
161/// branch: a distinguishable "already taken" reply would let anyone
162/// unauthenticated enumerate accounts, making the login decoy pointless.
163/// The UX cost (a typo-collision looks like success until the user tries to
164/// log in) is deliberate. The hash comes before any lookup, so every path
165/// pays the same argon2 bill first.
166#[utoipa::path(
167 post,
168 path = "/register",
169 tag = "auth",
170 request_body = RegisterCredentials,
171 responses(
172 (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),
173 (status = 400, description = "Invalid username or password", body = ErrorResponse),
174 (status = 401, description = "No such school — deliberately the same answer a bad credential gets", body = ErrorResponse),
175 (status = 403, description = "The school is suspended", body = ErrorResponse),
176 (status = 429, description = "Too many attempts from this address; see Retry-After", body = ErrorResponse),
177 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
178 ),
179)]
180async fn register(
181 State(st): State<AppState>,
182 Json(req): Json<RegisterCredentials>,
183) -> Result<(StatusCode, Json<RegisterResponse>), AppError> {
184 // The school first: a registration into a school that does not exist, or
185 // one that is suspended, must not reach the (expensive) hashing path — and
186 // an unknown school answers `401` here for the same anti-enumeration reason
187 // login does, rather than confirming which schools this deployment serves.
188 let school = SchoolId::try_parse(&req.school).map_err(|_| AppError::Unauthorized)?;
189 let db = st.tenants.get(&school).await?;
190 let username = Username::try_new(&req.username)?;
191 // Registration-level policy, not a `Username` invariant: these names read
192 // as staff and invite impersonation, but the `ADMIN_USERNAME` bootstrap
193 // must still be able to seed e.g. `admin` through the same newtype.
194 if RESERVED_USERNAMES.contains(&username.as_str()) {
195 return Err(ValidationError::Invalid {
196 field: "username",
197 reason: "this username is reserved",
198 }
199 .into());
200 }
201 // Hash BEFORE any lookup, never after: the ~33ms of argon2 is what makes
202 // every outcome cost the same up front, so taken-vs-free can't be spotted
203 // by a fast reply.
204 let password = Password::try_new(&req.password)?;
205 let password_hash = password.hash_async().await?;
206 // Built once, before the branch: every path answers with the very same
207 // value, so they cannot be told apart by construction rather than by
208 // keeping two field lists in sync. Every fresh account starts as a
209 // student, so this holds whichever way the writes go.
210 let body = RegisterResponse {
211 username: username.as_str().to_string(),
212 role: DomainRole::Student.into(),
213 };
214
215 // Person half (control database): create the global account, or meet the
216 // one already standing. The stored credential is never overwritten here —
217 // the caller has not proven they know it until the verify below.
218 let person =
219 service::person::create_or_load(&st.db, username.clone(), password_hash.clone()).await?;
220 if person.get_password_hash().verify_async(&password).await {
221 // School half, in the cross-database order `app_user` then
222 // membership (no distributed transaction spans the two databases, so
223 // each half is idempotent and a retry after a torn pair completes
224 // it). A taken school username means the person is already a member
225 // — the same 201.
226 match service::user::create(&db, username, Some(*person.get_id())).await {
227 Ok(_) => {}
228 Err(AppError::Conflict(_)) => {
229 tracing::info!("register: school username already taken, answering 201");
230 }
231 Err(err) => return Err(err),
232 }
233 service::person::link_school(&st.db, person.get_id(), &school).await?;
234 } else {
235 tracing::info!("register: username taken, password does not match, answering 201");
236 }
237 Ok((StatusCode::CREATED, Json(body)))
238}
239
240/// Log in with username + password — no school. Sets a `session` cookie on
241/// success: exactly one active membership enters that school right away
242/// (`<uuid>.<token>` and the full [`UserResponse`], unchanged for
243/// single-school clients), several answer a [`SchoolChoiceResponse`] with a
244/// `person.<token>` cookie that `POST /auth/school` binds.
245#[utoipa::path(
246 post,
247 path = "/login",
248 tag = "auth",
249 request_body = LoginCredentials,
250 responses(
251 (status = 200, description = "Logged in — either straight into the one school (a `UserResponse` and a `<uuid>.<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),
252 (status = 401, description = "Bad credentials — unknown username, wrong password, or no school membership left to enter, all deliberately indistinguishable", body = ErrorResponse),
253 (status = 403, description = "Every school the person belongs to is suspended", body = ErrorResponse),
254 (status = 429, description = "Too many attempts from this address; see Retry-After", body = ErrorResponse),
255 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
256 ),
257)]
258async fn login(
259 State(st): State<AppState>,
260 jar: CookieJar,
261 Json(req): Json<LoginCredentials>,
262) -> Result<(CookieJar, Json<LoginResponse>), AppError> {
263 // A malformed password is a bad credential (`401`, not a `422`): the body
264 // parsed, the credential did not. Same answer an unknown username gets —
265 // neither may help a caller tell them apart.
266 let password = Password::try_new(&req.password).map_err(|_| AppError::Unauthorized)?;
267 // The account is a person in the control database; a school is picked
268 // after login, not named by it. Usernames are stored trimmed (see
269 // `Username::try_new`); trim the lookup the same way so a padded attempt
270 // matches the canonical name.
271 let person = match service::person::find_by_username(&st.db, req.username.trim()).await? {
272 // Verification is `.await`ed so argon2 runs on the blocking pool instead
273 // of stalling an async worker; that rules out a match guard, which
274 // cannot await.
275 Some(person) => {
276 if !person.get_password_hash().verify_async(&password).await {
277 return Err(AppError::Unauthorized);
278 }
279 person
280 }
281 None => {
282 // No such person. Still do the argon2 work against a decoy so the reply
283 // takes as long as a real (wrong-password) check — otherwise the
284 // timing difference leaks which usernames exist.
285 PasswordHash::verify_decoy_async(&password).await;
286 return Err(AppError::Unauthorized);
287 }
288 };
289
290 let memberships = service::person::memberships(&st.db, person.get_id()).await?;
291 let active: Vec<_> = memberships.iter().filter(|m| m.is_active()).collect();
292 match active.as_slice() {
293 // A person with no membership cannot enter anything: the same `401`
294 // a bad credential gets, so a register that created only the person
295 // half (a torn cross-database pair) is not a signal either.
296 [] if memberships.is_empty() => Err(AppError::Unauthorized),
297 // Every membership sits in a suspended school: closed to its users,
298 // including this one.
299 [] => Err(AppError::Forbidden("school is suspended")),
300 [only] => {
301 let db = st.tenants.get(&only.id()).await?;
302 // The school-side row the session binds to. A membership without
303 // its `app_user` (a torn create) refuses like a bad credential
304 // rather than confirm anything.
305 let Some(user) =
306 service::user::find_by_username(&db, person.get_username().as_str()).await?
307 else {
308 return Err(AppError::Unauthorized);
309 };
310 // The caller is genuine; opportunistically drop expired session rows.
311 let _ = service::session::purge_expired(&db).await;
312 let session = service::session::create(&db, user.get_id()).await?;
313 // `<uuid>.<token>`: the cookie carries the school, so every later
314 // request finds its database without a second lookup path that
315 // could disagree.
316 let cookie = session_cookie(
317 format!("{}.{}", only.id(), session.token().as_str()),
318 st.cookie_secure,
319 );
320 Ok((
321 jar.add(cookie),
322 Json(LoginResponse::LoggedIn(Box::new(UserResponse::new(&user)))),
323 ))
324 }
325 many => {
326 // Not entering any school yet: the `person.<token>` cookie is the
327 // not-chosen state, and `POST /auth/school` exchanges it. The
328 // list carries id and display name, suspended schools omitted.
329 let session = service::person::create_session(&st.db, person.get_id()).await?;
330 let cookie = session_cookie(
331 format!("{PERSON_COOKIE_PREFIX}.{}", session.token().as_str()),
332 st.cookie_secure,
333 );
334 let schools = many
335 .iter()
336 .map(|m| SchoolChoice {
337 id: m.id().as_str(),
338 name: m.name().to_string(),
339 })
340 .collect();
341 Ok((
342 jar.add(cookie),
343 Json(LoginResponse::ChooseSchool(SchoolChoiceResponse {
344 username: person.get_username().as_str().to_string(),
345 schools,
346 })),
347 ))
348 }
349 }
350}
351
352/// Bind a `person.<token>` session to one of the person's schools: the
353/// cookie is replaced with that school's own `<uuid>.<token>` and the person
354/// session is revoked. Deliberately outside the credential rate-limit tier —
355/// this is not a credential guess, and it requires a session cookie already.
356#[utoipa::path(
357 post,
358 path = "/school",
359 tag = "auth",
360 request_body = SelectSchool,
361 responses(
362 (status = 200, description = "School selected; the person cookie is replaced by the school session cookie", body = UserResponse),
363 (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 an id the person does not hold all answer the same)", body = ErrorResponse),
364 (status = 403, description = "The school is suspended", body = ErrorResponse),
365 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
366 ),
367)]
368async fn select_school(
369 State(st): State<AppState>,
370 jar: CookieJar,
371 Json(req): Json<SelectSchool>,
372) -> Result<(CookieJar, Json<UserResponse>), AppError> {
373 // Only a person cookie binds a school: a school cookie already names its
374 // school (switching is logout + login again), and a builder cookie names
375 // no school at all — the same `401` every school surface gives them.
376 let Some((prefix, token)) = jar.get("session").and_then(|c| split_cookie(c.value())) else {
377 return Err(AppError::Unauthorized);
378 };
379 if prefix != PERSON_COOKIE_PREFIX {
380 return Err(AppError::Unauthorized);
381 }
382 let session = service::person::find_session_by_token(&st.db, token)
383 .await?
384 .filter(|s| !s.is_expired())
385 .ok_or(AppError::Unauthorized)?;
386 // Membership required, and an id that names nothing is the same refusal
387 // as one the person does not hold — the list login already gave them is
388 // not a directory of the deployment.
389 let id = SchoolId::try_parse(&req.school).map_err(|_| AppError::Unauthorized)?;
390 service::person::membership_of(&st.db, session.person(), &id)
391 .await?
392 .ok_or(AppError::Unauthorized)?;
393 // Suspended → `403` here, like on every school door.
394 let db = st.tenants.get(&id).await?;
395 let person = service::person::read(&st.db, session.person())
396 .await?
397 .ok_or(AppError::Unauthorized)?;
398 let Some(user) = service::user::find_by_username(&db, person.get_username().as_str()).await?
399 else {
400 return Err(AppError::Unauthorized);
401 };
402 // The school session first, then the person session goes: if the create
403 // fails the person cookie still works and the same request can be
404 // retried — a revoked cookie with no school session is a lockout.
405 let school_session = service::session::create(&db, user.get_id()).await?;
406 service::person::delete_session_by_token(&st.db, token).await?;
407 let cookie = session_cookie(
408 format!("{id}.{}", school_session.token().as_str()),
409 st.cookie_secure,
410 );
411 Ok((jar.add(cookie), Json(UserResponse::new(&user))))
412}
413
414/// The `session` cookie, however it was earned. Shared by school login and the
415/// builder surface (`web::builder`) so the two can never drift apart on path,
416/// flags or lifetime — the value is the only difference between them
417/// (`<uuid>.<token>` against `builder.<token>`).
418pub(crate) fn session_cookie(value: String, secure: bool) -> Cookie<'static> {
419 Cookie::build(("session", value))
420 .path("/")
421 .http_only(true)
422 .secure(secure)
423 // Lax is part of the CORS defense: it keeps this cookie off cross-site
424 // requests. Before relaxing toward SameSite=None, first make sure
425 // `cors_layer` (lib.rs) can never mirror origins with credentials on.
426 .same_site(SameSite::Lax)
427 .max_age(time::Duration::days(SESSION_DURATION_DAYS))
428 .build()
429}
430
431/// Log out: revoke the current session (if any) and clear the cookie.
432/// Idempotent — no session required; answers `204` either way.
433#[utoipa::path(
434 post,
435 path = "/logout",
436 tag = "auth",
437 responses((status = 204, description = "Logged out (no-op without a session)")),
438)]
439async fn logout(
440 State(st): State<AppState>,
441 jar: CookieJar,
442) -> Result<(CookieJar, StatusCode), AppError> {
443 // Best-effort: the cookie names its own session kind, so a logout
444 // resolves it and deletes the row there. A cookie naming a school that is
445 // gone or suspended still clears below — logging out must never fail.
446 if let Some((prefix, token)) = jar.get("session").and_then(|c| split_cookie(c.value())) {
447 if prefix == BUILDER_COOKIE_PREFIX {
448 crate::service::builder::delete_by_token(&st.db, token).await?;
449 } else if prefix == PERSON_COOKIE_PREFIX {
450 service::person::delete_session_by_token(&st.db, token).await?;
451 } else if let Ok(id) = SchoolId::try_parse(prefix)
452 && let Ok(db) = st.tenants.get(&id).await
453 {
454 service::session::delete_by_token(&db, token).await?;
455 }
456 }
457 let jar = jar.remove(Cookie::build(("session", "")).path("/").build());
458 Ok((jar, StatusCode::NO_CONTENT))
459}
460
461/// Return the currently authenticated user.
462#[utoipa::path(
463 get,
464 path = "/me",
465 tag = "auth",
466 security(("session_cookie" = [])),
467 responses(
468 (status = 200, description = "The current user", body = UserResponse),
469 (status = 401, description = "Not authenticated", body = ErrorResponse),
470 ),
471)]
472async fn me(CurrentUser(user): CurrentUser) -> Json<UserResponse> {
473 Json(UserResponse::new(&user))
474}