Lines
53.33 %
Functions
20.59 %
Branches
100 %
//! Per-user JWT signing/verification for the web layer.
//!
//! Tokens are signed with each user's own RSA key (private key in their per-user
//! DB, public key in the global `users` directory). This module wraps the
//! `server` key lookups + the `token` codec into mint/verify helpers the auth
//! handlers call.
//! Verification always reads the authoritative public key from the directory —
//! no public-key cache. A cache would risk accepting tokens signed with a
//! rotated/revoked key until process restart; correctness wins over saving one
//! indexed primary-key lookup. The DoS surface of unauthenticated lookups is
//! bounded by the per-address throttle on the auth routes
//! (`crate::rate_limit`), not by caching.
use crate::token::{self, TokenDetails, TokenType};
use axum::http::StatusCode;
use uuid::Uuid;
/// Whether auth cookies should carry the `Secure` attribute (sent only over
/// HTTPS). Defaults to `true`; set `INSECURE_COOKIES=1` for local plain-HTTP
/// development. Bearer cookies (access/refresh tokens) must be `Secure` in
/// production so they can't leak over a downgraded HTTP request.
#[must_use]
pub fn secure_cookies() -> bool {
!matches!(
std::env::var("INSECURE_COOKIES").as_deref(),
Ok("1") | Ok("true")
)
}
/// Mints a token of `token_type` for `user_id`, signed with that user's
/// private key.
/// `generation` is threaded in by the caller rather than re-read here: login
/// already holds it from the password check and refresh from the verified
/// token, so minting costs no extra query.
pub async fn mint(
user_id: Uuid,
ttl: i64,
token_type: TokenType,
generation: i32,
) -> Result<TokenDetails, MintError> {
let private_key = server::auth_keys::private_key_for(user_id)
.await
.map_err(|e| match e {
server::db::DBError::TenantQuarantined => MintError::Quarantined,
server::db::DBError::KeyGen => MintError::KeyUnavailable,
// A budget stall or a transient connect failure is not a missing
// key: reporting it as one sent operators hunting a provisioning
// bug, and told the caller the account was broken rather than busy.
_ => MintError::Unavailable,
})?;
token::generate_jwt_token(user_id, ttl, &private_key, token_type, generation)
.map_err(|_| MintError::Sign)
/// Verifies a token of the EXPECTED type against its owner's public key.
///
/// Reads the `sub` claim unverified as a routing hint ONLY, fetches that user's
/// authoritative public key from the directory, re-verifies the signature, and
/// requires the claimed `token_type` to match `expected` — so an access token
/// can never be replayed where a refresh token is required (or vice-versa).
/// Returns `Ok(None)` for any *credential* failure — unknown user, missing key,
/// bad signature, wrong type, disabled account, or a superseded session
/// generation — so callers cannot distinguish failure modes (existence
/// masking). `Err` is reserved for the directory being unreadable, which is
/// not the user's fault and must not read as an expired session. Always hits the DB for
/// the current key, status and generation, so a rotated key, a switched-off
/// account or a password change takes effect immediately.
pub async fn verify(
token: &str,
expected: TokenType,
) -> Result<Option<TokenDetails>, server::db::DBError> {
let Ok(user_id) = token::unverified_user_id(token) else {
return Ok(None);
};
// An unreadable directory is NOT a bad token: folding the two together told
// a user with valid credentials that their session had expired, and sent
// them down a refresh path that consumed it.
let Some(identity) = server::auth_keys::public_key_for(user_id).await? else {
let Ok(details) = token::verify_jwt_token(&identity.public_key, token) else {
// After the signature, so a prober cannot time a disabled account apart
// from an active one. Still ahead of every caller's refresh path, which is
// what stops a stale refresh cookie consuming its Redis entry.
if !identity.verified || details.generation != identity.generation {
if details.token_type != Some(expected) {
Ok(Some(details))
#[derive(Debug, Clone, Copy)]
pub enum MintError {
/// The user has no stored signing key (a provisioning invariant violation).
KeyUnavailable,
/// The account is quarantined for maintenance.
Quarantined,
/// The tenant database could not be reached right now.
Unavailable,
/// Signing failed (malformed key material).
Sign,
impl MintError {
/// A tenant that is merely unreachable is a 503; a missing or broken key is
/// ours to fix, so it stays a 500.
pub(crate) const fn status(self) -> StatusCode {
match self {
MintError::Quarantined | MintError::Unavailable => StatusCode::SERVICE_UNAVAILABLE,
MintError::KeyUnavailable | MintError::Sign => StatusCode::INTERNAL_SERVER_ERROR,
impl std::fmt::Display for MintError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
MintError::KeyUnavailable => write!(f, "no signing key available for user"),
MintError::Quarantined => write!(f, "account is undergoing maintenance"),
MintError::Unavailable => write!(f, "user database is temporarily unreachable"),
MintError::Sign => write!(f, "failed to sign token"),
#[cfg(test)]
mod mint_error_tests {
use super::{MintError, StatusCode};
/// A tenant that is quarantined or briefly unreachable is not a missing
/// key: reporting both as 500 told the caller the account was broken when
/// it was only busy, and sent operators hunting a provisioning bug.
#[test]
fn an_unreachable_tenant_is_service_unavailable_not_a_server_error() {
assert_eq!(
MintError::Quarantined.status(),
StatusCode::SERVICE_UNAVAILABLE
);
MintError::Unavailable.status(),
MintError::KeyUnavailable.status(),
StatusCode::INTERNAL_SERVER_ERROR
assert_eq!(MintError::Sign.status(), StatusCode::INTERNAL_SERVER_ERROR);