Integrity Failures in Axum with Api Keys
Integrity Failures in Axum with Api Keys — how this specific combination creates or exposes the vulnerability
An integrity failure occurs when an API does not adequately verify that a request originates from a trusted source or that parameters have not been tampered with. In Axum, combining weak API key handling with missing validation can turn a simple key check into a path for privilege escalation or data manipulation. Axum is a Rust web framework, and developers often store API keys in headers or query parameters. If these keys are passed to downstream services, written to logs, or used to make authorization decisions without integrity checks, an attacker can replay, modify, or inject keys to gain higher privileges.
Consider an Axum handler that retrieves an API key from a header and uses it to fetch tenant-scoped permissions. If the handler does not validate the key against a cryptographically signed token or a server-side mapping, an attacker can supply any string and potentially be treated as a valid key. Worse, if the key is included in logs or error messages, it can be exfiltrated via log injection or SSRF. MiddleBrick’s LLM/AI Security checks detect system prompt leakage and unsafe consumption patterns that could expose keys in responses, while its BOLA/IDOR and Property Authorization checks verify whether key-based access respects ownership boundaries.
In practice, an integrity failure with API keys in Axum often maps to OWASP API Top 10:2023 A01 (Broken Object Level Authorization) and A07 (Identification and Authentication Failures). For example, an endpoint like /api/v1/tenant/{id}/settings that accepts a header X-API-Key but does not bind the key to the tenant ID can allow a low-privilege key to read or modify another tenant’s settings. Runtime findings from a scan may show that unauthenticated endpoints accept API key-like values, or that spec definitions declare key requirements but implementation checks are missing or inconsistent. This mismatch between declared and enforced integrity is a common root cause of data exposure and privilege escalation.
MiddleBrick’s OpenAPI/Swagger spec analysis resolves all $ref references and cross-references definitions with runtime behavior, highlighting where key usage is declared but not enforced. For instance, if the spec marks an endpoint as requiring an API key but the Axum handler lacks a guard, the scan reports a finding with severity and remediation guidance. Because scans run in 5–15 seconds without credentials, teams can quickly identify integrity gaps introduced by recent code changes or dependency updates.
When API keys are used alongside tokens or session cookies, integrity failures can also arise from mixing authentication schemes. An Axum service that validates a cookie but ignores a missing or malformed API key may inadvertently treat an unauthenticated request as authorized. The scanner’s Authentication and Unsafe Consumption checks surface these gaps, ensuring that key-based checks are neither bypassed nor silently ignored.
Api Keys-Specific Remediation in Axum — concrete code fixes
Remediation focuses on strict validation, binding keys to resources, and avoiding key leakage. In Axum, implement a dedicated extractor that verifies API keys against a trusted store and enforces scope and ownership checks before processing a request.
First, define a strong key format and store hashed keys in your database. Never pass raw keys through logs or responses. Use middleware to extract and validate keys early in the pipeline. The following example shows an Axum middleware that checks a key against a hash map and attaches tenant-aware claims to the request extensions:
use axum::{{
async_trait,
extract::{FromRequest, Request},
http::{
header::{AUTHORIZATION, HeaderValue},
StatusCode,
},
response::IntoResponse,
Extension,
}};
use std::{collections::HashMap, sync::Arc};
use uuid::Uuid;
// Simulated DB of hashed keys mapped to tenant and scopes
struct ApiKeyStore(Arc)>>);
#[async_trait]
impl FromRequest for (Uuid, Vec)
where
S: Send + Sync,
{
type Rejection = (StatusCode, String);
async fn from_request(req: Request, state: &S) -> Result {
let store = req.extensions().get::>().ok_or_else(|| {
(StatusCode::INTERNAL_SERVER_ERROR, "Missing key store".to_string())
})?;
let header = req.headers().get(AUTHORIZATION)
.and_then(|v| v.to_str().ok())
.ok_or_else(|| (StatusCode::UNAUTHORIZED, "Missing or invalid Authorization header".to_string()))?;
let key = header.strip_prefix("ApiKey ").ok_or_else(|| {
(StatusCode::UNAUTHORIZED, "Invalid key format".to_string())
})?.to_string();
match store.0.get(&key) {
Some((tenant_id, scopes)) => Ok((*tenant_id, scopes.clone())),
None => Err((StatusCode::FORBIDDEN, "Invalid API key".to_string())),
}
}
}
// Handler using the extractor
async fn get_tenant_settings(
Extension(tenant_id): Extension,
(tenant_key, scopes): (Uuid, Vec),
) -> impl IntoResponse {
// Ensure tenant_key matches the requested tenant (BOLA/IDOR prevention)
if tenant_key != tenant_id {
return (StatusCode::FORBIDDEN, "Access denied");
}
// Proceed with scoped logic
(StatusCode::OK, "Settings")
}
// Build app with store
let store = Arc::new(ApiKeyStore(Arc::new([
("a1b2c3d4".to_string(), (Uuid::new_v4(), vec!["read:settings".to_string()])),
].iter().cloned().collect())));
let app = Router::new()
.route("/api/v1/tenant/:id/settings", get(get_tenant_settings))
.layer(Extension(store));
This pattern ensures that each request validates the key and binds it to the intended tenant, reducing integrity failures. For production, replace the hash map with a database lookup and use constant-time comparison for hashed keys.
Additionally, enforce HTTPS to prevent key interception and apply rate limiting to deter brute-force attempts. MiddleBrick’s Pro plan includes continuous monitoring and CI/CD integration; the GitHub Action can fail builds if a scan detects that an endpoint declares API key usage but lacks proper validation in the source code. Use the CLI to verify changes locally: middlebrick scan <url>.
Finally, avoid returning API keys in error messages or logs. Structured logging that redacts keys helps prevent accidental exfiltration. Combine these practices with regular scans to maintain integrity as your API evolves.
Frequently Asked Questions
How does MiddleBrick detect integrity failures involving API keys?
Can MiddleBrick’s scans be integrated into the Axum development workflow?
middlebrick scan <url> for local testing, or add the GitHub Action to your CI/CD pipeline to fail builds if a scan’s risk score drops below your chosen threshold. The dashboard also supports tracking scores over time.