1
use std::sync::Arc;
2

            
3
use axum::{
4
    Extension,
5
    body::Body,
6
    extract::State,
7
    http::{HeaderValue, Request, StatusCode, header},
8
    middleware::Next,
9
    response::{IntoResponse, Response},
10
};
11

            
12
use axum_extra::extract::{CookieJar, cookie::Cookie};
13
use serde::{Deserialize, Serialize};
14

            
15
use crate::{
16
    AppState,
17
    model::User,
18
    response::{UNAVAILABLE_MESSAGE, WebError},
19
};
20
use redis::AsyncCommands;
21
use server::command::user::{Account, Refusal};
22

            
23
#[derive(Debug, Serialize, Deserialize, Clone)]
24
pub struct JWTAuthMiddleware {
25
    pub user: User,
26
    pub access_token_uuid: uuid::Uuid,
27
    /// This request arrived with a dead access token and the middleware
28
    /// refreshed the session itself, consuming the refresh token in the jar.
29
    pub refreshed: bool,
30
}
31

            
32
type AuthError = WebError;
33

            
34
/// A session-store or directory outage: 503 rather than 500 because the
35
/// account is intact and a retry is the right response. Checked in this
36
/// middleware, which already re-reads the user row on every request, so it
37
/// covers the whole authenticated surface.
38
8
fn unavailable_err(e: &dyn std::fmt::Display) -> AuthError {
39
8
    tracing::error!("session store error: {e}");
40
8
    WebError::unavailable(UNAVAILABLE_MESSAGE)
41
8
}
42

            
43
33
fn extract_access_token(cookie_jar: &CookieJar, req: &Request<Body>) -> Option<String> {
44
33
    cookie_jar
45
33
        .get("access_token")
46
3
        .map(|cookie| cookie.value().to_string())
47
30
        .or_else(|| {
48
30
            req.headers()
49
30
                .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
30
        })
57
33
}
58

            
59
/// Why an access token did or did not resolve to a session.
60
enum Access {
61
    Valid(uuid::Uuid, uuid::Uuid),
62
    /// No usable token. The caller may still refresh.
63
    Absent,
64
    /// The session store could not be reached. Distinguished from `Absent`
65
    /// because falling through to the refresh path told the user their session
66
    /// had expired — and consumed their refresh token — over an outage that
67
    /// had nothing to do with them.
68
    Unavailable,
69
}
70

            
71
33
async fn resolve_access(data: &Arc<AppState>, access_token: Option<&str>) -> Access {
72
33
    let Some(token_str) = access_token else {
73
30
        return Access::Absent;
74
    };
75
3
    let details = match crate::auth_keys::verify(token_str, crate::token::TokenType::Access).await {
76
3
        Ok(Some(details)) => details,
77
        Ok(None) => return Access::Absent,
78
        Err(_) => return Access::Unavailable,
79
    };
80
3
    let Ok(mut redis) = data.redis_client.get_multiplexed_async_connection().await else {
81
        return Access::Unavailable;
82
    };
83
    // `Option<String>`, so a missing session reads as `Ok(None)` rather than
84
    // sharing an error arm with the store being down.
85
3
    let Ok(user_id_str) = redis
86
3
        .get::<_, Option<String>>(details.token_uuid.to_string())
87
3
        .await
88
    else {
89
        return Access::Unavailable;
90
    };
91
3
    let Some(user_id) = user_id_str.and_then(|id| uuid::Uuid::parse_str(&id).ok()) else {
92
1
        return Access::Absent;
93
    };
94
    // Bind the verified JWT subject to the Redis session owner: the token was
95
    // signed by `details.user_id`'s key, so a mismatch means the token_uuid was
96
    // paired with a different user's session — reject it.
97
2
    if user_id != details.user_id {
98
        return Access::Absent;
99
2
    }
100
2
    Access::Valid(user_id, details.token_uuid)
101
33
}
102

            
103
struct RefreshOutcome {
104
    account: Account,
105
    access_token_uuid: uuid::Uuid,
106
    set_cookies: Vec<HeaderValue>,
107
}
108

            
109
impl RefreshOutcome {
110
    /// A request that lost the rotation race: the winner's response carries the
111
    /// new cookies. The nil access uuid names no session, so logout's delete
112
    /// of it touches nothing.
113
3
    fn shared(account: Account) -> Self {
114
3
        Self {
115
3
            account,
116
3
            access_token_uuid: uuid::Uuid::nil(),
117
3
            set_cookies: Vec::new(),
118
3
        }
119
3
    }
120
}
121

            
122
/// How long a rotated refresh session, and the access session it superseded,
123
/// stay usable by requests that were already in flight with them. An old
124
/// refresh cookie or superseded access token stays usable for up to the grace
125
/// even after a logout made with the new cookies; that is the accepted cost.
126
pub(crate) const REUSE_GRACE_SECS: u64 = 30;
127

            
128
/// What one refresh-token rotation writes.
129
pub(crate) struct Rotation {
130
    /// The session being redeemed.
131
    pub token_uuid: uuid::Uuid,
132
    /// The user the caller's signed token claims to be.
133
    pub owner: uuid::Uuid,
134
    /// The refresh session replacing it.
135
    pub successor: uuid::Uuid,
136
    /// The access session issued with it.
137
    pub access_uuid: uuid::Uuid,
138
    /// The access session the caller held before rotating, if it still has
139
    /// one: superseded now, and shortened to the grace so a later logout, which
140
    /// only sees the newest tokens, does not leave it valid.
141
    pub superseded: Option<uuid::Uuid>,
142
    pub refresh_ttl: u64,
143
    pub access_ttl: u64,
144
    pub grace: u64,
145
}
146

            
147
/// What redeeming a refresh session did.
148
#[derive(Debug, PartialEq, Eq)]
149
pub(crate) enum Redemption {
150
    /// This call consumed the session and wrote its replacements.
151
    Rotated,
152
    /// Another call rotated this session within the grace: nothing was written.
153
    Reused,
154
    /// The session is missing, expired past the grace, or not this owner's.
155
    Refused,
156
}
157

            
158
impl Redemption {
159
31
    fn from_script(code: i64) -> Self {
160
31
        match code {
161
17
            1 => Self::Rotated,
162
6
            2 => Self::Reused,
163
8
            _ => Self::Refused,
164
        }
165
31
    }
166
}
167

            
168
/// Rotates a refresh session in one step.
169
///
170
/// The replacements are written before the old session is marked rotated, and
171
/// a failing `redis.call` aborts the script, so either the new sessions are
172
/// live or the old one still is. The rotated marker and the superseded access
173
/// session live at most `grace` seconds, never longer than they already had.
174
/// A token whose subject is not the session's owner consumes nothing.
175
33
pub(crate) async fn rotate_refresh(
176
33
    redis: &mut redis::aio::MultiplexedConnection,
177
33
    rotation: &Rotation,
178
33
) -> Result<Redemption, AuthError> {
179
33
    let script = redis::Script::new(
180
33
        r"local prefix = 'rotated:' .. ARGV[1] .. ':'
181
33
          local current = redis.call('GET', KEYS[1])
182
33
          if current and string.sub(current, 1, #prefix) == prefix then return 2 end
183
33
          if current ~= ARGV[1] then return 0 end
184
33
          redis.call('SETEX', KEYS[2], ARGV[2], ARGV[1])
185
33
          redis.call('SETEX', KEYS[3], ARGV[3], ARGV[1])
186
33
          local grace = tonumber(ARGV[4]) * 1000
187
33
          local function capped(key)
188
33
            local pttl = redis.call('PTTL', key)
189
33
            if pttl == -1 or pttl > grace then return grace end
190
33
            return math.max(pttl, 1)
191
33
          end
192
33
          if KEYS[4] and redis.call('EXISTS', KEYS[4]) == 1 then
193
33
            redis.call('PEXPIRE', KEYS[4], capped(KEYS[4]))
194
33
          end
195
33
          redis.call('SET', KEYS[1], prefix .. KEYS[2] .. ':' .. KEYS[3], 'PX', capped(KEYS[1]))
196
33
          return 1",
197
33
    );
198
33
    let mut invocation = script.prepare_invoke();
199
33
    invocation
200
33
        .key(rotation.token_uuid.to_string())
201
33
        .key(rotation.successor.to_string())
202
33
        .key(rotation.access_uuid.to_string());
203
33
    if let Some(superseded) = rotation.superseded {
204
6
        invocation.key(superseded.to_string());
205
27
    }
206
33
    invocation
207
33
        .arg(rotation.owner.to_string())
208
33
        .arg(rotation.refresh_ttl)
209
33
        .arg(rotation.access_ttl)
210
33
        .arg(rotation.grace)
211
33
        .invoke_async::<i64>(redis)
212
33
        .await
213
33
        .map(Redemption::from_script)
214
2
        .map_err(|e| unavailable_err(&e))
215
33
}
216

            
217
/// Ends a session: deletes the presented refresh and access sessions and, when
218
/// the refresh one was already rotated by this owner, the successors its marker
219
/// names. A marker of another owner is never followed.
220
5
pub(crate) async fn end_session(
221
5
    redis: &mut redis::aio::MultiplexedConnection,
222
5
    refresh: uuid::Uuid,
223
5
    access: uuid::Uuid,
224
5
    owner: uuid::Uuid,
225
5
) -> Result<(), AuthError> {
226
5
    let script = redis::Script::new(
227
5
        r"local prefix = 'rotated:' .. ARGV[1] .. ':'
228
5
          local current = redis.call('GET', KEYS[1])
229
5
          if current and string.sub(current, 1, #prefix) == prefix then
230
5
            for successor in string.gmatch(string.sub(current, #prefix + 1), '[^:]+') do
231
5
              redis.call('DEL', successor)
232
5
            end
233
5
          end
234
5
          return redis.call('DEL', KEYS[1], KEYS[2])",
235
5
    );
236
5
    script
237
5
        .key(refresh.to_string())
238
5
        .key(access.to_string())
239
5
        .arg(owner.to_string())
240
5
        .invoke_async::<()>(redis)
241
5
        .await
242
        .map_err(|e| unavailable_err(&e))
243
5
}
244

            
245
/// Fetches the account a token names, or refuses the request.
246
///
247
/// Read through `server`, which owns every database connection and releases
248
/// this one before the handler runs: held across `next.run` it would tie up one
249
/// of the admin pool's five connections for the whole request.
250
9
async fn fetch_account(user_id: uuid::Uuid) -> Result<Account, AuthError> {
251
9
    server::command::user::fetch_account(user_id)
252
9
        .await
253
9
        .map_err(WebError::from)?
254
        .ok_or_else(|| WebError::unauthorized("The user belonging to this token no longer exists"))
255
9
}
256

            
257
/// Refuses an account that may not be served.
258
15
fn refuse(refusal: Option<Refusal>) -> Result<(), AuthError> {
259
15
    match refusal {
260
2
        Some(Refusal::Disabled) => Err(WebError::forbidden("The user is not verified yet")),
261
2
        Some(Refusal::Quarantined) => Err(WebError::unavailable(
262
2
            "This account is undergoing maintenance and is temporarily unavailable",
263
2
        )),
264
11
        None => Ok(()),
265
    }
266
15
}
267

            
268
/// A mint that failed: quarantined and unreachable tenants are retryable.
269
8
pub(crate) fn mint_failed(e: crate::auth_keys::MintError) -> AuthError {
270
8
    match e.status() {
271
4
        StatusCode::SERVICE_UNAVAILABLE => unavailable_err(&e),
272
4
        _ => WebError::internal("Token minting failed", e),
273
    }
274
8
}
275

            
276
31
async fn try_refresh_session(
277
31
    data: &Arc<AppState>,
278
31
    cookie_jar: &CookieJar,
279
31
) -> Result<RefreshOutcome, AuthError> {
280
31
    let refresh_token = cookie_jar
281
31
        .get("refresh_token")
282
7
        .map(|c| c.value().to_string())
283
24
        .ok_or_else(|| WebError::unauthorized("You are not logged in, please provide token"))?;
284

            
285
    let refresh_details =
286
7
        match crate::auth_keys::verify(&refresh_token, crate::token::TokenType::Refresh).await {
287
7
            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
7
    let mut redis_client = data
297
7
        .redis_client
298
7
        .get_multiplexed_async_connection()
299
7
        .await
300
        .map_err(|e| unavailable_err(&e))?;
301

            
302
    // Everything that can fail runs BEFORE the rotation, which consumes the
303
    // session: the account read and its refusal, and both mints, which touch
304
    // the tenant database. A failure after the rotation would log the user
305
    // out; a token minted here and never registered is inert.
306
7
    let user_id = refresh_details.user_id;
307
7
    let account = fetch_account(user_id).await?;
308
7
    refuse(account.refusal)?;
309

            
310
7
    let access_details = crate::auth_keys::mint(
311
7
        user_id,
312
7
        data.conf.access_token_max_age,
313
7
        crate::token::TokenType::Access,
314
7
        refresh_details.generation,
315
7
    )
316
7
    .await
317
7
    .map_err(mint_failed)?;
318
7
    let new_refresh_details = crate::auth_keys::mint(
319
7
        user_id,
320
7
        data.conf.refresh_token_max_age,
321
7
        crate::token::TokenType::Refresh,
322
7
        refresh_details.generation,
323
7
    )
324
7
    .await
325
7
    .map_err(mint_failed)?;
326

            
327
7
    let redemption = rotate_refresh(
328
7
        &mut redis_client,
329
7
        &Rotation {
330
7
            token_uuid: refresh_details.token_uuid,
331
7
            owner: user_id,
332
7
            successor: new_refresh_details.token_uuid,
333
7
            access_uuid: access_details.token_uuid,
334
7
            superseded: None,
335
7
            refresh_ttl: (data.conf.refresh_token_max_age * 60) as u64,
336
7
            access_ttl: (data.conf.access_token_max_age * 60) as u64,
337
7
            grace: REUSE_GRACE_SECS,
338
7
        },
339
7
    )
340
7
    .await?;
341
7
    match redemption {
342
2
        Redemption::Rotated => {}
343
3
        Redemption::Reused => return Ok(RefreshOutcome::shared(account)),
344
        Redemption::Refused => {
345
2
            return Err(WebError::unauthorized(
346
2
                "Token is invalid or session has expired",
347
2
            ));
348
        }
349
    }
350

            
351
2
    let mut cookie_headers = axum::http::HeaderMap::new();
352
2
    crate::session::append_set_cookies(
353
2
        &mut cookie_headers,
354
2
        crate::session::session_cookies(
355
2
            &data.conf,
356
2
            access_details.token.unwrap_or_default(),
357
2
            new_refresh_details.token.unwrap_or_default(),
358
2
        ),
359
2
    );
360
2
    let set_cookies = cookie_headers
361
2
        .get_all(header::SET_COOKIE)
362
2
        .iter()
363
2
        .cloned()
364
2
        .collect();
365

            
366
2
    Ok(RefreshOutcome {
367
2
        account,
368
2
        access_token_uuid: access_details.token_uuid,
369
2
        set_cookies,
370
2
    })
371
31
}
372

            
373
33
pub async fn auth(
374
33
    cookie_jar: CookieJar,
375
33
    State(data): State<Arc<AppState>>,
376
33
    mut req: Request<Body>,
377
33
    next: Next,
378
33
) -> Result<Response, AuthError> {
379
33
    let access_token = extract_access_token(&cookie_jar, &req);
380

            
381
    let (row, access_token_uuid, refreshed_cookies, refreshed) =
382
33
        match resolve_access(&data, access_token.as_deref()).await {
383
            Access::Valid(uid, atid) => {
384
2
                let account = fetch_account(uid).await?;
385
2
                refuse(account.refusal)?;
386
2
                (account, atid, Vec::new(), false)
387
            }
388
            Access::Unavailable => {
389
                return Err(WebError::unavailable(UNAVAILABLE_MESSAGE));
390
            }
391
            // The refresh read the account before rotating, so nothing that can
392
            // fail is left between consuming the session and answering.
393
            Access::Absent => {
394
31
                let outcome = try_refresh_session(&data, &cookie_jar).await?;
395
5
                (
396
5
                    outcome.account,
397
5
                    outcome.access_token_uuid,
398
5
                    outcome.set_cookies,
399
5
                    true,
400
5
                )
401
            }
402
        };
403

            
404
7
    let user = User {
405
7
        id: row.id,
406
7
        name: row.name,
407
7
        email: row.email,
408
7
        role: row.role,
409
7
        photo: row.photo,
410
7
        verified: row.verified,
411
7
        created_at: row.created_at,
412
7
        updated_at: row.updated_at,
413
7
    };
414

            
415
7
    req.extensions_mut().insert(JWTAuthMiddleware {
416
7
        user,
417
7
        access_token_uuid,
418
7
        refreshed,
419
7
    });
420

            
421
7
    let mut response = next.run(req).await;
422
    // A handler that ends the session sets its own expiry cookies, and the
423
    // browser keeps whichever `Set-Cookie` for a name comes last: appending the
424
    // refresh minted on the way in would hand the client a live session back.
425
7
    if !ends_session(&response) {
426
6
        for cookie in refreshed_cookies {
427
4
            response.headers_mut().append(header::SET_COOKIE, cookie);
428
        }
429
1
    }
430
7
    Ok(response)
431
33
}
432

            
433
/// Whether the handler already expired the access cookie.
434
9
pub fn ends_session<B>(response: &Response<B>) -> bool {
435
9
    response
436
9
        .headers()
437
9
        .get_all(header::SET_COOKIE)
438
9
        .iter()
439
5
        .filter_map(|value| value.to_str().ok())
440
5
        .filter_map(|raw| Cookie::parse(raw.to_owned()).ok())
441
5
        .any(|cookie| cookie.name() == "access_token" && cookie.value().is_empty())
442
9
}
443

            
444
2
pub async fn admin(
445
2
    Extension(jwtauth): Extension<JWTAuthMiddleware>,
446
2
    req: Request<Body>,
447
2
    next: Next,
448
2
) -> Result<impl IntoResponse, WebError> {
449
2
    if jwtauth.user.role != "admin" {
450
2
        return Err(WebError::forbidden(
451
2
            "The user does not have admin permissions",
452
2
        ));
453
    }
454

            
455
    Ok(next.run(req).await)
456
2
}
457

            
458
#[cfg(test)]
459
#[path = "jwt_auth_rotation_tests.rs"]
460
mod rotation_tests;
461

            
462
#[cfg(test)]
463
#[path = "jwt_auth_refusal_tests.rs"]
464
mod refusal_tests;