Pii Leakage in Actix with Mongodb
Pii Leakage in Actix with Mongodb — how this specific combination creates or exposes the vulnerability
When an Actix web service interacts with a MongoDB backend, PII leakage commonly arises from application-level data handling rather than the database itself. Actix routes deserialize incoming requests into Rust structs, and developers may inadvertently construct responses that include sensitive fields such as email, phone, national ID, or internal identifiers. If these routes query MongoDB using a driver like mongodb and directly return query results or partially filtered documents, any PII present in the stored documents can be exposed to clients or logs.
For example, a user profile endpoint might fetch a document from a users collection and serialize the entire BSON document into JSON. Without explicit field selection or transformation, fields such as password_hash, ssn, or api_key can be included in HTTP responses. In addition, logging of requests, deserialization errors, or MongoDB driver messages may inadvertently include PII if structured logging captures full request or response bodies.
Another common pattern is using Actix extractors like web::Json to bind incoming data to a struct and then passing that data to MongoDB queries. If query filters are built from user-controlled input without strict validation, an attacker may leverage injection or insecure deserialization to coerce the server into retrieving or returning more data than intended. The combination of Actix’s flexible extractor model and MongoDB’s schema-less nature increases the risk that sensitive fields are included in responses or error messages, especially when indexes or projections are not explicitly defined to limit returned fields.
Compliance frameworks such as OWASP API Top 10 classify this as a Broken Object Level Authorization (BOLA) and data exposure issue. middleBrick scans detect such leakage by correlating OpenAPI/Swagger specifications with runtime responses, flagging endpoints that return fields commonly recognized as PII. The scanner identifies missing projection definitions, unauthenticated or overly permissive read routes, and inconsistencies between documented and actual response schemas, providing prioritized findings with severity and remediation guidance.
Mongodb-Specific Remediation in Actix — concrete code fixes
To prevent PII leakage in an Actix service using MongoDB, explicitly define which fields are safe to return and ensure that database queries use projections to limit returned data. Avoid returning entire BSON documents to HTTP responses. Instead, construct dedicated response structs that contain only the necessary, non-sensitive fields.
Below is a secure example using the official MongoDB Rust driver with Actix. The code demonstrates a login endpoint that queries by username, uses a projection to return only the required fields, and returns a sanitized response struct.
use actix_web::{web, HttpResponse, Result};
use mongodb::{bson::{doc, Document}};
use serde::{Deserialize, Serialize};
#[derive(Deserialize)]
struct LoginRequest {
username: String,
password: String,
}
#[derive(Serialize)]
struct UserPublic {
id: String,
username: String,
email: String,
}
async fn login(
db: web::Data,
req: web::Json,
) -> Result {
let users = db.collection::("users");
let filter = doc! { "username": &req.username };
// Explicit projection: only return safe fields
let projection = doc! { "username": 1, "email": 1, "_id": 1 };
let find_options = mongodb::options::FindOptions::builder()
.projection(projection)
.build();
if let Some(result) = users.find_one(filter, find_options).await? {
let user = UserPublic {
id: result.get_object_id("_id")?.to_string(),
username: result.get_str("username")?.to_string(),
email: result.get_str("email")?.to_string(),
};
Ok(HttpResponse::Ok().json(user))
} else {
Ok(HttpResponse::Unauthorized().finish())
}
}
Additionally, enforce field-level encryption or tokenization for highly sensitive attributes at rest, and configure MongoDB role-based access control so that the Actix service’s database user cannot read sensitive collections unless explicitly required. Avoid logging full request or response payloads; if logging is necessary, sanitize PII before output. middleBrick’s Pro plan supports continuous monitoring and can be integrated into CI/CD pipelines via the GitHub Action to fail builds if response schemas unexpectedly include PII fields, helping maintain compliance with frameworks such as PCI-DSS and GDPR.
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 |