HIGH token leakageaxumapi keys

Token Leakage in Axum with Api Keys

Token Leakage in Axum with Api Keys — how this specific combination creates or exposes the vulnerability

Token leakage in an Axum service using API keys occurs when key material is unintentionally exposed in logs, error responses, URLs, or headers. Because Axum is a Rust web framework, developers often manage keys via environment variables and pass them into handlers through extractor patterns. If those keys are echoed in responses or written to logs at an info or debug level, an unauthenticated attacker can harvest valid API keys.

For example, returning the key directly in a JSON response or including it in a header that is reflected to the client creates a classic data exposure finding. MiddleBrick’s Data Exposure and Header/Property Authorization checks detect when API keys appear in response bodies or non‑security headers. Similarly, improper error handling can leak keys through stack traces or validation messages, which may be captured by SSRF probes if the key is used to sign or authorize outbound requests.

Axum routes that accept keys via headers or query parameters are particularly at risk if the application does not enforce strict input validation and rate limiting. An attacker can probe endpoints with malformed or repeated key values, potentially triggering verbose errors or logs that reveal portions of the key. The Authentication and Rate Limiting checks in MiddleBrick verify whether key validation is strict and whether excessive requests are throttled to reduce leakage risk.

Because API keys often act as bearer tokens, leakage effectively grants the same access as compromised credentials. MiddleBrick’s LLM/AI Security module does not test API key leakage directly, but its output scanning and system prompt leakage detection help ensure that keys are not inadvertently surfaced in any model-generated responses or debug information when integrating AI components into the API surface.

When scanning an Axum endpoint with MiddleBrick, findings typically include references to CWE-532 (Insertion of Sensitive Information into Log File) and CWE-200 (Exposure of Sensitive Information to an Unauthorized Actor), along with precise guidance on redacting keys from logs and responses.

Api Keys-Specific Remediation in Axum — concrete code fixes

Remediation focuses on preventing keys from appearing in responses, logs, and error paths, and on enforcing strict validation and authorization. Below are Axum-compatible patterns that reduce token leakage risk.

  • Do not return API keys in responses. Use a wrapper that excludes sensitive fields:
use axum::{routing::get, Json, Router};
use serde::Serialize;

#[derive(Serialize)]
struct SafeResponse {
    message: String,
    // Do not include api_key here
}

async fn handler() -> Json<SafeResponse> {
    Json(SafeResponse {
        message: String::from("ok"),
    })
}

#[tokio::main]
async fn main() {
    let app = Router::new().route("/status", get(handler));
    axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
        .serve(app.into_make_service())
        .await
        .unwrap();
}
  • Validate and sanitize input keys. Reject malformed keys early and avoid echoing them:
use axum::{
    async_trait,
    extract::{FromRequest, Request},
    http::StatusCode,
};

struct ApiKey(String);

#[async_trait]
impl FromRequest<S> for ApiKey {
    type Rejection = (StatusCode, &'static str);

    async fn from_request(req: Request, _state: &S) -> Result<Self, Self::Rejection> {
        let key = req.headers().get("X-API-Key")
            .and_then(|v| v.to_str().ok())
            .filter(|k| !k.is_empty() && k.len() == 32) // strict validation
            .ok_or((StatusCode::UNAUTHORIZED, "Invalid API key"))?;
        Ok(ApiKey(key.to_string()))
    }
}
  • Redact keys from logs. Configure logging to filter or mask key values:
use tracing_subscriber::fmt::format::FmtSpan;
use tracing_subscriber::EnvFilter;

fn init_logger() {
    // Redact known sensitive headers in logs
    let filter = EnvFilter::new("info");
    tracing_subscriber::fmt()
        .with_env_filter(filter)
        .json()
        .with_span_events(FmtSpan::CLOSE)
        .init();
}
  • Use middleware to reject requests with missing or malformed keys, and avoid passing keys through query strings:
use axum::{middleware, Extension, Router};

async fn key_guard(
    Extension(key): Extension<String>,
) -> Result<(), (StatusCode, &'static str)> {
    if key.starts_with("ak_live_") {
        Ok(())
    } else {
        Err((StatusCode::FORBIDDEN, "Invalid key scope"))
    }
}

fn app_with_middleware() -> Router {
    Router::new()
        .route("/data", get(|| async { "ok" }))
        .layer(middleware::from_fn(key_guard))
        .layer(Extension(String::from("ak_live_example")))
}

These patterns align with MiddleBrick’s findings for Authentication, Data Exposure, and Rate Limiting, and they support compliance mapping to OWASP API Top 10 and SOC2 controls.

Frequently Asked Questions

How does MiddleBrick detect token leakage in Axum APIs without access to source code?
MiddleBrick performs black-box testing by sending crafted requests and inspecting responses, headers, and error payloads. It flags cases where API keys appear in JSON bodies, non‑security headers, or verbose error messages, referencing CWE-532 and CWE-200.
Can MiddleBrick integrate into CI/CD for Axum projects to fail builds on key leakage findings?
Yes, via the GitHub Action you can add API security checks to your CI/CD pipeline and configure it to fail builds if risk scores drop below your chosen threshold, including token leakage related findings.