Pii Leakage in Actix with Hmac Signatures
Pii Leakage in Actix with Hmac Signatures — how this specific combination creates or exposes the vulnerability
Actix-web is a popular Rust framework for building HTTP services. When HMAC signatures are used for request authentication, developers often focus on verifying integrity and origin, but may inadvertently expose personally identifiable information (PII) through logs, error messages, or reflection of input data in responses.
One common pattern is to include PII such as email addresses or usernames inside the signed payload or HTTP headers to identify the actor. If the application logs incoming requests verbatim, including headers and query parameters, PII can be written to persistent storage or monitoring systems. For example, a header like x-user-email: alice@example.com might be logged in access logs in clear text, creating a data exposure path.
Another vector arises when HMAC verification fails and the framework returns detailed errors that echo back parts of the signed payload or headers. If the error response includes the received payload or header values, an attacker can learn whether specific PII values are valid by observing differences in error messages. In Actix, this can occur if custom error handlers inadvertently serialize request parts into response bodies or logs during debugging.
Middleware or interceptors that inspect HMAC headers may also copy header values into structured objects or tracing contexts that are retained beyond the request lifecycle. If these contexts include PII and are exposed through debug endpoints, metrics, or logs, the data can be leaked. For instance, storing the authenticated subject (e.g., user ID or email) in request extensions for later use is safe only if those extensions are cleared and never serialized or logged.
Additionally, reflection attacks can occur when the server includes data from the signed payload in responses without careful sanitization. If a client sends a JSON body containing PII and the server echoes back fields (even partially) upon success, the response may leak that PII to unintended parties, especially if responses are cached or logged by intermediaries.
To detect this using unauthenticated scanning, middleBrick runs checks focused on Data Exposure and Input Validation across authenticated-like surfaces (testing what is observable without credentials). The LLM/AI Security module further probes whether endpoints reflecting data in responses or logs might inadvertently disclose PII, and whether HMAC usage patterns create side channels that assist an attacker in correlating signatures with identifiable information.
Hmac Signatures-Specific Remediation in Actix — concrete code fixes
Remediation focuses on preventing PII from entering logging paths, avoiding reflection of sensitive data, and ensuring HMAC verification logic does not amplify information leakage.
First, sanitize what is logged. Use structured logging that excludes headers or bodies containing PII. In Actix, you can wrap the service and filter out sensitive headers before logging. For example:
use actix_web::{dev::ServiceRequest, Error};
use actix_web_httpauth::extractors::bearer::BearerAuth;
async fn verify_hmac_and_log(req: ServiceRequest) -> Result {
// Extract HMAC from headers without logging raw header values
let headers = req.headers();
if let Some(hmac_value) = headers.get("x-hmac-signature") {
// Do NOT log hmac_value or any PII-containing headers
// Instead, log only metadata like request path and method
tracing::info!("request_path={} method={}", req.path(), req.method());
}
// Continue processing
Ok(req)
}
Second, ensure error responses do not reflect PII. Standardize error messages to generic descriptions and avoid echoing payload content. For HMAC verification, return a uniform 401/403 without indicating which part failed:
use actix_web::{web, HttpResponse, Result};
use hmac::{Hmac, Mac};
use sha2::Sha256;
type HmacSha256 = Hmac;
async fn verify_signature(body: web::Json, headers: web::Header) -> Result> {
let signature = match headers.get("x-api-signature") {
Some(v) => v.to_str().unwrap_or(""),
None => return Err(actix_web::error::ErrorUnauthorized("invalid signature")),
};
let secret = std::env::var("HMAC_SECRET").expect("HMAC_SECRET must be set");
let mut mac = HmacSha256::new_from_slice(secret.as_bytes()).expect("HMAC can take key of any size");
mac.update(body.as_bytes());
match mac.verify_slice(signature.as_bytes()) {
Ok(_) => Ok(body),
Err(_) => Err(actix_web::error::ErrorUnauthorized("invalid signature")),
}
}
Third, avoid storing PII in request extensions used for tracing or metrics. If you must pass a subject identifier, use a non-PII stable ID (e.g., a numeric user ID) and ensure extensions are scoped to the request and not serialized:
use actix_web::dev::Extensions;
use std::num::NonZeroU64;
fn set_subject_id(req: &mut actix_web::dev::ServiceRequest, user_id: NonZeroU64) {
req.extensions_mut().insert(user_id);
// Do not include email or username in extensions
}
fn get_subject_id(req: &actix_web::dev::ServiceRequest) -> Option {
req.extensions().get::().copied()
}
Fourth, if you accept file uploads or JSON with potential PII, do not echo fields in success responses. Instead, return minimal confirmation data that does not reflect client content:
async fn upload_handler(payload: web::Json) -> web::Json {
// Process PII-containing payload without echoing it back
web::Json(serde_json::json!({ "status": "ok" }))
}
Finally, adopt continuous scanning via middleBrick Pro to detect whether your deployed endpoints reflect PII in responses or logs. The GitHub Action can gate merges if new endpoints introduce risky patterns, and the MCP Server allows you to scan API definitions directly from your IDE, catching problematic echo patterns before deployment.
Related CWEs: dataExposure
| CWE ID | Name | Severity |
|---|---|---|
| CWE-200 | Exposure of Sensitive Information | HIGH |
| CWE-209 | Error Information Disclosure | MEDIUM |
| CWE-213 | Exposure of Sensitive Information Due to Incompatible Policies | HIGH |
| CWE-215 | Insertion of Sensitive Information Into Debugging Code | MEDIUM |
| CWE-312 | Cleartext Storage of Sensitive Information | HIGH |
| CWE-359 | Exposure of Private Personal Information (PII) | HIGH |
| CWE-522 | Insufficiently Protected Credentials | CRITICAL |
| CWE-532 | Insertion of Sensitive Information into Log File | MEDIUM |
| CWE-538 | Insertion of Sensitive Information into Externally-Accessible File | HIGH |
| CWE-540 | Inclusion of Sensitive Information in Source Code | HIGH |