Lines
92.39 %
Functions
32.14 %
Branches
100 %
use std::sync::Arc;
use axum::{
Extension,
body::Body,
extract::State,
http::{HeaderValue, Request, StatusCode, header},
middleware::Next,
response::{IntoResponse, Response},
};
use axum_extra::extract::{CookieJar, cookie::Cookie};
use serde::{Deserialize, Serialize};
use crate::{
AppState,
model::User,
response::{UNAVAILABLE_MESSAGE, WebError},
use redis::AsyncCommands;
use server::command::user::{Account, Refusal};
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct JWTAuthMiddleware {
pub user: User,
pub access_token_uuid: uuid::Uuid,
/// This request arrived with a dead access token and the middleware
/// refreshed the session itself, consuming the refresh token in the jar.
pub refreshed: bool,
}
type AuthError = WebError;
/// A session-store or directory outage: 503 rather than 500 because the
/// account is intact and a retry is the right response. Checked in this
/// middleware, which already re-reads the user row on every request, so it
/// covers the whole authenticated surface.
fn unavailable_err(e: &dyn std::fmt::Display) -> AuthError {
tracing::error!("session store error: {e}");
WebError::unavailable(UNAVAILABLE_MESSAGE)
fn extract_access_token(cookie_jar: &CookieJar, req: &Request<Body>) -> Option<String> {
cookie_jar
.get("access_token")
.map(|cookie| cookie.value().to_string())
.or_else(|| {
req.headers()
.get(header::AUTHORIZATION)
.and_then(|auth_header| auth_header.to_str().ok())
.and_then(|auth_value| {
auth_value
.strip_prefix("Bearer ")
.map(std::borrow::ToOwned::to_owned)
})
/// Why an access token did or did not resolve to a session.
enum Access {
Valid(uuid::Uuid, uuid::Uuid),
/// No usable token. The caller may still refresh.
Absent,
/// The session store could not be reached. Distinguished from `Absent`
/// because falling through to the refresh path told the user their session
/// had expired — and consumed their refresh token — over an outage that
/// had nothing to do with them.
Unavailable,
async fn resolve_access(data: &Arc<AppState>, access_token: Option<&str>) -> Access {
let Some(token_str) = access_token else {
return Access::Absent;
let details = match crate::auth_keys::verify(token_str, crate::token::TokenType::Access).await {
Ok(Some(details)) => details,
Ok(None) => return Access::Absent,
Err(_) => return Access::Unavailable,
let Ok(mut redis) = data.redis_client.get_multiplexed_async_connection().await else {
return Access::Unavailable;
// `Option<String>`, so a missing session reads as `Ok(None)` rather than
// sharing an error arm with the store being down.
let Ok(user_id_str) = redis
.get::<_, Option<String>>(details.token_uuid.to_string())
.await
else {
let Some(user_id) = user_id_str.and_then(|id| uuid::Uuid::parse_str(&id).ok()) else {
// Bind the verified JWT subject to the Redis session owner: the token was
// signed by `details.user_id`'s key, so a mismatch means the token_uuid was
// paired with a different user's session — reject it.
if user_id != details.user_id {
Access::Valid(user_id, details.token_uuid)
struct RefreshOutcome {
account: Account,
access_token_uuid: uuid::Uuid,
set_cookies: Vec<HeaderValue>,
impl RefreshOutcome {
/// A request that lost the rotation race: the winner's response carries the
/// new cookies. The nil access uuid names no session, so logout's delete
/// of it touches nothing.
fn shared(account: Account) -> Self {
Self {
account,
access_token_uuid: uuid::Uuid::nil(),
set_cookies: Vec::new(),
/// How long a rotated refresh session, and the access session it superseded,
/// stay usable by requests that were already in flight with them. An old
/// refresh cookie or superseded access token stays usable for up to the grace
/// even after a logout made with the new cookies; that is the accepted cost.
pub(crate) const REUSE_GRACE_SECS: u64 = 30;
/// What one refresh-token rotation writes.
pub(crate) struct Rotation {
/// The session being redeemed.
pub token_uuid: uuid::Uuid,
/// The user the caller's signed token claims to be.
pub owner: uuid::Uuid,
/// The refresh session replacing it.
pub successor: uuid::Uuid,
/// The access session issued with it.
pub access_uuid: uuid::Uuid,
/// The access session the caller held before rotating, if it still has
/// one: superseded now, and shortened to the grace so a later logout, which
/// only sees the newest tokens, does not leave it valid.
pub superseded: Option<uuid::Uuid>,
pub refresh_ttl: u64,
pub access_ttl: u64,
pub grace: u64,
/// What redeeming a refresh session did.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Redemption {
/// This call consumed the session and wrote its replacements.
Rotated,
/// Another call rotated this session within the grace: nothing was written.
Reused,
/// The session is missing, expired past the grace, or not this owner's.
Refused,
impl Redemption {
fn from_script(code: i64) -> Self {
match code {
1 => Self::Rotated,
2 => Self::Reused,
_ => Self::Refused,
/// Rotates a refresh session in one step.
///
/// The replacements are written before the old session is marked rotated, and
/// a failing `redis.call` aborts the script, so either the new sessions are
/// live or the old one still is. The rotated marker and the superseded access
/// session live at most `grace` seconds, never longer than they already had.
/// A token whose subject is not the session's owner consumes nothing.
pub(crate) async fn rotate_refresh(
redis: &mut redis::aio::MultiplexedConnection,
rotation: &Rotation,
) -> Result<Redemption, AuthError> {
let script = redis::Script::new(
r"local prefix = 'rotated:' .. ARGV[1] .. ':'
local current = redis.call('GET', KEYS[1])
if current and string.sub(current, 1, #prefix) == prefix then return 2 end
if current ~= ARGV[1] then return 0 end
redis.call('SETEX', KEYS[2], ARGV[2], ARGV[1])
redis.call('SETEX', KEYS[3], ARGV[3], ARGV[1])
local grace = tonumber(ARGV[4]) * 1000
local function capped(key)
local pttl = redis.call('PTTL', key)
if pttl == -1 or pttl > grace then return grace end
return math.max(pttl, 1)
end
if KEYS[4] and redis.call('EXISTS', KEYS[4]) == 1 then
redis.call('PEXPIRE', KEYS[4], capped(KEYS[4]))
redis.call('SET', KEYS[1], prefix .. KEYS[2] .. ':' .. KEYS[3], 'PX', capped(KEYS[1]))
return 1",
);
let mut invocation = script.prepare_invoke();
invocation
.key(rotation.token_uuid.to_string())
.key(rotation.successor.to_string())
.key(rotation.access_uuid.to_string());
if let Some(superseded) = rotation.superseded {
invocation.key(superseded.to_string());
.arg(rotation.owner.to_string())
.arg(rotation.refresh_ttl)
.arg(rotation.access_ttl)
.arg(rotation.grace)
.invoke_async::<i64>(redis)
.map(Redemption::from_script)
.map_err(|e| unavailable_err(&e))
/// Ends a session: deletes the presented refresh and access sessions and, when
/// the refresh one was already rotated by this owner, the successors its marker
/// names. A marker of another owner is never followed.
pub(crate) async fn end_session(
refresh: uuid::Uuid,
access: uuid::Uuid,
owner: uuid::Uuid,
) -> Result<(), AuthError> {
if current and string.sub(current, 1, #prefix) == prefix then
for successor in string.gmatch(string.sub(current, #prefix + 1), '[^:]+') do
redis.call('DEL', successor)
return redis.call('DEL', KEYS[1], KEYS[2])",
script
.key(refresh.to_string())
.key(access.to_string())
.arg(owner.to_string())
.invoke_async::<()>(redis)
/// Fetches the account a token names, or refuses the request.
/// Read through `server`, which owns every database connection and releases
/// this one before the handler runs: held across `next.run` it would tie up one
/// of the admin pool's five connections for the whole request.
async fn fetch_account(user_id: uuid::Uuid) -> Result<Account, AuthError> {
server::command::user::fetch_account(user_id)
.map_err(WebError::from)?
.ok_or_else(|| WebError::unauthorized("The user belonging to this token no longer exists"))
/// Refuses an account that may not be served.
fn refuse(refusal: Option<Refusal>) -> Result<(), AuthError> {
match refusal {
Some(Refusal::Disabled) => Err(WebError::forbidden("The user is not verified yet")),
Some(Refusal::Quarantined) => Err(WebError::unavailable(
"This account is undergoing maintenance and is temporarily unavailable",
)),
None => Ok(()),
/// A mint that failed: quarantined and unreachable tenants are retryable.
pub(crate) fn mint_failed(e: crate::auth_keys::MintError) -> AuthError {
match e.status() {
StatusCode::SERVICE_UNAVAILABLE => unavailable_err(&e),
_ => WebError::internal("Token minting failed", e),
async fn try_refresh_session(
data: &Arc<AppState>,
cookie_jar: &CookieJar,
) -> Result<RefreshOutcome, AuthError> {
let refresh_token = cookie_jar
.get("refresh_token")
.map(|c| c.value().to_string())
.ok_or_else(|| WebError::unauthorized("You are not logged in, please provide token"))?;
let refresh_details =
match crate::auth_keys::verify(&refresh_token, crate::token::TokenType::Refresh).await {
Ok(None) => {
return Err(WebError::unauthorized(
"Token is invalid or session has expired",
));
Err(e) => return Err(unavailable_err(&e)),
let mut redis_client = data
.redis_client
.get_multiplexed_async_connection()
.map_err(|e| unavailable_err(&e))?;
// Everything that can fail runs BEFORE the rotation, which consumes the
// session: the account read and its refusal, and both mints, which touch
// the tenant database. A failure after the rotation would log the user
// out; a token minted here and never registered is inert.
let user_id = refresh_details.user_id;
let account = fetch_account(user_id).await?;
refuse(account.refusal)?;
let access_details = crate::auth_keys::mint(
user_id,
data.conf.access_token_max_age,
crate::token::TokenType::Access,
refresh_details.generation,
)
.map_err(mint_failed)?;
let new_refresh_details = crate::auth_keys::mint(
data.conf.refresh_token_max_age,
crate::token::TokenType::Refresh,
let redemption = rotate_refresh(
&mut redis_client,
&Rotation {
token_uuid: refresh_details.token_uuid,
owner: user_id,
successor: new_refresh_details.token_uuid,
access_uuid: access_details.token_uuid,
superseded: None,
refresh_ttl: (data.conf.refresh_token_max_age * 60) as u64,
access_ttl: (data.conf.access_token_max_age * 60) as u64,
grace: REUSE_GRACE_SECS,
},
.await?;
match redemption {
Redemption::Rotated => {}
Redemption::Reused => return Ok(RefreshOutcome::shared(account)),
Redemption::Refused => {
let mut cookie_headers = axum::http::HeaderMap::new();
crate::session::append_set_cookies(
&mut cookie_headers,
crate::session::session_cookies(
&data.conf,
access_details.token.unwrap_or_default(),
new_refresh_details.token.unwrap_or_default(),
),
let set_cookies = cookie_headers
.get_all(header::SET_COOKIE)
.iter()
.cloned()
.collect();
Ok(RefreshOutcome {
access_token_uuid: access_details.token_uuid,
set_cookies,
pub async fn auth(
cookie_jar: CookieJar,
State(data): State<Arc<AppState>>,
mut req: Request<Body>,
next: Next,
) -> Result<Response, AuthError> {
let access_token = extract_access_token(&cookie_jar, &req);
let (row, access_token_uuid, refreshed_cookies, refreshed) =
match resolve_access(&data, access_token.as_deref()).await {
Access::Valid(uid, atid) => {
let account = fetch_account(uid).await?;
(account, atid, Vec::new(), false)
Access::Unavailable => {
return Err(WebError::unavailable(UNAVAILABLE_MESSAGE));
// The refresh read the account before rotating, so nothing that can
// fail is left between consuming the session and answering.
Access::Absent => {
let outcome = try_refresh_session(&data, &cookie_jar).await?;
(
outcome.account,
outcome.access_token_uuid,
outcome.set_cookies,
true,
let user = User {
id: row.id,
name: row.name,
email: row.email,
role: row.role,
photo: row.photo,
verified: row.verified,
created_at: row.created_at,
updated_at: row.updated_at,
req.extensions_mut().insert(JWTAuthMiddleware {
user,
access_token_uuid,
refreshed,
});
let mut response = next.run(req).await;
// A handler that ends the session sets its own expiry cookies, and the
// browser keeps whichever `Set-Cookie` for a name comes last: appending the
// refresh minted on the way in would hand the client a live session back.
if !ends_session(&response) {
for cookie in refreshed_cookies {
response.headers_mut().append(header::SET_COOKIE, cookie);
Ok(response)
/// Whether the handler already expired the access cookie.
pub fn ends_session<B>(response: &Response<B>) -> bool {
response
.headers()
.filter_map(|value| value.to_str().ok())
.filter_map(|raw| Cookie::parse(raw.to_owned()).ok())
.any(|cookie| cookie.name() == "access_token" && cookie.value().is_empty())
pub async fn admin(
Extension(jwtauth): Extension<JWTAuthMiddleware>,
req: Request<Body>,
) -> Result<impl IntoResponse, WebError> {
if jwtauth.user.role != "admin" {
return Err(WebError::forbidden(
"The user does not have admin permissions",
Ok(next.run(req).await)
#[cfg(test)]
#[path = "jwt_auth_rotation_tests.rs"]
mod rotation_tests;
#[path = "jwt_auth_refusal_tests.rs"]
mod refusal_tests;