HIGH broken authenticationaxumapi keys

Broken Authentication in Axum with Api Keys

Broken Authentication in Axum with Api Keys — how this specific combination creates or exposes the vulnerability

Broken Authentication in an Axum service that relies on API keys typically occurs when the key validation logic is incomplete, overly permissive, or applied inconsistently across routes. Axum does not provide built-in API key handling; developers implement validation manually, often by inspecting headers in extractors or middleware. If these checks are missing, bypassed, or applied only to selected endpoints, an attacker can make authenticated requests without a valid key.

Common implementation patterns that lead to vulnerabilities include defining an extractor for the key but failing to enforce it on all sensitive routes, accidentally skipping validation when path or query parameters are present, or placing the key check after route-specific logic that alters request handling. Another risk is logging or exposing keys in error messages, which can aid enumeration. Because keys are often static and transmitted without additional context (e.g., rotating signatures), they can be leaked through logs, referrer headers, or client-side code, enabling unauthorized access across accounts.

When combined with other API risks, broken authentication in Axum with API keys can be severe. For example, an unauthenticated LLM endpoint in the same service could allow an attacker to probe whether key validation is inconsistently applied across public and private routes. Insecure default configurations or missing validation on OPTIONS or health-check routes can also expose whether authentication is enforced. Because middleBrick scans unauthenticated attack surfaces and includes checks for Authentication and BOLA/IDOR, it can surface these gaps by identifying endpoints that accept requests without a valid key or that accept keys in nonstandard locations (e.g., query strings without equivalent header checks).

In practice, a security scan might reveal that an Axum endpoint intended for administrative actions does not require a key, or that keys accepted via a custom extractor are not validated for scope or ownership. These findings align with the broader OWASP API Top 10 category for Broken Authentication and should be treated as high severity because they allow unauthorized access to functionality or data. Remediation requires consistent, centralized validation and strict mapping of keys to permissions, which Axum enables through well-structured extractors and middleware composition.

Api Keys-Specific Remediation in Axum — concrete code fixes

To remediate broken authentication in Axum when using API keys, centralize validation and enforce it uniformly across all routes that require authentication. Implement a dedicated extractor that retrieves the key from a standard header, validates it against a known set of allowed values or a secure lookup, and returns an appropriate rejection response when validation fails. Avoid scattering ad-hoc checks across handlers; instead, compose authentication into your routing using Axum’s middleware or nested routers with guards.

Below is a minimal, secure example of API key validation in Axum. The key is read from the X-API-Key header, compared against a constant-time comparison to reduce timing risks, and rejected with a 401 if missing or invalid. For production, store allowed keys securely (for example, in environment variables or a secrets manager) and avoid logging raw keys.

use axum::{{
    async_trait,
    extract::{FromRequest, Request},
    http::{self, StatusCode},
    response::IntoResponse,
    routing::get,
    Router,
}};
use std::net::SocketAddr;
use std::sync::Arc;

#[derive(Clone)]
struct ApiKeyValidator {
    allowed_key: String,
}

#[derive(Debug, Clone)]
struct ValidatedKey(String);

#[async_trait]
impl FromRequest for ValidatedKey
where
    S: Send + Sync,
{
    type Rejection = impl IntoResponse;

    async fn from_request(req: Request, _state: &S) -> Result {
        let key = req.headers()
            .get("X-API-Key")
            .and_then(|v| v.to_str().ok())
            .filter(|k| subtle::ConstantTimeEq::ct_eq(k.as_ref(), &self.0.as_bytes()).into());

        match key {
            Some(k) => Ok(ValidatedKey(k.to_string())),
            None => (StatusCode::UNAUTHORIZED, "Invalid API key").into_response(),
        }
    }
}

async fn handler(_key: ValidatedKey) -> &'static str {
    "Authenticated"
}

#[tokio::main]
async fn main() {
    let validator = ApiKeyValidator {
        allowed_key: std::env::var("API_KEY").expect("API_KEY must be set"),
    };

    let app = Router::new()
        .route("/secure", get(handler))
        .with_state(Arc::new(validator));

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

For broader protection, apply the extractor to a router subtree so that all endpoints under a prefix inherit the requirement. You can also layer this with role or scope checks by extending the validator to inspect claims or a permissions store associated with the key. When using the middleBrick CLI (middlebrick scan <url>) or the Web Dashboard, you can verify that routes requiring keys are consistently enforced and that no path bypasses validation.

If your service exposes an OpenAPI spec, ensure that security schemes for API keys are correctly declared and that each relevant operation references them. The middleBrick Pro plan supports continuous monitoring and CI/CD integration, which can alert you if new endpoints are added without corresponding authentication requirements. This helps maintain consistent authentication posture as the API evolves.

Related CWEs: authentication

CWE IDNameSeverity
CWE-287Improper Authentication CRITICAL
CWE-306Missing Authentication for Critical Function CRITICAL
CWE-307Brute Force HIGH
CWE-308Single-Factor Authentication MEDIUM
CWE-309Use of Password System for Primary Authentication MEDIUM
CWE-347Improper Verification of Cryptographic Signature HIGH
CWE-384Session Fixation HIGH
CWE-521Weak Password Requirements MEDIUM
CWE-613Insufficient Session Expiration MEDIUM
CWE-640Weak Password Recovery HIGH

Frequently Asked Questions

What should I do if my Axum API key is accidentally exposed in logs or client-side code?
Rotate the key immediately by updating the allowed value stored in your secure configuration or secrets manager. Audit recent logs for exposure, revoke the compromised key, and redeploy the updated key to services. Consider adding rate limits and monitoring for unusual request patterns associated with the exposed key.
How can I verify that my API key validation is enforced across all routes in an Axum service?
Use an unauthenticated scan with a tool like middleBrick (run middlebrick scan <your-api-url>) to identify endpoints that do not require a key. Review your route definitions and middleware stack to ensure the key extractor is applied consistently, and validate that no routes are skipped due to ordering or router nesting issues.