authr_http 0.1.0

Actix Web integration for authr.
Documentation
use actix_web::{
    HttpMessage, HttpResponse,
    body::{EitherBody, MessageBody},
    dev::{ServiceRequest, ServiceResponse},
    error::Error,
    http::header::{HeaderValue, SET_COOKIE},
    middleware::Next,
    web,
};
use chrono::Utc;

use authr_common::types::{Session, User};
use authr_core::{context::AuthrContext, database::AuthDatabase};

use crate::{
    cookies::{build_session_cookie, extract_session_token},
    error::ServerError,
};

/// Authentication data attached to requests with a valid session.
///
/// This structure is inserted into the request extensions by
/// [`require_session`] and can be retrieved by downstream handlers.
///
/// It intentionally does not implement `Debug` because it contains
/// the raw session token.
#[derive(Debug, Clone)]
pub struct AuthenticatedSession {
    /// The authenticated user's session.
    pub session: Session,

    /// The user associated with the session.
    pub user: User,

    /// The raw session token extracted from the request.
    pub token: String,

    /// Whether the session was recently authenticated.
    pub is_fresh: bool,

    /// Whether the session was refreshed during this request.
    pub refreshed: bool,
}

/// Requires a valid authenticated session to access the requested resource.
///
/// Resolves the session from the request cookie, refreshes it when necessary,
/// and inserts the resulting [`AuthenticatedSession`] into request extensions.
///
/// Returns `401 Unauthorized` when the session is missing or invalid, and
/// `500 Internal Server Error` when session resolution fails.
#[tracing::instrument(target = "middleware::session::require_session", skip_all, err)]
pub async fn require_session<D, B>(
    req: ServiceRequest,
    next: Next<B>,
) -> Result<ServiceResponse<EitherBody<B>>, Error>
where
    D: AuthDatabase + 'static,
    B: MessageBody + 'static,
{
    // ----- Retrieve context
    let Some(ctx) = req.app_data::<web::Data<AuthrContext<D>>>().cloned() else {
        tracing::error!("AuthrContext is missing from application data");

        return Ok(req
            .into_response(HttpResponse::InternalServerError().finish())
            .map_into_right_body());
    };

    // ----- Extract session token
    let Some(session_token) = extract_session_token(req.request()) else {
        tracing::debug!("Authentication required but no session token was provided");

        return Ok(unauthorized_response(req));
    };

    // ----- Resolve session
    let authenticated = match resolve_session(&ctx, &session_token).await {
        Ok(Some(authenticated)) => authenticated,
        Ok(None) => {
            tracing::debug!("Authentication failed because the session is invalid");

            return Ok(unauthorized_response(req));
        }
        Err(error) => {
            tracing::error!(
                error = ?error,
                "Failed to resolve authenticated session"
            );

            return Ok(req
                .into_response(HttpResponse::InternalServerError().finish())
                .map_into_right_body());
        }
    };

    tracing::debug!(
        session_id = %authenticated.session.id,
        user_id = %authenticated.user.id,
        is_fresh = authenticated.is_fresh,
        refreshed = authenticated.refreshed,
        "Authenticated request"
    );

    // ----- Prepare refreshed session cookie
    let refreshed_cookie = if authenticated.refreshed {
        let mut session = authenticated.session.clone();
        session.token = authenticated.token.clone();

        Some(build_session_cookie(&session).to_string())
    } else {
        None
    };

    // ----- Store authenticated context
    req.extensions_mut().insert(authenticated);

    // ----- Execute request
    let mut response = next
        .call(req)
        .await
        .map(ServiceResponse::map_into_left_body)?;

    // ----- Renew session cookie
    if let Some(cookie) = refreshed_cookie {
        match HeaderValue::try_from(cookie) {
            Ok(value) => {
                response
                    .response_mut()
                    .headers_mut()
                    .append(SET_COOKIE, value);
            }
            Err(error) => {
                tracing::error!(
                    error = %error,
                    "Failed to construct refreshed session cookie"
                );
            }
        }
    }

    Ok(response)
}

// -------------------- Session Resolution --------------------

/// Resolves a session token into its associated authenticated session.
///
/// Returns `Ok(None)` when the session is missing, expired, or its user
/// no longer exists. Expired and orphaned sessions are deleted from storage.
#[tracing::instrument(target = "middleware::session::resolve_session", skip_all, err)]
pub async fn resolve_session<D: AuthDatabase + 'static>(
    ctx: &AuthrContext<D>,
    session_token: &str,
) -> Result<Option<AuthenticatedSession>, ServerError> {
    let store = ctx.store();

    // ----- Find session
    let Some(session) = store.find_session_by_token(session_token).await? else {
        return Ok(None);
    };

    // ----- Check expiration
    if session.expires_at <= Utc::now() {
        store.delete_session_by_token(session_token).await?;

        tracing::debug!(
            session_id = %session.id,
            "Deleted expired session"
        );

        return Ok(None);
    }

    // ----- Refresh session if necessary
    let Some((session, refreshed)) = ctx.refresh_session(session).await? else {
        return Ok(None);
    };

    // ----- Check freshness
    let is_fresh = ctx.is_session_fresh(&session);

    // ----- Find user
    let user_id = session.user_id.to_string();

    let Some(user) = store.find_user_by_id(&user_id).await? else {
        store.delete_session_by_token(session_token).await?;

        tracing::debug!(
            session_id = %session.id,
            user_id,
            "Deleted session belonging to a missing user"
        );

        return Ok(None);
    };

    Ok(Some(AuthenticatedSession {
        session,
        user,
        token: session_token.to_owned(),
        is_fresh,
        refreshed,
    }))
}

// -------------------- Internal Helpers --------------------

/// Builds the response returned when authentication is missing or invalid.
fn unauthorized_response<B>(req: ServiceRequest) -> ServiceResponse<EitherBody<B>> {
    req.into_response(HttpResponse::Unauthorized().json(serde_json::json!({
        "message": "Unauthorized"
    })))
    .map_into_right_body()
}