Excessive Data Exposure in Axum with Api Keys
Excessive Data Exposure in Axum with Api Keys
Excessive Data Exposure occurs when an API returns more information than necessary for a given operation, and in Axum services this risk is amplified when API keys are handled carelessly. An Axum handler that includes an API key in a response body, logs it inadvertently, or exposes it through error messages can lead to credential leakage even when the endpoint itself is otherwise functionally correct.
In Axum, API keys are often passed via headers (e.g., x-api-key) and validated before business logic runs. If validation succeeds but the handler then serializes the request or debug information into the JSON response, the key may travel to clients that should never see it. For example, returning a full configuration struct that contains a key field will expose the credential to any caller, regardless of their authorization scope.
Another common pattern in Axum is to embed API keys within business data structures for downstream service communication. If these structures are shared directly through response serialization, the key can be unintentionally surfaced. This is especially risky when combined with overly broad CORS policies or missing authorization on endpoints that should be restricted to internal services only.
The combination of Axum’s type-driven routing and serialization via Serde makes it straightforward to build endpoints, but it also means developers must be deliberate about what fields are included in responses. An endpoint that returns a user profile alongside a service API key demonstrates Excessive Data Exposure because the key is not required for the profile use case and should be isolated to backend communication only.
Real-world attack patterns mirror this: an unauthenticated or low-privilege client calls an endpoint expecting basic data, and receives an API key that can be reused to impersonate backend services. This can lead to privilege escalation, data exfiltration, or lateral movement within an architecture that relies on key-based authentication. The risk is elevated when keys are long-lived and when logging or debugging output is accidentally included in responses during development that persists into production.
middleBrick scans for this class of issue by correlating OpenAPI/Swagger definitions with runtime behavior, looking for responses that include fields commonly named api_key, apikey, or similar, and checking whether those endpoints lack proper authorization or scope checks. The scanner does not fix the exposure, but it provides findings with severity ratings and remediation guidance to help developers isolate keys to backend contexts only.
Api Keys-Specific Remediation in Axum
Remediation focuses on preventing API keys from appearing in HTTP responses and ensuring they are handled only in secure backend contexts. In Axum, this means carefully designing response structs, avoiding serialization of key-bearing configuration, and using middleware to strip or hide keys from logs and error outputs.
First, define distinct request and response structs that omit sensitive fields. For instance, a configuration loader may read an API key from environment variables and use it internally, but the key should never be part of the struct serialized back to the client.
use axum::{routing::get, Router};
use std::net::SocketAddr;
use serde::Serialize;
#[derive(Serialize)]
struct PublicProfile {
user_id: u64,
username: String,
}
async fn get_profile() -> PublicProfile {
// API key used internally, not exposed
let _api_key = std::env::var("SERVICE_API_KEY").expect("KEY set");
PublicProfile {
user_id: 123,
username: "alice".to_string(),
}
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/profile", get(get_profile));
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
Second, if you must pass API keys between internal services within an Axum app, keep them in request extensions or environment variables rather than in structures that might be serialized. Middleware can inject keys for outbound calls without including them in the HTTP response.
Third, audit logging should exclude fields named similarly to api_key or secret. If you use tracing or custom log formats, ensure that serialization filters or field renaming prevent keys from being written to logs that could be exposed through log aggregation services.
Finally, validate that endpoints which handle API keys enforce appropriate authorization, even when the key itself is not returned. Combining key validation with scope checks reduces the blast radius should a key be inadvertently exposed elsewhere. The Pro plan of middleBrick supports continuous monitoring for such patterns, integrating with CI/CD via the GitHub Action to flag regressions before deployment.
Related CWEs: propertyAuthorization
| CWE ID | Name | Severity |
|---|---|---|
| CWE-915 | Mass Assignment | HIGH |