HIGH hallucination attacksaxumjwt tokens

Hallucination Attacks in Axum with Jwt Tokens

Hallucination Attacks in Axum with Jwt Tokens — how this specific combination creates or exposes the vulnerability

Axum is a Rust web framework where route handlers often validate JSON Web Tokens (JWT) to enforce authentication and identity. When JWT validation is implemented incorrectly or incompletely, it can enable hallucination attacks: an attacker fabricates or manipulates token claims to impersonate users, escalate privileges, or bypass authorization checks. In Axum, this commonly occurs when applications decode and verify JWTs but fail to enforce strict claim validation, audience/issuer checks, or proper key management.

Specifically, if an Axum handler decodes a JWT without verifying the signature or ignores token metadata such as iss (issuer), aud (audience), and exp (expiration), an attacker can reuse an older token, modify payload claims, or inject administrative flags (e.g., "is_admin": true) to hallucinate authorized access. Because Axum typically uses extractor patterns (e.g., Extension<JwtValidator> or custom guards), missing validation logic can be inadvertently inherited across routes, creating broad exposure across multiple endpoints.

Another vector involves unauthenticated LLM endpoints or misconfigured token introspection in APIs that expose model endpoints. If an Axum service exposes an LLM endpoint that trusts JWT-derived user context without re-validating token scope or session binding, an attacker can prompt-inject or exploit excessive agency to hallucinate data or actions on behalf of other users. This is particularly risky when token validation is performed once at middleware level and subsequent internal calls assume trust without re-checking authorization for sensitive operations.

OpenAPI/Swagger spec analysis can highlight these risks when spec definitions describe security schemes based on bearer tokens but runtime checks are incomplete. Cross-referencing spec definitions with runtime findings helps detect mismatches such as missing required claims or overly permissive scopes that facilitate hallucination. Since middleBrick scans the unauthenticated attack surface and tests authentication and authorization checks in parallel, it can surface these gaps without requiring credentials.

Real-world attack patterns include modifying the sub claim to impersonate another user, changing role-based claims to bypass property-level authorization, or removing exp to use long-lived tokens indefinitely. These map to common weaknesses under OWASP API Top 10 A07:2021 — Identification and Authentication Failures and A01:2027 — Broken Object Level Authorization, and may intersect with BOLA/IDOR when object references are derived from token claims.

Jwt Tokens-Specific Remediation in Axum — concrete code fixes

Remediation centers on strict JWT validation in Axum extractors and middleware, ensuring every route that relies on identity re-validates critical claims and scope. Use a dedicated validator that verifies signatures, checks issuer and audience, and enforces expiration. Below are concrete, working examples for Axum using the jsonwebtoken crate.

First, define your claims and validator:

use axum::extract::Extension;
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation, TokenData};
use serde::{Deserialize, Serialize};
use std::sync::Arc;

#[derive(Debug, Serialize, Deserialize)]
struct Claims {
    sub: String,
    iss: String,
    aud: String,
    exp: usize,
    roles: Vec<String>,
}

#[derive(Clone)]
struct JwtValidator {
    decoding_key: DecodingKey,
    issuer: String,
    audience: String,
}

impl JwtValidator {
    fn new(secret: String, issuer: String, audience: String) -> Self {
        Self {
            decoding_key: DecodingKey::from_secret(secret.as_ref()),
            issuer,
            audience,
        }
    }

    fn validate(&self, token: &str) -> Result<TokenData<Claims>, jsonwebtoken::Error> {
        let mut validation = Validation::new(Algorithm::HS256);
        validation.validate_exp = true;
        validation.validate_nbf = true;
        validation.validate_iss = true;
        validation.validate_aud = true;
        validation.iss = Some(&[self.issuer.as_str()]);
        validation.aud = Some(&[self.audience.as_str()]);
        decode<Claims>(token, &self.decoding_key, &validation)
    }
}

Then, mount the validator in your Axum app and use an extractor that rejects invalid tokens:

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

async fn protected_handler(Extension(claims): Extension<Claims>) -> String {
    format!("Hello, user: {} with roles: {:?}", claims.sub, claims.roles)
}

#[tokio::main]
async fn main() {
    let validator = Arc::new(JwtValidator::new(
        "super-secret-key".to_string(),
        "my-issuer".to_string(),
        "my-audience".to_string(),
    ));

    let app = Router::new()
        .route("/profile", get(protected_handler))
        .layer(axum::middleware::from_fn_with_extractor(
            move |token: String| {
                let validator = validator.clone();
                async move {
                    validator.validate(&token).map_err(|e| {
                        axum::http::StatusCode::UNAUTHORIZED
                    })?;
                    // In practice, extract claims from token and pass via Extension
                    // This is simplified to show validation step
                    Ok(claims)
                }
            },
        ));

    // axum::Server::bind("0.0.0.0:3000").serve(app.into_make_service()).await.unwrap();
}

For production, rotate keys and prefer asymmetric algorithms (RS256/ES256) with JWKS retrieval. Always re-validate sensitive claims per request and avoid storing authorization decisions derived solely from token payload without runtime checks.

Related CWEs: llmSecurity

CWE IDNameSeverity
CWE-754Improper Check for Unusual or Exceptional Conditions MEDIUM

Frequently Asked Questions

Can hallucination attacks bypass property-level authorization when JWTs contain role claims?
Yes, if Axum routes trust role claims in JWTs without re-checking object-level permissions, attackers can hallucinate access to other users' resources by manipulating the subject or role claims.
Does middleBrick detect JWT validation weaknesses that enable hallucination attacks in Axum APIs?
Yes, middleBrick runs authentication and authorization checks in parallel and maps findings to frameworks like OWASP API Top 10, identifying missing issuer/audience/exp validation and token manipulation risks.