1use std::sync::Arc;
2
3use axum::{
4 Extension,
5 body::Body,
6 extract::State,
7 http::{HeaderValue, Request, StatusCode, header},
8 middleware::Next,
9 response::{IntoResponse, Response},
10};
11
12use axum_extra::extract::{CookieJar, cookie::Cookie};
13use serde::{Deserialize, Serialize};
14
15use crate::{
16 AppState,
17 model::User,
18 response::{UNAVAILABLE_MESSAGE, WebError},
19};
20use redis::AsyncCommands;
21use server::command::user::{Account, Refusal};
22
23#[derive(Debug, Serialize, Deserialize, Clone)]
24pub struct JWTAuthMiddleware {
25 pub user: User,
26 pub access_token_uuid: uuid::Uuid,
27 pub refreshed: bool,
30}
31
32type AuthError = WebError;
33
34fn unavailable_err(e: &dyn std::fmt::Display) -> AuthError {
39 tracing::error!("session store error: {e}");
40 WebError::unavailable(UNAVAILABLE_MESSAGE)
41}
42
43fn extract_access_token(cookie_jar: &CookieJar, req: &Request<Body>) -> Option<String> {
44 cookie_jar
45 .get("access_token")
46 .map(|cookie| cookie.value().to_string())
47 .or_else(|| {
48 req.headers()
49 .get(header::AUTHORIZATION)
50 .and_then(|auth_header| auth_header.to_str().ok())
51 .and_then(|auth_value| {
52 auth_value
53 .strip_prefix("Bearer ")
54 .map(std::borrow::ToOwned::to_owned)
55 })
56 })
57}
58
59enum Access {
61 Valid(uuid::Uuid, uuid::Uuid),
62 Absent,
64 Unavailable,
69}
70
71async fn resolve_access(data: &Arc<AppState>, access_token: Option<&str>) -> Access {
72 let Some(token_str) = access_token else {
73 return Access::Absent;
74 };
75 let details = match crate::auth_keys::verify(token_str, crate::token::TokenType::Access).await {
76 Ok(Some(details)) => details,
77 Ok(None) => return Access::Absent,
78 Err(_) => return Access::Unavailable,
79 };
80 let Ok(mut redis) = data.redis_client.get_multiplexed_async_connection().await else {
81 return Access::Unavailable;
82 };
83 let Ok(user_id_str) = redis
86 .get::<_, Option<String>>(details.token_uuid.to_string())
87 .await
88 else {
89 return Access::Unavailable;
90 };
91 let Some(user_id) = user_id_str.and_then(|id| uuid::Uuid::parse_str(&id).ok()) else {
92 return Access::Absent;
93 };
94 if user_id != details.user_id {
98 return Access::Absent;
99 }
100 Access::Valid(user_id, details.token_uuid)
101}
102
103struct RefreshOutcome {
104 account: Account,
105 access_token_uuid: uuid::Uuid,
106 set_cookies: Vec<HeaderValue>,
107}
108
109impl RefreshOutcome {
110 fn shared(account: Account) -> Self {
114 Self {
115 account,
116 access_token_uuid: uuid::Uuid::nil(),
117 set_cookies: Vec::new(),
118 }
119 }
120}
121
122pub(crate) const REUSE_GRACE_SECS: u64 = 30;
127
128pub(crate) struct Rotation {
130 pub token_uuid: uuid::Uuid,
132 pub owner: uuid::Uuid,
134 pub successor: uuid::Uuid,
136 pub access_uuid: uuid::Uuid,
138 pub superseded: Option<uuid::Uuid>,
142 pub refresh_ttl: u64,
143 pub access_ttl: u64,
144 pub grace: u64,
145}
146
147#[derive(Debug, PartialEq, Eq)]
149pub(crate) enum Redemption {
150 Rotated,
152 Reused,
154 Refused,
156}
157
158impl Redemption {
159 fn from_script(code: i64) -> Self {
160 match code {
161 1 => Self::Rotated,
162 2 => Self::Reused,
163 _ => Self::Refused,
164 }
165 }
166}
167
168pub(crate) async fn rotate_refresh(
176 redis: &mut redis::aio::MultiplexedConnection,
177 rotation: &Rotation,
178) -> Result<Redemption, AuthError> {
179 let script = redis::Script::new(
180 r"local prefix = 'rotated:' .. ARGV[1] .. ':'
181 local current = redis.call('GET', KEYS[1])
182 if current and string.sub(current, 1, #prefix) == prefix then return 2 end
183 if current ~= ARGV[1] then return 0 end
184 redis.call('SETEX', KEYS[2], ARGV[2], ARGV[1])
185 redis.call('SETEX', KEYS[3], ARGV[3], ARGV[1])
186 local grace = tonumber(ARGV[4]) * 1000
187 local function capped(key)
188 local pttl = redis.call('PTTL', key)
189 if pttl == -1 or pttl > grace then return grace end
190 return math.max(pttl, 1)
191 end
192 if KEYS[4] and redis.call('EXISTS', KEYS[4]) == 1 then
193 redis.call('PEXPIRE', KEYS[4], capped(KEYS[4]))
194 end
195 redis.call('SET', KEYS[1], prefix .. KEYS[2] .. ':' .. KEYS[3], 'PX', capped(KEYS[1]))
196 return 1",
197 );
198 let mut invocation = script.prepare_invoke();
199 invocation
200 .key(rotation.token_uuid.to_string())
201 .key(rotation.successor.to_string())
202 .key(rotation.access_uuid.to_string());
203 if let Some(superseded) = rotation.superseded {
204 invocation.key(superseded.to_string());
205 }
206 invocation
207 .arg(rotation.owner.to_string())
208 .arg(rotation.refresh_ttl)
209 .arg(rotation.access_ttl)
210 .arg(rotation.grace)
211 .invoke_async::<i64>(redis)
212 .await
213 .map(Redemption::from_script)
214 .map_err(|e| unavailable_err(&e))
215}
216
217pub(crate) async fn end_session(
221 redis: &mut redis::aio::MultiplexedConnection,
222 refresh: uuid::Uuid,
223 access: uuid::Uuid,
224 owner: uuid::Uuid,
225) -> Result<(), AuthError> {
226 let script = redis::Script::new(
227 r"local prefix = 'rotated:' .. ARGV[1] .. ':'
228 local current = redis.call('GET', KEYS[1])
229 if current and string.sub(current, 1, #prefix) == prefix then
230 for successor in string.gmatch(string.sub(current, #prefix + 1), '[^:]+') do
231 redis.call('DEL', successor)
232 end
233 end
234 return redis.call('DEL', KEYS[1], KEYS[2])",
235 );
236 script
237 .key(refresh.to_string())
238 .key(access.to_string())
239 .arg(owner.to_string())
240 .invoke_async::<()>(redis)
241 .await
242 .map_err(|e| unavailable_err(&e))
243}
244
245async fn fetch_account(user_id: uuid::Uuid) -> Result<Account, AuthError> {
251 server::command::user::fetch_account(user_id)
252 .await
253 .map_err(WebError::from)?
254 .ok_or_else(|| WebError::unauthorized("The user belonging to this token no longer exists"))
255}
256
257fn refuse(refusal: Option<Refusal>) -> Result<(), AuthError> {
259 match refusal {
260 Some(Refusal::Disabled) => Err(WebError::forbidden("The user is not verified yet")),
261 Some(Refusal::Quarantined) => Err(WebError::unavailable(
262 "This account is undergoing maintenance and is temporarily unavailable",
263 )),
264 None => Ok(()),
265 }
266}
267
268pub(crate) fn mint_failed(e: crate::auth_keys::MintError) -> AuthError {
270 match e.status() {
271 StatusCode::SERVICE_UNAVAILABLE => unavailable_err(&e),
272 _ => WebError::internal("Token minting failed", e),
273 }
274}
275
276async fn try_refresh_session(
277 data: &Arc<AppState>,
278 cookie_jar: &CookieJar,
279) -> Result<RefreshOutcome, AuthError> {
280 let refresh_token = cookie_jar
281 .get("refresh_token")
282 .map(|c| c.value().to_string())
283 .ok_or_else(|| WebError::unauthorized("You are not logged in, please provide token"))?;
284
285 let refresh_details =
286 match crate::auth_keys::verify(&refresh_token, crate::token::TokenType::Refresh).await {
287 Ok(Some(details)) => details,
288 Ok(None) => {
289 return Err(WebError::unauthorized(
290 "Token is invalid or session has expired",
291 ));
292 }
293 Err(e) => return Err(unavailable_err(&e)),
294 };
295
296 let mut redis_client = data
297 .redis_client
298 .get_multiplexed_async_connection()
299 .await
300 .map_err(|e| unavailable_err(&e))?;
301
302 let user_id = refresh_details.user_id;
307 let account = fetch_account(user_id).await?;
308 refuse(account.refusal)?;
309
310 let access_details = crate::auth_keys::mint(
311 user_id,
312 data.conf.access_token_max_age,
313 crate::token::TokenType::Access,
314 refresh_details.generation,
315 )
316 .await
317 .map_err(mint_failed)?;
318 let new_refresh_details = crate::auth_keys::mint(
319 user_id,
320 data.conf.refresh_token_max_age,
321 crate::token::TokenType::Refresh,
322 refresh_details.generation,
323 )
324 .await
325 .map_err(mint_failed)?;
326
327 let redemption = rotate_refresh(
328 &mut redis_client,
329 &Rotation {
330 token_uuid: refresh_details.token_uuid,
331 owner: user_id,
332 successor: new_refresh_details.token_uuid,
333 access_uuid: access_details.token_uuid,
334 superseded: None,
335 refresh_ttl: (data.conf.refresh_token_max_age * 60) as u64,
336 access_ttl: (data.conf.access_token_max_age * 60) as u64,
337 grace: REUSE_GRACE_SECS,
338 },
339 )
340 .await?;
341 match redemption {
342 Redemption::Rotated => {}
343 Redemption::Reused => return Ok(RefreshOutcome::shared(account)),
344 Redemption::Refused => {
345 return Err(WebError::unauthorized(
346 "Token is invalid or session has expired",
347 ));
348 }
349 }
350
351 let mut cookie_headers = axum::http::HeaderMap::new();
352 crate::session::append_set_cookies(
353 &mut cookie_headers,
354 crate::session::session_cookies(
355 &data.conf,
356 access_details.token.unwrap_or_default(),
357 new_refresh_details.token.unwrap_or_default(),
358 ),
359 );
360 let set_cookies = cookie_headers
361 .get_all(header::SET_COOKIE)
362 .iter()
363 .cloned()
364 .collect();
365
366 Ok(RefreshOutcome {
367 account,
368 access_token_uuid: access_details.token_uuid,
369 set_cookies,
370 })
371}
372
373pub async fn auth(
374 cookie_jar: CookieJar,
375 State(data): State<Arc<AppState>>,
376 mut req: Request<Body>,
377 next: Next,
378) -> Result<Response, AuthError> {
379 let access_token = extract_access_token(&cookie_jar, &req);
380
381 let (row, access_token_uuid, refreshed_cookies, refreshed) =
382 match resolve_access(&data, access_token.as_deref()).await {
383 Access::Valid(uid, atid) => {
384 let account = fetch_account(uid).await?;
385 refuse(account.refusal)?;
386 (account, atid, Vec::new(), false)
387 }
388 Access::Unavailable => {
389 return Err(WebError::unavailable(UNAVAILABLE_MESSAGE));
390 }
391 Access::Absent => {
394 let outcome = try_refresh_session(&data, &cookie_jar).await?;
395 (
396 outcome.account,
397 outcome.access_token_uuid,
398 outcome.set_cookies,
399 true,
400 )
401 }
402 };
403
404 let user = User {
405 id: row.id,
406 name: row.name,
407 email: row.email,
408 role: row.role,
409 photo: row.photo,
410 verified: row.verified,
411 created_at: row.created_at,
412 updated_at: row.updated_at,
413 };
414
415 req.extensions_mut().insert(JWTAuthMiddleware {
416 user,
417 access_token_uuid,
418 refreshed,
419 });
420
421 let mut response = next.run(req).await;
422 if !ends_session(&response) {
426 for cookie in refreshed_cookies {
427 response.headers_mut().append(header::SET_COOKIE, cookie);
428 }
429 }
430 Ok(response)
431}
432
433pub fn ends_session<B>(response: &Response<B>) -> bool {
435 response
436 .headers()
437 .get_all(header::SET_COOKIE)
438 .iter()
439 .filter_map(|value| value.to_str().ok())
440 .filter_map(|raw| Cookie::parse(raw.to_owned()).ok())
441 .any(|cookie| cookie.name() == "access_token" && cookie.value().is_empty())
442}
443
444pub async fn admin(
445 Extension(jwtauth): Extension<JWTAuthMiddleware>,
446 req: Request<Body>,
447 next: Next,
448) -> Result<impl IntoResponse, WebError> {
449 if jwtauth.user.role != "admin" {
450 return Err(WebError::forbidden(
451 "The user does not have admin permissions",
452 ));
453 }
454
455 Ok(next.run(req).await)
456}
457
458#[cfg(test)]
459#[path = "jwt_auth_rotation_tests.rs"]
460mod rotation_tests;
461
462#[cfg(test)]
463#[path = "jwt_auth_refusal_tests.rs"]
464mod refusal_tests;