forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB0346717Ahmet Kaan Gümüş3 months ago230 commits

auth.rs219 lines, 9.6 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::session::Session;
15use crate::domain::user::{Password, PasswordHash, User, Username};
16use crate::error::{AppError, ErrorResponse, ValidationError};
17use crate::rate_limit::{RateLimitConfig, RateLimiter};
18use crate::state::AppState;
19
20use super::dto::Role;
21use super::{CurrentUser, UserResponse};
22
23pub fn routes(state: &AppState) -> OpenApiRouter<AppState> {
24 // Strict per-IP limit on the two credential endpoints only — the
25 // brute-force and username-enumeration surface. `me` and `logout` stay
26 // outside it: browser frontends poll `me` on every page load, and being
27 // over the auth limit must never block an intentional logout.
28 let rate_limit: &RateLimitConfig = &state.rate_limit;
29 let limiter = RateLimiter::per_minute(rate_limit.auth_per_minute, rate_limit.trust_proxy);
30 // The budget survives a restart — the tier only means something if a
31 // brute-forcer cannot reset it by waiting out a deploy.
32 limiter.share("auth", state.db.clone(), state.db_up.clone());
33 OpenApiRouter::new()
34 .routes(routes!(register))
35 .routes(routes!(login))
36 // `route_layer` wraps only the routes registered above it.
37 .route_layer(middleware::from_fn(move |req: Request, next: Next| {
38 let limiter = limiter.clone();
39 async move { limiter.enforce(req, next).await }
40 }))
41 .routes(routes!(logout))
42 .routes(routes!(me))
43}
44
45#[derive(Deserialize, ToSchema)]
46struct Credentials {
47 #[schema(example = "ada", min_length = 3, max_length = 32)]
48 username: String,
49 #[schema(example = "correct horse battery", min_length = 6, max_length = 128)]
50 password: String,
51}
52
53/// What `POST /auth/register` answers with — deliberately *not* [`UserResponse`].
54/// It carries only what is true of both outcomes (created, and already-taken):
55/// the echoed username and the role every fresh account gets. No `id`, because
56/// the taken path has no row to name and a fabricated one would be a lie the
57/// client stores; no profile fields, because a fresh account has none. Anything
58/// added here must hold for both paths, or the reply starts leaking existence.
59#[derive(Serialize, ToSchema)]
60struct RegisterResponse {
61 #[schema(example = "ada")]
62 username: String,
63 role: Role,
64}
65
66/// Register a new user account.
67///
68/// Answers `201` whether or not the username was free: a distinguishable
69/// "already taken" reply lets anyone unauthenticated enumerate every account in
70/// the school, which would make the constant-cost decoy on the login path
71/// pointless. A taken username is *not* re-created or overwritten — only the
72/// reply is uniform. The UX cost (a typo-collision looks like success until the
73/// user tries to log in) is deliberate. Both outcomes return the *same*
74/// [`RegisterResponse`] value, built once before the branch — there is no
75/// per-path body that could drift apart.
76#[utoipa::path(
77 post,
78 path = "/register",
79 tag = "auth",
80 request_body = Credentials,
81 responses(
82 (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),
83 (status = 400, description = "Invalid username or password", body = ErrorResponse),
84 (status = 429, description = "Too many attempts from this address; see Retry-After", body = ErrorResponse),
85 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
86 ),
87)]
88async fn register(
89 State(st): State<AppState>,
90 Json(req): Json<Credentials>,
91) -> Result<(StatusCode, Json<RegisterResponse>), AppError> {
92 let username = Username::try_new(&req.username)?;
93 // Registration-level policy, not a `Username` invariant: these names read
94 // as staff and invite impersonation, but the `ADMIN_USERNAME` bootstrap
95 // must still be able to seed e.g. `admin` through the same newtype.
96 if RESERVED_USERNAMES.contains(&username.as_str()) {
97 return Err(ValidationError::Invalid {
98 field: "username",
99 reason: "this username is reserved",
100 }
101 .into());
102 }
103 // Hash BEFORE the availability check inside `User::create`, never after: the
104 // ~33ms of argon2 is what makes both outcomes cost the same, so a taken
105 // username can't be spotted by a fast reply. The only work the taken path
106 // skips is the insert itself, orders of magnitude below hashing.
107 let password_hash = Password::try_new(&req.password)?.hash_async().await?;
108 // Built once, before the branch: the created and the taken path answer with
109 // the very same value, so they cannot be told apart by construction rather
110 // than by keeping two field lists in sync. Every fresh account starts as a
111 // student (`User::create`), so this holds whichever way the insert goes.
112 let body = RegisterResponse {
113 username: username.as_str().to_string(),
114 role: DomainRole::Student.into(),
115 };
116 match User::create(username, password_hash, &st.db).await {
117 Ok(_) => {}
118 // Taken. Log the real reason server-side; the caller gets the same 201
119 // and the same body, because telling the two apart is the whole thing
120 // we're denying. The account is not re-created or overwritten.
121 Err(AppError::Conflict(_)) => {
122 tracing::info!("register: username already taken, answering 201");
123 }
124 Err(err) => return Err(err),
125 }
126 Ok((StatusCode::CREATED, Json(body)))
127}
128
129/// Log in with username + password. Sets a `session` cookie on success.
130#[utoipa::path(
131 post,
132 path = "/login",
133 tag = "auth",
134 request_body = Credentials,
135 responses(
136 (status = 200, description = "Logged in; session cookie set", body = UserResponse),
137 (status = 401, description = "Bad credentials", body = ErrorResponse),
138 (status = 429, description = "Too many attempts from this address; see Retry-After", body = ErrorResponse),
139 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
140 ),
141)]
142async fn login(
143 State(st): State<AppState>,
144 jar: CookieJar,
145 Json(req): Json<Credentials>,
146) -> Result<(CookieJar, Json<UserResponse>), AppError> {
147 let password = Password::try_new(&req.password).map_err(|_| AppError::Unauthorized)?;
148 // Usernames are stored trimmed (see `Username::try_new`); trim the lookup
149 // the same way so a padded login attempt matches the canonical name.
150 let user = match User::find_by_username(req.username.trim(), &st.db).await? {
151 // Verification is `.await`ed so argon2 runs on the blocking pool instead
152 // of stalling an async worker; that rules out a match guard, which
153 // cannot await.
154 Some(user) => {
155 if !user.get_password_hash().verify_async(&password).await {
156 return Err(AppError::Unauthorized);
157 }
158 user
159 }
160 None => {
161 // No such user. Still do the argon2 work against a decoy so the reply
162 // takes as long as a real (wrong-password) check — otherwise the
163 // timing difference leaks which usernames exist.
164 PasswordHash::verify_decoy_async(&password).await;
165 return Err(AppError::Unauthorized);
166 }
167 };
168
169 // The caller is genuine; opportunistically drop any expired session rows.
170 let _ = Session::purge_expired(&st.db).await;
171
172 let session = Session::create(user.get_id(), &st.db).await?;
173 let cookie = Cookie::build(("session", session.token().as_str().to_string()))
174 .path("/")
175 .http_only(true)
176 .secure(st.cookie_secure)
177 // Lax is part of the CORS defense: it keeps this cookie off cross-site
178 // requests. Before relaxing toward SameSite=None, first make sure
179 // `cors_layer` (lib.rs) can never mirror origins with credentials on.
180 .same_site(SameSite::Lax)
181 .max_age(time::Duration::days(SESSION_DURATION_DAYS))
182 .build();
183
184 Ok((jar.add(cookie), Json(UserResponse::new(&user))))
185}
186
187/// Log out: revoke the current session (if any) and clear the cookie.
188/// Idempotent — no session required; answers `204` either way.
189#[utoipa::path(
190 post,
191 path = "/logout",
192 tag = "auth",
193 responses((status = 204, description = "Logged out (no-op without a session)")),
194)]
195async fn logout(
196 State(st): State<AppState>,
197 jar: CookieJar,
198) -> Result<(CookieJar, StatusCode), AppError> {
199 if let Some(cookie) = jar.get("session") {
200 Session::delete_by_token(cookie.value(), &st.db).await?;
201 }
202 let jar = jar.remove(Cookie::build(("session", "")).path("/").build());
203 Ok((jar, StatusCode::NO_CONTENT))
204}
205
206/// Return the currently authenticated user.
207#[utoipa::path(
208 get,
209 path = "/me",
210 tag = "auth",
211 security(("session_cookie" = [])),
212 responses(
213 (status = 200, description = "The current user", body = UserResponse),
214 (status = 401, description = "Not authenticated", body = ErrorResponse),
215 ),
216)]
217async fn me(CurrentUser(user): CurrentUser) -> Json<UserResponse> {
218 Json(UserResponse::new(&user))
219}