HIGH missing authenticationaxumapi keys

Missing Authentication in Axum with Api Keys

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

Axum is a Rust web framework that encourages strong type safety and composable middleware. When developers choose to implement authentication via static API keys, the risk arises if the enforcement layer is incomplete or conditionally bypassed. Missing Authentication in this context means an endpoint either does not validate the presence of a key, accepts an empty or default key, or fails to propagate the authorization decision through all handler branches.

Consider an Axum handler structured to extract an API key from a header but lacking a guard that uniformly rejects requests when extraction fails. A developer might use Option and later branch on Some(key) while leaving the alternative branch open to execution. That open branch can inadvertently expose business logic or data operations that should be protected. Even when a key is present, using a permissive comparison (e.g., checking only a prefix) can allow an attacker to supply a valid-looking but unauthorized key if the validation does not enforce exact matching.

Another common pattern is to conditionally apply authentication based on feature flags or build profiles, such as skipping key checks in debug mode. If such conditional logic reaches production inadvertently, the unauthenticated path becomes a direct exposure. Attackers probing the unauthenticated surface can enumerate endpoints that rely on this weak or missing gate, leading to unauthorized read, write, or administrative actions. Because Axum’s routing can compose multiple layers, a small missing .and_then(validate_key) step in one nested route can leave an otherwise protected service vulnerable.

During a black-box scan, tools like middleBrick exercise each discovered endpoint without credentials, looking for differences in response codes, timing, or data exposure between authenticated and unauthenticated calls. If an endpoint returns 200 with data when no key is provided, or returns a generic 500 that leaks stack traces, it signals Missing Authentication. Such findings often map to OWASP API Top 10:2023 — API1:2023 Broken Object Level Authorization when authorization checks are inconsistently applied, and can be compounded by BOLA/IDOR if object identifiers are exposed without verifying the caller’s right to access them.

It is important to note that detection does not equate to remediation. middleBrick identifies these gaps and provides guidance, but the developer must implement secure patterns in Axum to ensure every route that handles sensitive operations requires strict, exact API key validation.

Api Keys-Specific Remediation in Axum — concrete code fixes

To remediate Missing Authentication in Axum when using API keys, enforce validation as a mandatory layer that applies to all protected routes. Use extractor-based guards and avoid optional branches that skip checks. Below are concrete, working examples that demonstrate correct patterns.

First, define a typed extractor that validates the key against a constant or environment source. This extractor returns a 401 if the header is missing or incorrect, preventing execution from reaching unprotected handlers:

use axum::{{
    async_trait,
    extract::{FromRequest, Request},
    http::{self, StatusCode},
}};
use std::error::Error;

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

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

    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(|&v| v == std::env::var("EXPECTED_API_KEY").unwrap_or_default())
            .ok_or((StatusCode::UNAUTHORIZED, "Invalid or missing API key"))?;
        Ok(ApiKey(key.to_string()))
    }
}

Next, apply this extractor to routes that require protection. By using .layer(ApiKey) or including ApiKey as a parameter, you ensure the handler only executes when authentication succeeds:

use axum::{routing::get, Router};

async fn protected_handler(_key: ApiKey) -> &'static str {
    "Authenticated data"
}

let app = Router::new()
    .route("/admin/config", get(protected_handler))
    .layer(axum::middleware::from_fn(|req, next| {
        // Optional: global middleware to log or enforce additional rules
        async move { next.run(req).await }
    }));

For broader coverage, you can scope a router subtree to require the key, ensuring all nested routes inherit the check:

let secure = Router::new()
    .route("/export", get(|| async { "Sensitive export" }))
    .route("/update", post(update_resource));

let app = Router::new()
    .route("/health", get(|| async { "OK" }))
    .nest("/secure", secure.layer(axum::middleware::from_fn(|req, next| {
        async move { next.run(req).await }
    })));

When using environment variables for the expected key, always ensure they are loaded securely at startup and not hard-coded. Combine this approach with transport encryption and strict header naming conventions to reduce the risk of key leakage. These patterns keep authentication mandatory and deterministic, eliminating the open branches that lead to Missing Authentication.

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

How does middleBrick detect Missing Authentication in Axum APIs?
middleBrick sends unauthenticated requests to each discovered endpoint and compares responses. It flags 200/2xx responses that return sensitive data without a key, unexpected 500 errors that may leak stack traces, and differences in behavior between calls with and without keys. Findings align with OWASP API Top 10:2023 — API1:2023 Broken Object Level Authorization when authorization checks are inconsistently applied.
Can the free plan of middleBrick be used to scan Axum endpoints for authentication issues?
Yes. The free plan provides 3 scans per month and supports submitting any URL, including Axum services, to obtain a security risk score and findings such as Missing Authentication, without requiring credentials or agents.