securite.rs 99 lignes · 3726 octets
//! En-têtes de sécurité, CSP et protection CSRF (docs/ihm/CONVENTIONS.md § Sécurité), partagés
//! par l'installeur et la console (OI-169).

use axum::{
    extract::Request,
    http::{HeaderValue, Method, StatusCode, header},
    middleware::Next,
    response::{IntoResponse, Response},
};
use tower_sessions::Session;

use crate::notification::notify;

/// Aucune ressource externe, aucun script ni style en ligne.
pub const CSP: &str = "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; \
                       font-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; \
                       form-action 'self'";

pub const CSRF_HEADER: &str = "x-csrf-token";
const CSRF_SESSION_KEY: &str = "csrf";

pub async fn headers(req: Request, next: Next) -> Response {
    let is_static = req.uri().path().starts_with("/static/");
    let mut res = next.run(req).await;
    let headers = res.headers_mut();
    for (name, value) in [
        (header::CONTENT_SECURITY_POLICY, CSP),
        (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
        (header::REFERRER_POLICY, "no-referrer"),
        (header::X_FRAME_OPTIONS, "DENY"),
    ] {
        headers.insert(name, HeaderValue::from_static(value));
    }
    headers.insert("cross-origin-opener-policy", HeaderValue::from_static("same-origin"));
    headers.insert(
        "permissions-policy",
        HeaderValue::from_static("camera=(), microphone=(), geolocation=(), interest-cohort=()"),
    );
    if !is_static {
        headers.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
    }
    res
}

/// Jeton CSRF de la session, créé au premier appel.
pub async fn csrf_token(session: &Session) -> Result<String, tower_sessions::session::Error> {
    if let Some(token) = session.get::<String>(CSRF_SESSION_KEY).await? {
        return Ok(token);
    }
    let token: String = rand::random::<[u8; 32]>().iter().map(|b| format!("{b:02x}")).collect();
    session.insert(CSRF_SESSION_KEY, &token).await?;
    Ok(token)
}

/// Refuse toute requête non sûre dont l'en-tête `X-CSRF-Token` ne correspond pas à la session.
pub async fn csrf_guard(session: Session, req: Request, next: Next) -> Response {
    if matches!(*req.method(), Method::GET | Method::HEAD | Method::OPTIONS) {
        return next.run(req).await;
    }
    let sent = req.headers().get(CSRF_HEADER).map(HeaderValue::as_bytes);
    let expected = match session.get::<String>(CSRF_SESSION_KEY).await {
        Ok(token) => token,
        Err(err) => {
            tracing::error!(error = %err, "session illisible");
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                notify("error", "Une erreur est survenue sur le serveur. Réessayez."),
                "Erreur de session.",
            )
                .into_response();
        }
    };
    match (sent, expected) {
        (Some(sent), Some(expected)) if constant_time_eq(sent, expected.as_bytes()) => next.run(req).await,
        _ => (
            StatusCode::FORBIDDEN,
            notify("error", "Votre session a expiré. Rechargez la page."),
            "Requête refusée : jeton CSRF absent ou invalide.",
        )
            .into_response(),
    }
}

fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
    a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
}

#[cfg(test)]
mod tests {
    use super::constant_time_eq;

    #[test]
    fn la_comparaison_de_jetons_est_exacte() {
        assert!(constant_time_eq(b"abc", b"abc"));
        assert!(!constant_time_eq(b"abc", b"abd"));
        assert!(!constant_time_eq(b"abc", b"abcd"));
        assert!(!constant_time_eq(b"", b"a"));
    }
}