Token Leakage in Actix with Api Keys
Token Leakage in Actix with Api Keys — how this specific combination creates or exposes the vulnerability
Token leakage in Actix web applications occurs when API keys or session tokens are exposed through logs, error messages, URLs, or insecure headers. In Actix, a Rust web framework, developers often pass API keys via request headers or query parameters. If these values are inadvertently logged or reflected in responses, tokens can be exposed to unauthorized parties. For example, echoing an Authorization: ApiKey <key> header in a debug response or writing it to application logs can create a leakage path.
When API keys are handled in Actix handlers without care, the unauthenticated attack surface tested by middleBrick’s Authentication and Data Exposure checks can surface these mistakes. A handler that returns the incoming key as part of a JSON payload, or concatenates keys into URLs or redirect locations, can disclose secrets. MiddleBrick’s checks include sensitive data discovery and output scanning, which can detect whether API keys appear in responses or logs during the scan.
Actix middleware is often used to inject or validate API keys. If middleware writes keys to structured logs or attaches them to request extensions that are later serialized (for example, when telemetry or tracing captures request metadata), leakage can occur. Tokens may also leak through HTTP referrer headers if clients are redirected with keys embedded in URLs. SSRF checks within middleBrick additionally probe whether internal endpoints inadvertently expose keys when external services are called, compounding the risk when API keys are mishandled in Actix routes or service clients.
During a middleBrick scan, the tool tests whether API keys appear in responses, logs, or error traces. It examines input validation and data exposure vectors to determine whether token leakage is present. Remediation involves ensuring keys are never echoed back, are redacted from logs, and are transmitted only over encrypted channels, which aligns with middleBrick’s Encryption and Data Exposure checks.
Api Keys-Specific Remediation in Actix — concrete code fixes
To remediate token leakage in Actix, keep API keys out of responses, logs, and client-visible URLs. Use environment variables or a secure configuration source, and ensure keys are only used server-side for outbound requests. Below are concrete code examples demonstrating secure handling.
1. Securely read API keys from environment variables and attach them as headers when calling external services without exposing them to the client:
use actix_web::{web, App, HttpResponse, HttpServer, Responder};
use std::env;
async fn call_external_api() -> actix_web::Result {
// Load API key from environment at startup; do not accept from client.
let api_key = env::var("EXTERNAL_API_KEY").expect("EXTERNAL_API_KEY must be set");
let client = reqwest::Client::new();
let res = client
.get("https://external.example.com/protected")
.header("Authorization", format!("ApiKey {}", api_key))
.send()
.await
.map_err(|e| actix_web::error::ErrorInternalServerError(e))?;
let body = res.text().await.map_err(|e| actix_web::error::ErrorInternalServerError(e))?;
// Return only necessary data; never echo the key.
Ok(HttpResponse::Ok().body(body))
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.route("/proxy", web::get().to(call_external_api))
})
.bind("127.0.0.1:8080")?
.run()
.await
}
2. Avoid logging API keys. If structured logging is used, filter or redact sensitive headers:
use actix_web::{dev::ServiceRequest, Error};
use actix_web_httpauth::extractors::bearer::BearerAuth;
/// Example middleware that redacts sensitive authorization headers from logs.
pub async fn redacted_auth_middleware(
req: ServiceRequest,
_payload: &mut actix_web::dev::Payload,
) -> Result<(ServiceRequest, Option<String>), Error> {
// Clone headers safely without moving sensitive values into logs.
let headers = req.headers();
if let Some(auth) = headers.get("authorization") {
// Do NOT log auth; redact to avoid token leakage.
tracing::info!(target: "requests", method = %req.method(), path = %req.path(), authorization = "[REDACTED]");
} else {
tracing::info!(target: "requests", method = %req.method(), path = %req.path());
}
Ok((req, None))
}
3. Do not include API keys in URLs or query parameters. Use headers instead, and ensure responses do not reflect them:
async fn safe_handler() -> HttpResponse {
// Bad: HttpResponse::Ok().body(format!("Key is: {}", key)) // DO NOT DO THIS
// Good: return data without key
HttpResponse::Ok().json(serde_json::json!({ "status": "ok" }))
}
4. For applications that must accept keys from clients (e.g., for third-party integrations), validate and scope them server-side, then use them to authorize outbound calls without returning them. Apply input validation checks and enforce strict CORS policies to reduce misuse.
middleBrick’s CLI can be used to verify these fixes: scan from terminal with middlebrick scan