HIGH insufficient loggingaxumsaml

Insufficient Logging in Axum with Saml

Insufficient Logging in Axum with Saml — how this specific combination creates or exposes the vulnerability

Insufficient logging in an Axum application that uses SAML for authentication can leave security events unrecorded, reducing the ability to detect and respond to identity-related attacks. When SAML flows are processed without structured audit logs, critical context such as issuer, subject, session identifiers, and assertion validation outcomes are missing. This gap affects detection of authentication anomalies, replay attempts, and unauthorized access patterns.

Without logs, you cannot reliably trace which SAML response was accepted, whether the signature verification passed, or whether assertions originated from unexpected identity providers. Attackers may exploit this by tampering with NameID or session indexes, and the absence of logs prevents detection of tampering or elevation-of-privilege attempts tied to BOLA/IDOR scenarios. middleBrick scanning an Axum endpoint that relies on SAML can surface insufficient logging as a finding under Authentication and Property Authorization checks, highlighting missing audit trails for identity events.

In practice, insufficient logging also hampers forensic analysis post-incident. For example, if a SAML logout or session termination is not recorded, you cannot confirm whether single logout (SLO) was honored. Axum middleware should capture key elements of the SAML flow — issuer, inResponseTo, status, and attribute assertions — while ensuring no sensitive PII is logged in plaintext. middleBrick’s LLM/AI Security checks complement this by verifying that system prompt leakage and output exposure do not expose tokens or assertions, which can compound risks when logging is weak.

Saml-Specific Remediation in Axum — concrete code fixes

To address insufficient logging in Axum with SAML, instrument your SAML processing pipeline to emit structured, tamper-evident audit events for each stage of the protocol. Log at key points: receipt of SAML request/response, signature validation outcomes, NameID and session index values (without exposing raw assertions), and any validation or binding errors. Ensure logs include a correlation identifier so you can trace a full SSO/SLO exchange across services.

Below are concrete Axum examples that combine SAML handling with structured logging using tracing and serde_json. The snippets assume you use a SAML library that provides parsed outcomes and that you validate signatures and audience/issuer before consuming assertions.

use axum::{
    async_trait, body::Body, extract::FromRequest, handler, http::Request, middleware, Router,
};
use serde_json::json;
use tracing::{info, warn, error};

// Example structured logging in a SAML response handler
async fn handle_saml_response(
    saml_response: &str,
    relay_state: Option<&str>,
    session_id: &str,
) -> Result<(), &'static str> {
    // Assume validate_saml_response returns a parsed and validated outcome
    match validate_saml_response(saml_response).await {
        Ok(validation) => {
            info!(
                target: "saml_auth",
                event: "saml_response_validated",
                session_id = session_id,
                issuer = validation.issuer,
                name_id = validation.name_id,
                in_response_to = validation.in_response_to,
                status = validation.status,
                relay_state = relay_state.unwrap_or("none"),
                // Do not log raw assertions or signatures
            );
            // Continue with session creation or token issuance
            Ok(())
        }
        Err(e) => {
            warn!(
                target: "saml_auth",
                event: "saml_validation_failed",
                session_id = session_id,
                error = %e,
                // Optionally include request source for traceability
            );
            Err("invalid_saml")
        }
    }
}

// Example middleware that enforces logging for unauthenticated SAML endpoints
async fn require_saml_session(req: Request<B>) -> Result<Request<B>, (Request<B>, &'static str)> {
    // Placeholder: extract session context and ensure a prior SAML flow was logged
    let has_session = true; // derive from your session store
    if has_session {
        Ok(req)
    } else {
        error!(
            target: "saml_auth",
            event: "missing_saml_session",
            method = %req.method(),
            uri = %req.uri().path(),
            // Avoid logging full headers that may contain tokens
        );
        Err((req, "unauthenticated"))
    }
}

// Minimal Axum app integrating the above
pub fn app() -> Router<Body> {
    Router::new()
        .route("/acs", handler(|req: Request<Body>| async move {
            // Extract SAMLResponse and RelayState from form payload
            // After extraction, call handle_saml_response with structured logging
            handle_saml_response("", None, "corr-123").await
        }))
        .layer(middleware::from_fn(require_saml_session))
}

SAML audit guidelines and compliance mapping

Ensure logs capture SAML protocol metadata useful for compliance mappings such as OWASP API Top 10 (2023) and SOC2. Avoid logging sensitive SAML assertions or PII; instead log normalized identifiers and statuses. middleBrick’s scan can highlight whether your Axum endpoints emit sufficient authentication and identity-related audit events and map findings to relevant frameworks. For continuous assurance, combine these logs with runtime checks that validate issuer, audience, and signature status on every SAML response.

Log field Purpose Compliance relevance
event Type of SAML flow (login, logout, validation failure) OWASP API1:2023 Broken Object Level Authorization; SOC2 CC6.1
session_id Correlate requests within a SSO session Audit trail integrity (SOC2 AU-3)
issuer Identity provider name/ID Trust and source verification (PCI-DSS 8.2)
status SAML protocol status code Failure detection and incident response
in_response_to Link request to response to prevent replay Replay protection (OWASP API1:2023)

Frequently Asked Questions

What should I log when handling SAML responses in Axum to avoid insufficient logging?
Log structured events including session_id, issuer, name_id (hashed if sensitive), in_response_to, status, and relay_state. Avoid logging raw assertions or PII; use a target like "saml_auth" and include a correlation ID for traceability.
How does insufficient logging in Axum with SAML relate to broader API security findings from middleBrick?
middleBrick scans test authentication and property authorization without credentials and can flag missing audit trails for identity events. Insufficient logging impairs detection of BOLA/IDOR, replay, and privilege escalation involving SAML, and may appear alongside findings mapped to OWASP API Top 10 and compliance frameworks.