ryuk 0.1.1

A Laravel-style full-stack web framework for Rust: axum, SeaORM and Inertia, with auth, queues, mail, storage, cache, scheduling and an MCP server.
Documentation
//! Sessions, password hashing and the `Auth` extractors.
//!
//! ```ignore
//! let app = Router::new().route("/me", get(|Auth(id): Auth| async move { id.to_string() }))
//!     .layer(auth::session_layer());
//! ```
pub use crate::session::session_layer;
use argon2::Argon2;
use argon2::password_hash::{PasswordHasher, PasswordVerifier, phc::PasswordHash};
use axum::Json;
use axum::extract::FromRequestParts;
use axum::http::{HeaderMap, StatusCode, header, request::Parts};
use axum::response::{IntoResponse, Redirect, Response};
use tower_sessions::Session;

const USER_KEY: &str = "user_id";

/// Auth failure; renders as a 500.
#[derive(Debug, thiserror::Error)]
pub enum AuthError {
    /// Password hashing failed.
    #[error("password hashing failed: {0}")]
    Hash(String),
    /// Session store failed.
    #[error("session error: {0}")]
    Session(#[from] tower_sessions::session::Error),
}

impl IntoResponse for AuthError {
    fn into_response(self) -> Response {
        tracing::error!("{self}");
        StatusCode::INTERNAL_SERVER_ERROR.into_response()
    }
}

/// Hash a password with argon2 (random salt).
///
/// Usage: `let h = hash_password("secret")?;`
pub fn hash_password(plain: &str) -> Result<String, AuthError> {
    Argon2::default()
        .hash_password(plain.as_bytes())
        .map(|h| h.to_string())
        .map_err(|e| AuthError::Hash(e.to_string()))
}

/// Check a password against an argon2 hash; false on mismatch or malformed hash.
///
/// Usage: `if verify_password(&form.password, &user.password) { .. }`
pub fn verify_password(plain: &str, hash: &str) -> bool {
    PasswordHash::new(hash).is_ok_and(|h| {
        Argon2::default()
            .verify_password(plain.as_bytes(), &h)
            .is_ok()
    })
}

/// Concurrent argon2 jobs: a flood queues here instead of exhausting tokio's blocking pool.
fn hash_permits() -> &'static tokio::sync::Semaphore {
    static S: std::sync::OnceLock<tokio::sync::Semaphore> = std::sync::OnceLock::new();
    S.get_or_init(|| {
        let n = std::thread::available_parallelism().map_or(2, |n| n.get());
        tokio::sync::Semaphore::new(n.max(2))
    })
}

/// Run `f` on the blocking pool, at most `hash_permits` at a time.
async fn blocking<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> Option<T> {
    let _permit = hash_permits().acquire().await.ok()?;
    tokio::task::spawn_blocking(f).await.ok()
}

/// [`hash_password`] off the async workers (bounded blocking pool).
///
/// Usage: `let h = hash_password_async(form.password).await?;`
pub async fn hash_password_async(plain: String) -> Result<String, AuthError> {
    blocking(move || hash_password(&plain))
        .await
        .unwrap_or_else(|| Err(AuthError::Hash("hashing task failed".into())))
}

/// [`verify_password`] off the async workers (bounded blocking pool); false if the task fails.
///
/// Usage: `if verify_password_async(form.password, user.password).await { .. }`
pub async fn verify_password_async(plain: String, hash: String) -> bool {
    blocking(move || verify_password(&plain, &hash))
        .await
        .unwrap_or(false)
}

/// Log a user in, cycling the session id (prevents fixation) and discarding the CSRF token so a fresh one
/// is minted for the authenticated session.
///
/// Usage: `login(&session, user.id).await?;`
pub async fn login(session: &Session, user_id: i64) -> Result<(), AuthError> {
    session.cycle_id().await?;
    #[cfg(feature = "csrf")]
    // mirrors `csrf::KEY`, which is private; `login_rotates_the_csrf_token` fails if they diverge
    session.remove::<String>("csrf_token").await?;
    session.insert(USER_KEY, user_id).await?;
    Ok(())
}

/// Log out: destroys the whole session (best effort).
///
/// Usage: `logout(&session).await;`
pub async fn logout(session: &Session) {
    if let Err(e) = session.flush().await {
        tracing::error!("logout failed: {e}");
    }
}

/// Extractor requiring login. Unauthenticated: 303 to `/login` for Inertia/HTML, 401 JSON for API.
///
/// Usage: `async fn dash(Auth(user_id): Auth) {}`
pub struct Auth(pub i64);

/// Extractor yielding the user id if logged in.
///
/// Usage: `async fn home(OptionalAuth(uid): OptionalAuth) {}`
pub struct OptionalAuth(pub Option<i64>);

// Response is axum's standard rejection type; boxing it would only move the allocation.
#[allow(clippy::result_large_err)]
async fn user_id<S: Send + Sync>(parts: &mut Parts, state: &S) -> Result<Option<i64>, Response> {
    let session = Session::from_request_parts(parts, state)
        .await
        .map_err(|(c, m)| (c, m).into_response())?;
    session
        .get::<i64>(USER_KEY)
        .await
        .map_err(|e| AuthError::from(e).into_response())
}

/// JSON client = no X-Inertia header and Accept mentions json.
fn wants_json(h: &HeaderMap) -> bool {
    !h.contains_key("x-inertia")
        && h.get(header::ACCEPT)
            .and_then(|v| v.to_str().ok())
            .is_some_and(|a| a.contains("json"))
}

impl<S: Send + Sync> FromRequestParts<S> for Auth {
    type Rejection = Response;
    async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Response> {
        match user_id(parts, state).await? {
            Some(id) => Ok(Auth(id)),
            None if wants_json(&parts.headers) => Err((
                StatusCode::UNAUTHORIZED,
                Json(serde_json::json!({"message": "Unauthenticated."})),
            )
                .into_response()),
            None => Err(Redirect::to("/login").into_response()),
        }
    }
}

impl<S: Send + Sync> FromRequestParts<S> for OptionalAuth {
    type Rejection = Response;
    async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Response> {
        Ok(OptionalAuth(user_id(parts, state).await?))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::{Router, body::Body, http::Request, routing::get};
    use tower::ServiceExt;

    #[test]
    fn hash_round_trip() {
        let h = hash_password("pw").unwrap();
        assert!(verify_password("pw", &h));
        assert!(!verify_password("nope", &h));
        assert!(!verify_password("pw", "garbage"));
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn async_hashing_does_not_starve_the_runtime() {
        let h = hash_password_async("pw".into()).await.unwrap();
        assert!(h.starts_with("$argon2"));
        let jobs: Vec<_> = (0..64)
            .map(|i| {
                let h = h.clone();
                tokio::spawn(async move {
                    let pw = if i % 2 == 0 { "pw" } else { "bad" };
                    (i, verify_password_async(pw.into(), h).await)
                })
            })
            .collect();
        // while 64 verifications are queued, a trivial task must still be served promptly
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        let ping = tokio::time::timeout(
            std::time::Duration::from_millis(500),
            tokio::spawn(async { 1 }),
        )
        .await;
        assert_eq!(ping.expect("runtime starved").unwrap(), 1);
        for j in jobs {
            let (i, ok) = j.await.unwrap();
            assert_eq!(ok, i % 2 == 0);
        }
        assert!(!verify_password_async("pw".into(), "garbage".into()).await);
    }

    #[cfg(feature = "csrf")]
    #[tokio::test]
    async fn login_rotates_the_csrf_token() {
        use axum::middleware::from_fn_with_state;
        let app = Router::new()
            .route("/tok", get(|| async { "x" }))
            .route(
                "/login",
                get(|s: Session| async move { login(&s, 7).await.unwrap() }),
            )
            .layer(from_fn_with_state(
                crate::csrf::Csrf::new(&[]),
                crate::csrf::middleware,
            ))
            .layer(session_layer());
        let call = |path: &'static str, cookie: String| {
            let app = app.clone();
            async move {
                let r = get_with(app, path, &[("cookie", &cookie)]).await;
                let (mut sess, mut xsrf) = (None, String::new());
                for v in r.headers().get_all(header::SET_COOKIE) {
                    let c = v.to_str().unwrap().split(';').next().unwrap().to_string();
                    match c.strip_prefix("XSRF-TOKEN=") {
                        Some(t) => xsrf = t.to_string(),
                        None => sess = Some(c),
                    }
                }
                (sess, xsrf)
            }
        };
        let (sess, before) = call("/tok", String::new()).await;
        let sess = sess.unwrap();
        let (sess2, _) = call("/login", sess).await;
        let (_, after) = call("/tok", sess2.unwrap()).await;
        assert!(!before.is_empty() && !after.is_empty());
        assert_ne!(before, after, "csrf token must be re-minted after login");
    }

    fn app() -> Router {
        Router::new()
            .route("/me", get(|Auth(id): Auth| async move { id.to_string() }))
            .route(
                "/opt",
                get(|OptionalAuth(id): OptionalAuth| async move { format!("{id:?}") }),
            )
            .route(
                "/login",
                get(|s: Session| async move { login(&s, 7).await.unwrap() }),
            )
            .layer(session_layer())
    }

    async fn get_with(app: Router, path: &str, headers: &[(&str, &str)]) -> Response {
        let mut r = Request::get(path);
        for (k, v) in headers {
            r = r.header(*k, *v);
        }
        app.oneshot(r.body(Body::empty()).unwrap()).await.unwrap()
    }

    async fn body(r: Response) -> Vec<u8> {
        axum::body::to_bytes(r.into_body(), 1024)
            .await
            .unwrap()
            .to_vec()
    }

    #[tokio::test]
    async fn rejections() {
        let r = get_with(app(), "/me", &[("accept", "text/html")]).await;
        assert_eq!(r.status(), StatusCode::SEE_OTHER);
        assert_eq!(r.headers()["location"], "/login");
        let r = get_with(app(), "/me", &[("accept", "application/json")]).await;
        assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
        let r = get_with(
            app(),
            "/me",
            &[("accept", "application/json"), ("x-inertia", "true")],
        )
        .await;
        assert_eq!(r.status(), StatusCode::SEE_OTHER);
        assert_eq!(body(get_with(app(), "/opt", &[]).await).await, b"None");
    }

    #[tokio::test]
    async fn login_then_access() {
        // same router (same MemoryStore) for both requests
        let app = app();
        let r = get_with(app.clone(), "/login", &[]).await;
        let c = r.headers()[header::SET_COOKIE]
            .to_str()
            .unwrap()
            .to_string();
        assert!(c.contains("HttpOnly") && c.contains("SameSite=Lax") && !c.contains("Secure"));
        let cookie = c.split(';').next().unwrap();
        let r = get_with(app, "/me", &[("cookie", cookie)]).await;
        assert_eq!(body(r).await, b"7");
    }
}