HIGH xml external entitiesaxumjwt tokens

Xml External Entities in Axum with Jwt Tokens

Xml External Entities in Axum with Jwt Tokens — how this specific combination creates or exposes the vulnerability

XML External Entity (XXE) injection occurs when an application processes XML input that references external entities, and those entities are resolved in an unsafe way. In Axum, a web framework for Rust, this risk can intersect with JWT token handling when incoming requests carry XML payloads (for example, during legacy federation or SAML-style flows) and the application deserializes or logs those payloads before validating the JWT.

Consider a scenario where an endpoint accepts an HTTP Authorization header containing a JWT, but also supports an XML body for compatibility. If the XML parser is configured to resolve external entities, an attacker can supply an XML document with a DOCTYPE that defines an external file reference or a URL fetch. Even though the JWT is present and may be validated later, the XML parser runs before or independently of the token verification step. By leveraging entities such as &file; or &http;, the attacker can cause the server to read local files like /etc/passwd or make outbound HTTP requests, exfiltrating data through SSRF or local file inclusion paths. These actions are captured in the middleBrick scan under Data Exposure, SSRF, and Input Validation checks.

Because Axum is asynchronous and often uses extractors for both headers and body, a developer might parse the JWT in one extractor and the XML in another. If the XML extractor enables entity resolution, the framework may recursively expand references, leading to denial of service via billion laughs attacks or information disclosure. The JWT itself does not prevent XXE; it is merely a bearer token. The vulnerability exists in the XML processing configuration, not in the token format. The middleBrick OpenAPI/Swagger analysis can detect unsafe parser settings by correlating spec definitions with runtime behavior, flagging endpoints that accept XML without strict entity disabling.

During a black-box scan, middleBrick runs 12 security checks in parallel, including Authentication, Input Validation, and Data Exposure. For an endpoint that combines JWT tokens and XML, a test payload with a malicious DOCTYPE can reveal whether the server resolves external references. A positive finding would highlight insecure deserialization patterns and missing parser hardening. Remediation focuses on disabling external entities and external DTDs in the XML parser, ensuring that JWT validation occurs before any sensitive data processing, and avoiding mixing untrusted XML with trusted token handling.

Jwt Tokens-Specific Remediation in Axum — concrete code fixes

To mitigate XXE when JWT tokens are involved in Axum, you must configure the XML parser to prohibit external entity resolution and structure your extractors so that token validation is independent and fails safely if parsing is unsafe. Below are concrete code examples using the xml-rs crate with a secure configuration and a JWT extraction pattern that avoids mixing concerns.

Secure XML parser configuration

Disable external entities and DOCTYPE declarations explicitly. Using xml-rs, create a reader with features turned off:

use xml::reader::{EventReader, XmlEvent};
use std::io::Cursor;

fn parse_xml_safely(input: &str) -> Result<(), String> {
    let cursor = Cursor::new(input);
    let parser = EventReader::new(cursor);
    // Ensure no external entities are resolved by not registering external entity handlers.
    for event in parser {
        match event.map_err(|e| e.to_string())? {
            XmlEvent::StartElement { name, .. } => {
                // Process elements safely, avoid expanding entities
                println!("Start element: {:?}", name);
            }
            XmlEvent::EndElement { name } => {
                println!("End element: {:?}", name);
            }
            XmlEvent::Characters(chars) => {
                println!("Characters: {}", chars);
            }
            // Explicitly ignore any DOCTYPE or entity events
            XmlEvent::StartDocument { .. } => {}
            XmlEvent::EndDocument => {}
            _ => {}
        }
    }
    Ok(())
}

JWT extraction and validation in Axum extractors

Use Axum extractors to separate authentication from body parsing. Validate the JWT before processing any XML, and return an error early if the token is invalid. This ensures that even if XML parsing were unsafe, sensitive operations are guarded by a verified token.

use axum::{
    async_trait,
    extract::{FromRequest, Request},
    http::StatusCode,
};
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
struct Claims {
    sub: String,
    exp: usize,
}

struct Jwt(String);

#[async_trait]
impl

Combining both safely in a handler

In your route handler, first extract and validate the JWT, then parse the XML only if needed. Avoid passing untrusted XML to legacy parsers that resolve external entities by default.

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

async fn handler(
    Jwt(token): Jwt,
    body: String,
) -> Result<String, (StatusCode, String)> {
    // Token is already validated by the extractor
    parse_xml_safely(&body)?;
    Ok("OK".to_string())
}

fn app() -> Router {
    Router::new().route("/secure", post(handler))
}

By hardening the XML parser and decoupling JWT validation from XML processing, you reduce the attack surface. The middleBrick CLI can be used to verify that endpoints no longer resolve external entities, and the GitHub Action can enforce that new code does not reintroduce unsafe patterns.

Frequently Asked Questions

Can XXE still occur if the JWT is validated before XML parsing?
Yes. The vulnerability depends on the XML parser configuration, not the order of token validation. If the parser resolves external entities, XXE can happen regardless of when the JWT is checked.
Does the presence of a JWT token affect how middleBrick scans for XXE?
middleBrick tests the unauthenticated attack surface. While JWTs can affect authentication checks, XXE is evaluated based on whether the endpoint processes XML with unsafe entity resolution. The scan focuses on parser behavior and spec-defined inputs rather than token handling.