HIGH missing tlsaxumapi keys

Missing Tls in Axum with Api Keys

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

Transport Layer Security (TLS) ensures confidentiality and integrity between client and server. When an Axum API that uses API keys does not enforce TLS, keys can be captured in transit. middleBrick flags Missing TLS as a high-severity finding because API keys are bearer credentials; interception grants immediate unauthorized access.

In practice, a developer may configure Axum routes with key-based authorization but omit TLS configuration, leaving HTTP endpoints exposed. middleBrick’s scans perform unauthenticated checks and detect whether responses are served over HTTPS and whether sensitive headers are transmitted securely. Without TLS, an attacker on the same network can sniff requests using tools like tcpdump or Wireshark, extracting API keys included in headers (e.g., x-api-key). This becomes critical in shared or public networks, aligning with the OWASP API Top 10 Broken Object Level Authorization and Security Misconfiguration categories.

When API keys are transmitted without encryption, the risk extends beyond simple exposure. middleBrick’s Authentication and Data Exposure checks will identify unencrypted transmission of credentials and may surface related issues such as missing HTTP Strict Transport Security (HSTS) headers. This combination means that even if keys are rotated, interception remains possible until TLS is enforced. For services using OpenAPI specs, middleBrick resolves $ref definitions and cross-references runtime behavior, confirming whether TLS is applied consistently across operations that require keys.

The LLM/AI Security module does not directly test this scenario, but Missing TLS is a foundational control. Without it, any additional security layers (including API key validation) are undermined in transit. middleBrick reports this as a high-severity item with remediation guidance to enforce HTTPS across all endpoints and to apply TLS before enabling key-based authorization in Axum.

Api Keys-Specific Remediation in Axum — concrete code fixes

To remediate Missing TLS while using API keys in Axum, enforce HTTPS at the server or proxy level and validate keys only after transport security is established. Below are concrete Axum examples demonstrating secure setup with API key authorization over TLS.

Example 1: Basic Axum service with HTTPS and API key validation

use axum::{routing::get, Router, extract::State};
use std::net::SocketAddr;
use axum::http::HeaderValue;

struct ApiKeyState {
    valid_key: String,
}

async fn handler(
    State(state): State<ApiKeyState>,
    headers: axum::http::HeaderMap,
) -> String {
    match headers.get("x-api-key") {
        Some(key) if key == &HeaderValue::from_str(&state.valid_key).unwrap() =
            "Welcome".to_string(),
        _ => {
            use axum::http::StatusCode;
            (StatusCode::UNAUTHORIZED, "Invalid or missing API key").into_response()
        }
    }
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/secure", get(handler))
        .with_state(ApiKeyState {
            valid_key: "super-secret-key".to_string(),
        });

    let tls_config = tokio_rustls::rustls::ServerConfig::builder()
        .with_safe_defaults()
        .with_no_client_auth()
        .with_single_cert(
            vec![rustls_pemfile::certs(&mut std::io::BufReader::new(
                std::fs::File::open("cert.pem").unwrap(),
            ))
            .unwrap()
            .into_iter()
            .map(rustls::pki_types::CertificateDer::from)
            .collect()],
            rustls_pemfile::pkcs8_private_keys(&mut std::io::BufReader::new(
                std::fs::File::open("key.pem").unwrap(),
            ))
            .unwrap()
            .into_iter()
            .map(rustls::pki_types::PrivateKeyDer::from)
            .collect()
            .unwrap(),
        )
        .unwrap();

    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).tls_config(tls_config).unwrap().await.unwrap();
}

This example shows an Axum server that requires an x-api-key header and serves traffic only over TLS using tokio-rustls. The TLS configuration is supplied to axum::serve, ensuring that all communication is encrypted before API key validation occurs.

Example 2: Conditional middleware for TLS enforcement

use axum::{routing::get, Router, extract::Extension, async_trait};
use std::convert::Infallible;

async fn enforce_https(req: axum::http::Request<B>) -> Result<axum::http::Request<B>, (axum::http::StatusCode, String)> {
    if req.uri().scheme_str() != Some("https") {
        Err((axum::http::StatusCode::FORBIDDEN, "HTTPS required".into()))
    } else {
        Ok(req)
    }
}

async fn handler_with_key(
    Extension(state): Extension<ApiKeyState>,
    headers: axum::http::HeaderMap,
) -> String {
    // same key validation as before
    match headers.get("x-api-key") {
        Some(k) if k == &HeaderValue::from_str(&state.valid_key).unwrap() =
            "Authorized".to_string(),
        _ => (axum::http::StatusCode::UNAUTHORIZED, "Bad key").into_response(),
    }
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .layer(axum::middleware::from_fn(enforce_https))
        .route("/check", get(handler_with_key))
        .with_state(ApiKeyState {
            valid_key: "another-secure-key".to_string(),
        });

    // TLS configuration as in previous example
    // ...
}

This second example adds middleware that rejects non-HTTPS requests before any API key processing, ensuring that keys are never transmitted in cleartext. middleBrick’s scans will verify that both HTTPS enforcement and API key validation are present and that findings are mapped to compliance frameworks such as OWASP API Top 10 and SOC2.

Related CWEs: encryption

CWE IDNameSeverity
CWE-319Cleartext Transmission of Sensitive Information HIGH
CWE-295Improper Certificate Validation HIGH
CWE-326Inadequate Encryption Strength HIGH
CWE-327Use of a Broken or Risky Cryptographic Algorithm HIGH
CWE-328Use of Weak Hash HIGH
CWE-330Use of Insufficiently Random Values HIGH
CWE-338Use of Cryptographically Weak PRNG MEDIUM
CWE-693Protection Mechanism Failure MEDIUM
CWE-757Selection of Less-Secure Algorithm During Negotiation HIGH
CWE-261Weak Encoding for Password HIGH

Frequently Asked Questions

Why does Missing TLS in Axum with API keys result in a high-severity finding?
Because API keys act as bearer tokens, transmitting them without TLS allows interception. middleBrick detects unencrypted credential transmission and maps it to high-severity risks under authentication and data exposure checks.
Can middleBrick verify that TLS is enforced for all endpoints in an Axum API?
Yes. middleBrick scans the unauthenticated attack surface, validates HTTPS availability, and cross-references OpenAPI spec definitions with runtime behavior to confirm consistent TLS usage across operations that involve API keys.