HIGH pii leakageactixbearer tokens

Pii Leakage in Actix with Bearer Tokens

Pii Leakage in Actix with Bearer Tokens — how this specific combination creates or exposes the vulnerability

Actix Web is a widely used Rust framework for building HTTP services. When Bearer Tokens are used for authorization, PII leakage can occur if token handling, logging, error messages, and data serialization are not carefully controlled. The combination of Actix and Bearer Tokens introduces specific risks because tokens often carry identity or scope claims that, if exposed, can reveal user information or enable abuse.

One common pattern is extracting the Bearer token from the Authorization header and passing it through request extensions or logging statements. If developers inadvertently log the full header or include the token in structured logs, PII such as user identifiers embedded in the token payload can be exposed. For example, a token containing a subject claim (sub) or email (email) becomes a direct data exposure vector when logs are not sanitized.

Another risk arises from error handling. Actix handlers that return detailed errors including authorization failures can inadvertently echo the token or its claims if responses include header values or debug information. Without proper response filtering, an attacker can infer valid tokens or usernames from verbose error messages, leading to information disclosure.

Serialization of responses can also contribute to PII leakage. If API responses include user data derived from token claims and the serialization layer does not exclude sensitive fields, those fields may be returned to clients. For instance, an endpoint that uses the token’s sub to look up a user profile might return the full user record including email, phone, or other PII, even when only a subset is necessary.

Middleware and guards that rely on Bearer tokens must ensure they do not propagate tokens into downstream services or worker threads without stripping unnecessary claims. Cross-service calls that forward Authorization headers without redaction can extend the exposure surface. In distributed tracing or metrics contexts, attaching token values to span contexts can further amplify leakage by persisting PII across systems.

Finally, insecure deserialization or misuse of extractors can cause tokens or their embedded claims to be stored temporarily in structures that are serialized for debugging or caching. If those artifacts are written to disk or transmitted over insecure channels, the embedded PII becomes accessible to unauthorized parties.

Bearer Tokens-Specific Remediation in Actix — concrete code fixes

Remediation focuses on preventing unintended exposure of token contents and ensuring that PII derived from tokens is handled with minimal privilege and strict lifecycle controls.

  • Avoid logging tokens or claims: Ensure that logging macros do not include the Authorization header or token claims. Use field redaction when structured logging is required.
  • Sanitize error responses: Return generic error messages for authorization failures without echoing token values or internal identifiers.
  • Limit response serialization: Use serialization filters or DTOs to ensure only required fields are emitted, excluding PII derived from token claims unless explicitly needed.
  • Control header propagation: Do not forward Authorization headers to downstream services unless necessary. If forwarded, strip or replace tokens with opaque references where possible.
  • Secure middleware and guards: Validate token structure and claims without storing raw tokens in request extensions used for debugging or tracing.

Below are concrete Actix examples demonstrating secure handling of Bearer tokens.

// src/main.rs
use actix_web::{web, App, HttpServer, HttpResponse, HttpRequest, Error};
use actix_web::http::header::HeaderValue;
use actix_web::dev::ServiceRequest;
use actix_web::http::header::AUTHORIZATION;
use std::future::{ready, Ready};

// A guard that extracts and validates a Bearer token without logging it
fn validate_token(req: &ServiceRequest) -> Result {
    if let Some(auth_header) = req.headers().get(AUTHORIZATION) {
        if let Ok(auth_str) = auth_header.to_str() {
            if auth_str.starts_with("Bearer ") {
                let token = &auth_str[7..];
                // Perform validation (e.g., verify signature, check revocation)
                // Do NOT log `token` or its decoded claims here
                if is_valid_token(token) {
                    return Ok(true);
                }
            }
        }
    }
    Ok(false)
}

fn is_valid_token(token: &str) -> bool {
    // Placeholder: integrate with your auth provider
    !token.is_empty()
}

async fn profile_handler(req: HttpRequest) -> HttpResponse {
    // Derive a user ID from validated claims, not from logging the token
    let user_id = match req.extensions().get::() {
        Some(id) => id.clone(),
        None => return HttpResponse::Unauthorized().json(serde_json::json!({"error": "unauthorized"})),
    };
    // Return only necessary fields; exclude PII unless required
    HttpResponse::Ok().json(serde_json::json!({
        "user_id": user_id,
        "subscription": "premium"
    }))
}

async fn index() -> HttpResponse {
    HttpResponse::Ok().body("API is running")
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .wrap(actix_web::middleware::Logger::default())
            // Custom guard to validate token before routing
            .service(
                web::resource("/profile")
                    .route(web::get().to(profile_handler))
            )
            .service(web::resource("/").route(web::get().to(index)))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

The above example shows a validation guard that avoids logging the raw token. The profile handler uses extensions to access a validated user identifier rather than re-parsing the token on each request, reducing the chance of accidental exposure. For production use, integrate a robust token validation library and ensure that any structured logging excludes sensitive fields.

Additionally, consider using Actix's data facilities to pass minimal claim-derived data (e.g., user ID) instead of the full token, and apply response serialization filters to strip PII before transmission.

Related CWEs: dataExposure

CWE IDNameSeverity
CWE-200Exposure of Sensitive Information HIGH
CWE-209Error Information Disclosure MEDIUM
CWE-213Exposure of Sensitive Information Due to Incompatible Policies HIGH
CWE-215Insertion of Sensitive Information Into Debugging Code MEDIUM
CWE-312Cleartext Storage of Sensitive Information HIGH
CWE-359Exposure of Private Personal Information (PII) HIGH
CWE-522Insufficiently Protected Credentials CRITICAL
CWE-532Insertion of Sensitive Information into Log File MEDIUM
CWE-538Insertion of Sensitive Information into Externally-Accessible File HIGH
CWE-540Inclusion of Sensitive Information in Source Code HIGH

Frequently Asked Questions

Can middleBrick detect PII leakage in Actix APIs that use Bearer Tokens?
Yes. middleBrick runs 12 security checks in parallel, including Data Exposure and Unsafe Consumption, and it uses OpenAPI/Swagger spec analysis with full $ref resolution to correlate runtime findings with schema definitions, helping to identify PII leakage risks in Actix APIs that use Bearer Tokens.
Does middleBrick test for Bearer Token handling issues such as logging or error message leakage?
Yes. middleBrick performs unauthenticated black-box testing focused on the attack surface. While it does not fix or block issues, it provides prioritized findings with severity and remediation guidance for issues such as token leakage in logs or error responses, including how these may relate to authentication mechanisms like Bearer Tokens.