Pii Leakage in Actix with Jwt Tokens
Pii Leakage in Actix with Jwt Tokens — how this specific combination creates or exposes the vulnerability
Actix Web is a popular Rust framework for building HTTP services, and JWT tokens are commonly used for authentication. When JWT handling is implemented without strict controls, PII leakage can occur in several realistic scenarios. For example, developers may embed user identifiers, email addresses, or roles directly into the JWT payload for convenience. If those tokens are transmitted over non-encrypted connections, intercepted tokens expose PII in transit. Additionally, if APIs return JWTs in URLs, browser history, or logs, sensitive claims can be persisted or exposed inadvertently.
In an unauthenticated scan context, middleBrick tests the attack surface where authentication is weak or absent. If an Actix endpoint accepts JWTs but does not enforce strict validation, scope checks, or secure transmission, the scan can detect endpoints that return user data without verifying token ownership. This reflects BOLA/IDOR-like patterns where one user can access another’s data by manipulating the token or request parameters. Tokens with overly broad claims or missing audience/issuer checks can be reused across services, increasing the risk of PII exposure across microservices.
Another realistic risk occurs when Actix routes decode JWTs and merge claims into JSON responses without filtering. For instance, a token containing a user ID and email may be decoded and the entire payload serialized into an API response, unintentionally leaking PII to clients or logs. MiddleBrick’s LLM/AI Security checks include system prompt leakage detection and output scanning; while focused on AI endpoints, the same pattern illustrates how unchecked data propagation can expose sensitive information. Even in non-AI APIs, if responses include user metadata derived from JWT claims without redaction, scanners can flag Data Exposure findings.
Furthermore, if Actix services share JWTs across internal calls without re-validation, PII can propagate beyond the intended boundary. A token issued for one service might be forwarded to another with broader logging, where PII is retained in structured logs or error messages. middleBrick’s checks for Data Exposure and Unsafe Consumption are designed to surface cases where responses contain sensitive patterns such as email-like strings or common PII attributes, even when those values originate from JWT claims. This demonstrates how JWT convenience can conflict with privacy-by-design principles.
Proper configuration and validation are essential to prevent PII leakage in Actix with JWT tokens. Security checks must ensure tokens are transmitted only over encrypted channels, validated for audience and issuer, scoped to minimum required claims, and never echoed back in raw form. MiddleBrick’s parallel checks for Authentication, Data Exposure, and Unsafe Consumption help identify misconfigurations that could lead to PII exposure in JWT-driven architectures.
Jwt Tokens-Specific Remediation in Actix — concrete code fixes
To remediate PII leakage risks with JWT tokens in Actix, implement strict validation, avoid exposing claims unnecessarily, and ensure secure transmission. Below are concrete, realistic code examples using the jsonwebtoken crate and Actix Web handlers.
1. Validate token and limit claims before use
Decode the token with strict validation, and only extract the claims you need. Do not forward or log the full token payload.
use actix_web::{web, HttpRequest, HttpResponse, Result};
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation, TokenData};
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
struct Claims {
sub: String,
email: String,
role: String,
exp: usize,
// Avoid including raw PII beyond necessity
}
fn validate_token(token: &str) -> Result, jsonwebtoken::errors::Error> {
let validation = Validation::new(Algorithm::HS256);
let key = DecodingKey::from_secret("YOUR_SECRET_KEY".as_ref());
decode::(token, &key, &validation)
}
async fn profile(req: HttpRequest) -> Result {
let auth_header = req.headers().get("Authorization");
let token = match auth_header.and_then(|v| v.to_str().ok()) {
Some(t) if t.starts_with("Bearer ") => &t[7..],
_ => return Ok(HttpResponse::Unauthorized().body("Missing or invalid authorization header")),
};
let data = validate_token(token)?;
// Only use minimal claims needed for the response
let safe_response = web::Json(serde_json::json!({
"user_id": data.claims.sub,
"role": data.claims.role,
}));
Ok(HttpResponse::Ok().json(safe_response))
}
2. Avoid returning raw JWTs or PII in responses
Ensure endpoints do not echo back the full token or include PII fields such as email unless explicitly required and consented. If email is needed, consider masking or omitting it.
async fn token_echo_risk() -> HttpResponse {
// BAD: Returning token or PII in response can cause leakage
// return HttpResponse::Ok().json(json!({"token": token_string, "email": "[email protected]"}));
// GOOD: Return only necessary, non-sensitive data
HttpResponse::Ok().json(json!({"status": "ok"}))
}
3. Enforce HTTPS and secure cookie attributes if storing tokens
If your Actix service sets authentication cookies, configure them with Secure, HttpOnly, and SameSite attributes.
use actix_web::cookie::{Cookie, SameSite};
let secure_cookie = Cookie::build(("auth_token", token_string))
.secure(true)
.http_only(true)
.same_site(SameSite::Strict)
.path("/")
.finish();
4. Scope token validation per endpoint and avoid over-fetching
Use different validation expectations for public and privileged endpoints. For public read-only endpoints, consider skipping JWT validation or using anonymous access where appropriate.
async fn public_data() -> HttpResponse {
// No token required; no PII exposure risk
HttpResponse::Ok().json(json!({"public": "data"}))
}
5. Redact PII in logs and error messages
Ensure that Actix logging or error handling does not include raw claims or tokens. Use structured logging with filters for sensitive fields.
// Example: avoid logging full claims
// log::info!("User data: {:?}", data.claims);
// Prefer minimal logging
log::info!( "Request processed for user_id: {}", data.claims.sub);
By combining strict JWT validation, minimal claim usage, secure transport, and careful logging, you reduce PII leakage risks in Actix services that rely on token-based authentication.
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 |