HIGH api key exposureactixsaml

Api Key Exposure in Actix with Saml

Api Key Exposure in Actix with Saml — how this specific combination creates or exposes the vulnerability

When an Actix web service uses SAML for identity federation, developers often focus on authentication correctness and may inadvertently expose API keys through logging, debug endpoints, or misconfigured middleware. Actix routes and handlers can inadvertently include API key material in error responses or telemetry when SAML assertions are processed. Because SAML responses are typically processed server-side and may carry user attributes into Actix handlers, keys stored in application state or environment variables can be serialized into logs or HTTP traces if instrumentation is overly verbose.

In a black-box scan, middleBrick tests the unauthenticated attack surface and checks for data exposure across 12 parallel security checks, including Data Exposure and Authentication. When an endpoint protected by SAML also reflects or logs headers that may contain API keys (for example, custom authorization headers used by downstream services), middleBrick can detect whether key-like values appear in responses or logs. This commonly occurs when Actix applications log the full request headers for debugging SAML flows and include Authorization or X-API-Key headers that contain secrets.

Additionally, if an Actix application exposes an unauthenticated diagnostic or health endpoint that returns environment details, configuration summaries, or metadata about the SAML setup, it may leak API keys embedded in configuration structures. The scanner’s Data Exposure check flags such endpoints, while the Authentication and BOLA/IDOR checks validate whether SAML session handling leaks identity or privilege information across users. The combination of SAML-based identity flows and poorly guarded API key usage increases the likelihood of inadvertent disclosure through logs, error pages, or introspection endpoints.

middleBrick’s LLM/AI Security checks are not directly relevant here unless the service exposes an LLM endpoint that echoes back configuration or debug data; however, the scanner’s Inventory Management and Unsafe Consumption checks ensure that any API consuming key-based credentials does so without unsafe deserialization or exposure in query strings. By correlating SAML authentication events with key usage patterns, the scan can highlight risky integrations where keys are passed in headers or cookies that SAML middleware does not adequately protect.

Real-world examples include an Actix route that forwards SAML attributes to a backend service using an API key stored in app data, where the key is accidentally included in panic messages or tracing output. Another scenario is misconfigured log formatting that prints the SAML NameID alongside the API key, making it trivial for an attacker who can view logs or error pages to associate identities with keys. The scanner’s prioritized findings include severity, a description, and remediation guidance to help developers remove key exposure from logs, responses, and debug surfaces.

Saml-Specific Remediation in Actix — concrete code fixes

Remediation focuses on ensuring SAML flows in Actix do not propagate or persist API keys and that keys are never included in logs, error responses, or telemetry. Use Actix’s extractor patterns to separate identity information from credentials and avoid storing API keys in structures that are serialized into responses or logs.

1. Avoid logging sensitive headers

Configure Actix logging to exclude Authorization and X-API-Key headers. Instead of logging the full header map, extract only the identity-relevant parts from the SAML assertion.

use actix_web::{web, HttpRequest, HttpResponse, Responder};
use tracing::info;

async fn saml_protected_route(req: HttpRequest) -> impl Responder {
    // Extract identity from SAML assertion (e.g., via session extractor)
    let name_id = req.extensions().get::().map(|s| s.as_str()).unwrap_or("unknown");
    // Do NOT log headers that may contain API keys
    info!(user = %name_id, "SAML authentication succeeded");
    HttpResponse::Ok().body("OK")
}

2. Store API keys outside SAML identity structures

Keep API keys in Actix application data that is not populated from SAML attributes. Do not merge SAML user attributes with credential maps.

use actix_web::web::Data;
use serde::{Deserialize, Serialize};

#[derive(Clone)]
struct AppState {
    api_key: String,
    // Do not include SAML-derived user fields here unless necessary
}

async fn call_backend(state: Data<AppState>) -> HttpResponse {
    let client = reqwest::Client::new();
    let res = client
        .get("https://backend.example.com/protected")
        .bearer_auth(&state.api_key)
        .send()
        .await;
    match res {
        Ok(r) => HttpResponse::Ok().body(r.text().await.unwrap_or_default()),
        Err(_) => HttpResponse::InternalServerError().finish(),
    }
}

3. Validate and sanitize SAML responses before use

Ensure that SAML responses are validated and that only required attributes are used. Do not echo raw SAML responses to clients or logs.

use saml2::core::saml2::assertion::Assertion;

fn handle_saml_assertion(assertion: Assertion) -> Result<String, &'static str> {
    // Validate issuer and conditions per your IdP configuration
    if assertion.issuer().map(|s| s.value()) != Some("https://idp.example.com") {
        return Err("Invalid issuer");
    }
    // Extract only required attributes
    let name_id = assertion
        .subject()
        .name_id()
        .ok_or("Missing NameID")?
        .to_string();
    // Do not include sensitive metadata in responses
    Ok(name_id)
}

4. Use Actix middleware to strip sensitive headers

Implement a lightweight middleware that removes or masks API keys and Authorization headers from logs while preserving SAML-related cookies or session identifiers required for routing.

use actix_web::dev::{Service, ServiceRequest, ServiceResponse, Transform};
use actix_web::Error;
use futures::future::{ok, Ready};
use std::task::{Context, Poll};

pub struct SensitiveHeaderFilter;

impl Transform<S, ServiceRequest> for SensitiveHeaderFilter
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
    S::Future: 'static,
    B: 'static,
{
    type Response = ServiceResponse<B>;
    type Error = Error;
    type Transform = HeaderFilterMiddleware<S>;
    type InitError = ();
    type Future = Ready<Result<Self::Transform, Self::InitError>>;

    fn new_transform(&self, service: S) -> Self::Future {
        ok(HeaderFilterMiddleware { service })
    }
}

pub struct HeaderFilterMiddleware<S> {
    service: S,
}

impl<S, B> Service<ServiceRequest> for HeaderFilterMiddleware<S>
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
    S::Future: 'static,
    B: 'static,
{
    type Response = ServiceResponse<B>;
    type Error = Error;
    type Future = S::Future;

    fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<Self::Ready, Self::Error>> {
        self.service.poll_ready(cx)
    }

    fn call(&self, mut req: ServiceRequest) -> Self::Future {
        // Remove or mask sensitive headers before they reach logging layer
        req.headers_mut().remove("X-API-Key");
        req.headers_mut().remove("Authorization");
        self.service.call(req)
    }
}

5. Enforce strict attribute scoping

\n

Configure your IdP to emit only the minimal attributes required by the Actix application. Do not include API keys or secrets in SAML attributes. Validate audience and destination fields to prevent token misuse.

By combining these practices, you reduce the risk that API keys are exposed through SAML-related logging, error handling, or data flows. middleBrick’s checks for Data Exposure, Authentication, and BOLA/IDOR help confirm that your Actix endpoints do not leak keys and that SAML handling is scoped correctly.

Frequently Asked Questions

Can middleBrick detect API key exposure in SAML-protected Actix endpoints?
Yes. middleBrick’s Data Exposure and Authentication checks identify whether API keys appear in responses, logs, or debug endpoints, even when SAML is used for identity.
Does middleBrick fix exposed API keys in Actix applications?
No. middleBrick detects and reports findings with remediation guidance; it does not fix, patch, or block exposures. Developers should follow the remediation steps to remove keys from logs, headers, and response data.