forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB69d4295Ahmet Kaan Gümüş2 months ago536 commits

auth.rs451 lines, 21.3 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::Slug;
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!(select_school))
44 .routes(routes!(logout))
45 .routes(routes!(me))
46}
47
48/// What `POST /auth/register` takes: registration is still aimed at a school.
49/// Split from the login body — a login names no school, it picks the school
50/// afterwards. Serde ignores unknown fields, so a frontend that still sends
51/// `school` to login is merely ignored, not broken.
52#[derive(Deserialize, ToSchema)]
53struct RegisterCredentials {
54 /// The school's slug — where the new account (or the new membership of an
55 /// existing person) lives.
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/// What `POST /auth/login` takes. The account is a **person**: one global
65/// username + password, no school — a person with several memberships chooses
66/// one afterwards (`POST /auth/school`).
67#[derive(Deserialize, ToSchema)]
68struct 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/// One school offered to a multi-school person.
76#[derive(Serialize, ToSchema)]
77struct SchoolChoice {
78 #[schema(example = "demo")]
79 slug: String,
80 #[schema(example = "Demo")]
81 name: String,
82}
83
84/// What `POST /auth/login` answers when the person belongs to more than one
85/// active school: no `id` (no school is entered yet, so there is no school
86/// row to speak of), and no school cookie. The `schools` list is in slug
87/// order and omits suspended schools.
88#[derive(Serialize, ToSchema)]
89struct SchoolChoiceResponse {
90 #[schema(example = "ada")]
91 username: String,
92 schools: Vec<SchoolChoice>,
93}
94
95/// The two login outcomes, told apart by shape: a school was entered (a
96/// [`UserResponse`] and a `<slug>.<token>` cookie), or one must be chosen (a
97/// [`SchoolChoiceResponse`] and a `person.<token>` cookie). Disjoint by the
98/// `id` field, so an untagged `oneOf` is unambiguous on the wire.
99#[derive(Serialize, ToSchema)]
100#[serde(untagged)]
101enum LoginResponse {
102 LoggedIn(Box<UserResponse>),
103 ChooseSchool(SchoolChoiceResponse),
104}
105
106/// What `POST /auth/school` takes: which of the person's memberships to bind.
107#[derive(Deserialize, ToSchema)]
108struct SelectSchool {
109 #[schema(example = "demo", min_length = 2, max_length = 32)]
110 school: String,
111}
112
113/// What `POST /auth/register` answers with — deliberately *not* [`UserResponse`].
114/// It carries only what is true of both outcomes (created, and already-taken):
115/// the echoed username and the role every fresh account gets. No `id`, because
116/// the taken path has no row to name and a fabricated one would be a lie the
117/// client stores; no profile fields, because a fresh account has none. Anything
118/// added here must hold for both paths, or the reply starts leaking existence.
119#[derive(Serialize, ToSchema)]
120struct RegisterResponse {
121 #[schema(example = "ada")]
122 username: String,
123 role: Role,
124}
125
126/// Register a new user account, or attach an existing person to one more
127/// school: `{school, username, password}` in, `{username, role}` back (no
128/// `id`; new accounts are `student`). Always `201` — see below.
129///
130/// The account is a **person**: a global username in the control plane that
131/// can hold memberships in many schools. Registering a username that is new
132/// everywhere creates the person and the school's `app_user` (student). A
133/// person who already exists is attached to this school too — but only when
134/// the password matches the person credential; a wrong password is the same
135/// `201` and joins nothing.
136///
137/// Every outcome answers `201` with the *same* body, built once before the
138/// branch: a distinguishable "already taken" reply would let anyone
139/// unauthenticated enumerate accounts, making the login decoy pointless.
140/// The UX cost (a typo-collision looks like success until the user tries to
141/// log in) is deliberate. The hash comes before any lookup, so every path
142/// pays the same argon2 bill first.
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)]
157async fn register(
158 State(st): State<AppState>,
159 Json(req): Json<RegisterCredentials>,
160) -> Result<(StatusCode, Json<RegisterResponse>), AppError> {
161 // The school first: a registration into a school that does not exist, or
162 // one that is suspended, must not reach the (expensive) hashing path — and
163 // an unknown school answers `401` here for the same anti-enumeration reason
164 // login does, rather than confirming which schools this deployment serves.
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 // Registration-level policy, not a `Username` invariant: these names read
169 // as staff and invite impersonation, but the `ADMIN_USERNAME` bootstrap
170 // must still be able to seed e.g. `admin` through the same newtype.
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 // Hash BEFORE any lookup, never after: the ~33ms of argon2 is what makes
179 // every outcome cost the same up front, so taken-vs-free can't be spotted
180 // by a fast reply.
181 let password = Password::try_new(&req.password)?;
182 let password_hash = password.hash_async().await?;
183 // Built once, before the branch: every path answers with the very same
184 // value, so they cannot be told apart by construction rather than by
185 // keeping two field lists in sync. Every fresh account starts as a
186 // student, so this holds whichever way the writes go.
187 let body = RegisterResponse {
188 username: username.as_str().to_string(),
189 role: DomainRole::Student.into(),
190 };
191
192 // Person half (control database): create the global account, or meet the
193 // one already standing. The stored credential is never overwritten here —
194 // the caller has not proven they know it until the verify below.
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 // School half, in the cross-database order `app_user` then
199 // membership (no distributed transaction spans the two databases, so
200 // each half is idempotent and a retry after a torn pair completes
201 // it). A taken school username means the person is already a member
202 // — the same 201.
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/// Log in with username + password — no school. Sets a `session` cookie on
218/// success: exactly one active membership enters that school right away
219/// (`<slug>.<token>` and the full [`UserResponse`], unchanged for
220/// single-school clients), several answer a [`SchoolChoiceResponse`] with a
221/// `person.<token>` cookie that `POST /auth/school` binds.
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)]
235async fn login(
236 State(st): State<AppState>,
237 jar: CookieJar,
238 Json(req): Json<LoginCredentials>,
239) -> Result<(CookieJar, Json<LoginResponse>), AppError> {
240 // A malformed password is a bad credential (`401`, not a `422`): the body
241 // parsed, the credential did not. Same answer an unknown username gets —
242 // neither may help a caller tell them apart.
243 let password = Password::try_new(&req.password).map_err(|_| AppError::Unauthorized)?;
244 // The account is a person in the control database; a school is picked
245 // after login, not named by it. Usernames are stored trimmed (see
246 // `Username::try_new`); trim the lookup the same way so a padded attempt
247 // matches the canonical name.
248 let person = match service::person::find_by_username(&st.db, req.username.trim()).await? {
249 // Verification is `.await`ed so argon2 runs on the blocking pool instead
250 // of stalling an async worker; that rules out a match guard, which
251 // cannot await.
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 // No such person. Still do the argon2 work against a decoy so the reply
260 // takes as long as a real (wrong-password) check — otherwise the
261 // timing difference leaks which usernames exist.
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 // A person with no membership cannot enter anything: the same `401`
271 // a bad credential gets, so a register that created only the person
272 // half (a torn cross-database pair) is not a signal either.
273 [] if memberships.is_empty() => Err(AppError::Unauthorized),
274 // Every membership sits in a suspended school: closed to its users,
275 // including this one.
276 [] => Err(AppError::Forbidden("school is suspended")),
277 [only] => {
278 let db = st.tenants.get(only.slug()).await?;
279 // The school-side row the session binds to. A membership without
280 // its `app_user` (a torn create) refuses like a bad credential
281 // rather than confirm anything.
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 // The caller is genuine; opportunistically drop expired session rows.
288 let _ = service::session::purge_expired(&db).await;
289 let session = service::session::create(&db, user.get_id()).await?;
290 // `<slug>.<token>`: the cookie carries the school, so every later
291 // request finds its database without a second lookup path that
292 // could disagree.
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 // Not entering any school yet: the `person.<token>` cookie is the
304 // not-chosen state, and `POST /auth/school` exchanges it. The
305 // list carries slug and display name, suspended schools omitted.
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/// Bind a `person.<token>` session to one of the person's schools: the
330/// cookie is replaced with that school's own `<slug>.<token>` and the person
331/// session is revoked. Deliberately outside the credential rate-limit tier —
332/// this is not a credential guess, and it requires a session cookie already.
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)]
345async fn select_school(
346 State(st): State<AppState>,
347 jar: CookieJar,
348 Json(req): Json<SelectSchool>,
349) -> Result<(CookieJar, Json<UserResponse>), AppError> {
350 // Only a person cookie binds a school: a school cookie already names its
351 // school (switching is logout + login again), and a builder cookie names
352 // no school at all — the same `401` every school surface gives them.
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 // Membership required, and a slug that names nothing is the same refusal
364 // as one the person does not hold — the list login already gave them is
365 // not a directory of the deployment.
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 // Suspended → `403` here, like on every school door.
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 // The school session first, then the person session goes: if the create
380 // fails the person cookie still works and the same request can be
381 // retried — a revoked cookie with no school session is a lockout.
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/// The `session` cookie, however it was earned. Shared by school login and the
392/// builder surface (`web::builder`) so the two can never drift apart on path,
393/// flags or lifetime — the value is the only difference between them
394/// (`<slug>.<token>` against `builder.<token>`).
395pub(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 // Lax is part of the CORS defense: it keeps this cookie off cross-site
401 // requests. Before relaxing toward SameSite=None, first make sure
402 // `cors_layer` (lib.rs) can never mirror origins with credentials on.
403 .same_site(SameSite::Lax)
404 .max_age(time::Duration::days(SESSION_DURATION_DAYS))
405 .build()
406}
407
408/// Log out: revoke the current session (if any) and clear the cookie.
409/// Idempotent — no session required; answers `204` either way.
410#[utoipa::path(
411 post,
412 path = "/logout",
413 tag = "auth",
414 responses((status = 204, description = "Logged out (no-op without a session)")),
415)]
416async fn logout(
417 State(st): State<AppState>,
418 jar: CookieJar,
419) -> Result<(CookieJar, StatusCode), AppError> {
420 // Best-effort: the cookie names its own session kind, so a logout
421 // resolves it and deletes the row there. A cookie naming a school that is
422 // gone or suspended still clears below — logging out must never fail.
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/// Return the currently authenticated user.
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)]
449async fn me(CurrentUser(user): CurrentUser) -> Json<UserResponse> {
450 Json(UserResponse::new(&user))
451}