forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB08aa13eAhmet Kaan Gümüş2 months ago378 commits

auth.rs268 lines, 12.5 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, 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(), state.db_up.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!(logout))
44 .routes(routes!(me))
45}
46
47#[derive(Deserialize, ToSchema)]
48struct Credentials {
49 /// The school's slug — the name in front of the dot in the session cookie.
50 /// One backend serves many schools, so a username only identifies an
51 /// account together with this.
52 #[schema(example = "demo", min_length = 2, max_length = 32)]
53 school: String,
54 #[schema(example = "ada", min_length = 3, max_length = 32)]
55 username: String,
56 #[schema(example = "correct horse battery", min_length = 6, max_length = 128)]
57 password: String,
58}
59
60/// What `POST /auth/register` answers with — deliberately *not* [`UserResponse`].
61/// It carries only what is true of both outcomes (created, and already-taken):
62/// the echoed username and the role every fresh account gets. No `id`, because
63/// the taken path has no row to name and a fabricated one would be a lie the
64/// client stores; no profile fields, because a fresh account has none. Anything
65/// added here must hold for both paths, or the reply starts leaking existence.
66#[derive(Serialize, ToSchema)]
67struct RegisterResponse {
68 #[schema(example = "ada")]
69 username: String,
70 role: Role,
71}
72
73/// Register a new user account: `{school, username, password}` in, `{username, role}`
74/// back (no `id`; new accounts are `student`). Always `201`, even if the name
75/// was already taken — see "Auth model".
76///
77/// Answers `201` whether or not the username was free: a distinguishable
78/// "already taken" reply lets anyone unauthenticated enumerate every account in
79/// the school, which would make the constant-cost decoy on the login path
80/// pointless. A taken username is *not* re-created or overwritten — only the
81/// reply is uniform. The UX cost (a typo-collision looks like success until the
82/// user tries to log in) is deliberate. Both outcomes return the *same*
83/// [`RegisterResponse`] value, built once before the branch — there is no
84/// per-path body that could drift apart.
85#[utoipa::path(
86 post,
87 path = "/register",
88 tag = "auth",
89 request_body = Credentials,
90 responses(
91 (status = 201, description = "Account created, or the username was already taken — 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),
92 (status = 400, description = "Invalid username or password", body = ErrorResponse),
93 (status = 401, description = "No such school — deliberately the same answer a bad credential gets", body = ErrorResponse),
94 (status = 403, description = "The school is suspended", body = ErrorResponse),
95 (status = 429, description = "Too many attempts from this address; see Retry-After", body = ErrorResponse),
96 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
97 ),
98)]
99async fn register(
100 State(st): State<AppState>,
101 Json(req): Json<Credentials>,
102) -> Result<(StatusCode, Json<RegisterResponse>), AppError> {
103 // The school first: a registration into a school that does not exist, or
104 // one that is suspended, must not reach the (expensive) hashing path — and
105 // an unknown school answers `401` here for the same anti-enumeration reason
106 // login does, rather than confirming which schools this deployment serves.
107 let school = Slug::try_new(&req.school).map_err(|_| AppError::Unauthorized)?;
108 let db = st.tenants.get(&school).await?;
109 let username = Username::try_new(&req.username)?;
110 // Registration-level policy, not a `Username` invariant: these names read
111 // as staff and invite impersonation, but the `ADMIN_USERNAME` bootstrap
112 // must still be able to seed e.g. `admin` through the same newtype.
113 if RESERVED_USERNAMES.contains(&username.as_str()) {
114 return Err(ValidationError::Invalid {
115 field: "username",
116 reason: "this username is reserved",
117 }
118 .into());
119 }
120 // Hash BEFORE the availability check inside the user-create path, never
121 // after: the
122 // ~33ms of argon2 is what makes both outcomes cost the same, so a taken
123 // username can't be spotted by a fast reply. The only work the taken path
124 // skips is the insert itself, orders of magnitude below hashing.
125 let password_hash = Password::try_new(&req.password)?.hash_async().await?;
126 // Built once, before the branch: the created and the taken path answer with
127 // the very same value, so they cannot be told apart by construction rather
128 // than by keeping two field lists in sync. Every fresh account starts as a
129 // student (`service::user::create`), so this holds whichever way the insert goes.
130 let body = RegisterResponse {
131 username: username.as_str().to_string(),
132 role: DomainRole::Student.into(),
133 };
134 match crate::service::user::create(&db, username, password_hash).await {
135 Ok(_) => {}
136 // Taken. Log the real reason server-side; the caller gets the same 201
137 // and the same body, because telling the two apart is the whole thing
138 // we're denying. The account is not re-created or overwritten.
139 Err(AppError::Conflict(_)) => {
140 tracing::info!("register: username already taken, answering 201");
141 }
142 Err(err) => return Err(err),
143 }
144 Ok((StatusCode::CREATED, Json(body)))
145}
146
147/// Log in with school + username + password. Sets a `session` cookie
148/// (`<school>.<token>`) on success.
149#[utoipa::path(
150 post,
151 path = "/login",
152 tag = "auth",
153 request_body = Credentials,
154 responses(
155 (status = 200, description = "Logged in; session cookie set", body = UserResponse),
156 (status = 401, description = "Bad credentials, or no such school — deliberately indistinguishable", body = ErrorResponse),
157 (status = 403, description = "The school is suspended", body = ErrorResponse),
158 (status = 429, description = "Too many attempts from this address; see Retry-After", body = ErrorResponse),
159 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
160 ),
161)]
162async fn login(
163 State(st): State<AppState>,
164 jar: CookieJar,
165 Json(req): Json<Credentials>,
166) -> Result<(CookieJar, Json<UserResponse>), AppError> {
167 // Resolved *before* the argon2 work: a login aimed at a school that does
168 // not exist is a bad credential (`401`, indistinguishable from a bad
169 // password — the school list is not public), and a suspended school is
170 // `403` for every request including this one, so neither should buy an
171 // attacker a hash.
172 let school = Slug::try_new(&req.school).map_err(|_| AppError::Unauthorized)?;
173 let db = st.tenants.get(&school).await?;
174 let password = Password::try_new(&req.password).map_err(|_| AppError::Unauthorized)?;
175 // Usernames are stored trimmed (see `Username::try_new`); trim the lookup
176 // the same way so a padded login attempt matches the canonical name.
177 let user = match crate::service::user::find_by_username(&db, req.username.trim()).await? {
178 // Verification is `.await`ed so argon2 runs on the blocking pool instead
179 // of stalling an async worker; that rules out a match guard, which
180 // cannot await.
181 Some(user) => {
182 if !user.get_password_hash().verify_async(&password).await {
183 return Err(AppError::Unauthorized);
184 }
185 user
186 }
187 None => {
188 // No such user. Still do the argon2 work against a decoy so the reply
189 // takes as long as a real (wrong-password) check — otherwise the
190 // timing difference leaks which usernames exist.
191 PasswordHash::verify_decoy_async(&password).await;
192 return Err(AppError::Unauthorized);
193 }
194 };
195
196 // The caller is genuine; opportunistically drop any expired session rows.
197 let _ = service::session::purge_expired(&db).await;
198
199 let session = service::session::create(&db, user.get_id()).await?;
200 // `<slug>.<token>`: the cookie carries the school, so every later request
201 // finds its database without a second lookup path that could disagree.
202 let cookie = session_cookie(
203 format!("{school}.{}", session.token().as_str()),
204 st.cookie_secure,
205 );
206
207 Ok((jar.add(cookie), Json(UserResponse::new(&user))))
208}
209
210/// The `session` cookie, however it was earned. Shared by school login and the
211/// builder surface (`web::builder`) so the two can never drift apart on path,
212/// flags or lifetime — the value is the only difference between them
213/// (`<slug>.<token>` against `builder.<token>`).
214pub(crate) fn session_cookie(value: String, secure: bool) -> Cookie<'static> {
215 Cookie::build(("session", value))
216 .path("/")
217 .http_only(true)
218 .secure(secure)
219 // Lax is part of the CORS defense: it keeps this cookie off cross-site
220 // requests. Before relaxing toward SameSite=None, first make sure
221 // `cors_layer` (lib.rs) can never mirror origins with credentials on.
222 .same_site(SameSite::Lax)
223 .max_age(time::Duration::days(SESSION_DURATION_DAYS))
224 .build()
225}
226
227/// Log out: revoke the current session (if any) and clear the cookie.
228/// Idempotent — no session required; answers `204` either way.
229#[utoipa::path(
230 post,
231 path = "/logout",
232 tag = "auth",
233 responses((status = 204, description = "Logged out (no-op without a session)")),
234)]
235async fn logout(
236 State(st): State<AppState>,
237 jar: CookieJar,
238) -> Result<(CookieJar, StatusCode), AppError> {
239 // Best-effort: the cookie names its own school, so a logout resolves that
240 // school and deletes the row there. A cookie naming a school that is gone
241 // or suspended still clears below — logging out must never fail.
242 if let Some((prefix, token)) = jar.get("session").and_then(|c| split_cookie(c.value())) {
243 if prefix == BUILDER_COOKIE_PREFIX {
244 crate::service::builder::delete_by_token(&st.db, token).await?;
245 } else if let Ok(slug) = Slug::try_new(prefix)
246 && let Ok(db) = st.tenants.get(&slug).await
247 {
248 service::session::delete_by_token(&db, token).await?;
249 }
250 }
251 let jar = jar.remove(Cookie::build(("session", "")).path("/").build());
252 Ok((jar, StatusCode::NO_CONTENT))
253}
254
255/// Return the currently authenticated user.
256#[utoipa::path(
257 get,
258 path = "/me",
259 tag = "auth",
260 security(("session_cookie" = [])),
261 responses(
262 (status = 200, description = "The current user", body = UserResponse),
263 (status = 401, description = "Not authenticated", body = ErrorResponse),
264 ),
265)]
266async fn me(CurrentUser(user): CurrentUser) -> Json<UserResponse> {
267 Json(UserResponse::new(&user))
268}