01 //Introduction to Sensitive Data Exposure
Sensitive data exposure occurs when an application inadvertently reveals protected information — personally identifiable information (PII), credentials, financial data, health records, or internal system details. Unlike injection or authentication attacks where an attacker actively exploits a flaw, data exposure often happens passively: the application simply includes too much information in logs, API responses, error messages, or URLs.
In this guide, you'll learn how to classify and identify sensitive data across different regulatory frameworks, how PII leaks through logs, error messages, and monitoring systems, why API over-exposure is one of the most pervasive data leak vectors, how insecure storage practices — from plaintext passwords to unencrypted backups — lead to breaches, and how to build systematic defenses at every stage of the data lifecycle.
Forms, APIs, file uploads, third-party integrations
Over-collection, no consent, unencrypted transit
Validation, enrichment, transformations, calculations
PII in variables, temp files, debug output
Databases, file systems, caches, session stores
Plaintext PII, unencrypted at rest, excessive retention
Application logs, error tracking, APM, audit trails
Passwords, tokens, PII in log messages and stack traces
API responses, rendered pages, emails, exports
Excessive data in responses, verbose errors, data in URLs
critical · Passwords, SSNs, tokens
high · Stack traces to users
high · Too much data in APIs
critical · Plaintext secrets
Which of these is the most common way sensitive data gets exposed in production applications?
02 //Real-World Scenario
The Scenario: You're reviewing a healthcare SaaS application that manages patient appointments and medical records. The application has a REST API consumed by a web frontend and a mobile app.
1// --- Patient Appointment Endpoint ---
2app.get('/api/appointments/:id', authenticate, async (req, res) => {
3 const appointment = await db.query(
4 'SELECT * FROM appointments WHERE id = $1', [req.params.id]
5 );
6
7 // ❌ Returns ENTIRE database row including:
8 // - patient SSN
9 // - insurance policy number
10 // - internal notes from doctor
11 // - billing codes
12 // - next_of_kin contact info
13 res.json(appointment);
14});
15
16// --- User Login Endpoint ---
17app.post('/api/auth/login', async (req, res) => {
18 const { email, password } = req.body;
19
20 // ❌ Logging the full request body — includes password!
21 logger.info('Login attempt', { body: req.body });
22
23 const user = await db.query(
24 'SELECT * FROM users WHERE email = $1', [email]
25 );
26
27 if (!user || !bcrypt.compare(password, user.password_hash)) {
28 // ❌ Different error messages leak whether the email exists
29 if (!user) {
30 return res.status(401).json({ error: 'Email not found' });
31 }
32 return res.status(401).json({ error: 'Incorrect password' });
33 }
34
35 // ❌ Token includes sensitive data in the payload
36 const token = jwt.sign({
37 userId: user.id,
38 email: user.email,
39 ssn: user.ssn, // ❌ SSN in JWT!
40 role: user.role,
41 salary: user.salary, // ❌ Salary in JWT!
42 }, SECRET);
43
44 res.json({ token });
45});
46
47// --- Error Handler ---
48app.use((err, req, res, next) => {
49 // ❌ Stack trace with internal paths sent to client
50 // ❌ Database connection info in error details
51 console.error('Unhandled error:', err);
52 res.status(500).json({
53 error: err.message,
54 stack: err.stack, // ❌ Full stack trace!
55 query: err.sql, // ❌ SQL query that failed!
56 connectionString: err.host, // ❌ DB host exposed!
57 });
58});A JWT token contains the user's SSN in its payload. Why is this dangerous even though the JWT is signed?
03 //Understanding Sensitive Data
Before you can prevent sensitive data exposure, you need to know what counts as sensitive data. The classification depends on the regulatory framework, industry, and jurisdiction.
Sensitive Data Classification
| Category | Examples | Regulations | Exposure Impact |
|---|---|---|---|
| PII (Personally Identifiable Information) | Name, email, phone, address, date of birth, IP address | GDPR, CCPA, PIPEDA | Identity theft, regulatory fines, reputational damage |
| Authentication Credentials | Passwords, password hashes, API keys, tokens, session IDs | PCI DSS, SOC 2, ISO 27001 | Account takeover, lateral movement, full system compromise |
| Financial Data | Credit card numbers, bank accounts, transaction history, salary | PCI DSS, SOX, GLBA | Financial fraud, regulatory fines up to 4% of revenue |
| Health Information (PHI) | Medical records, diagnoses, prescriptions, insurance IDs | HIPAA, HITECH | Fines up to $1.5M per violation category, criminal penalties |
| Government IDs | SSN, passport number, driver's license, tax ID | Varies by jurisdiction | Identity theft, fraud, very high PII sensitivity |
| System / Infrastructure | DB connection strings, internal IPs, file paths, stack traces | SOC 2, ISO 27001 | Aids further attacks, enables targeted exploitation |
| Biometric Data | Fingerprints, facial recognition data, voice prints, retina scans | GDPR, BIPA, CCPA | Irrevocable — cannot be changed like a password |
1// ✅ Define data sensitivity at the schema level
2
3enum DataSensitivity {
4 PUBLIC = 'public', // Can be freely shared
5 INTERNAL = 'internal', // For internal use only
6 CONFIDENTIAL = 'confidential', // Restricted access
7 RESTRICTED = 'restricted', // Highest sensitivity (PII, PHI)
8}
9
10// ✅ Annotate your data models with sensitivity levels
11interface User {
12 id: string; // INTERNAL
13 displayName: string; // PUBLIC
14 email: string; // CONFIDENTIAL (PII)
15 passwordHash: string; // RESTRICTED (never expose)
16 ssn: string; // RESTRICTED (PII)
17 dateOfBirth: Date; // CONFIDENTIAL (PII)
18 phoneNumber: string; // CONFIDENTIAL (PII)
19 role: string; // INTERNAL
20 loginAttempts: number; // INTERNAL
21 lastIpAddress: string; // CONFIDENTIAL (PII under GDPR)
22 medicalNotes?: string; // RESTRICTED (PHI)
23}
24
25// ✅ Create view models that expose only what's needed
26interface UserPublicProfile {
27 id: string;
28 displayName: string;
29}
30
31interface UserOwnProfile {
32 id: string;
33 displayName: string;
34 email: string; // User can see their own email
35 phoneNumber: string; // User can see their own phone
36 role: string;
37}
38
39// ✅ Map to appropriate view based on context
40function toPublicProfile(user: User): UserPublicProfile {
41 return { id: user.id, displayName: user.displayName };
42}
43
44function toOwnProfile(user: User): UserOwnProfile {
45 return {
46 id: user.id,
47 displayName: user.displayName,
48 email: user.email,
49 phoneNumber: user.phoneNumber,
50 role: user.role,
51 };
52}An analytics API returns: { zipCode: '02139', birthYear: 1985, gender: 'M', purchaseCount: 47 }. Is this sensitive data?
04 //PII in Logs & Error Messages
Logging is the single most common vector for sensitive data exposure. Developers log request/response bodies for debugging, error messages include stack traces with variable values, and monitoring tools capture everything. Once sensitive data enters log files, it persists indefinitely and is accessible to anyone with log access — often a much wider group than those with database access.
1// Pattern 1: Logging full request bodies
2app.use((req, res, next) => {
3 // ❌ Logs EVERYTHING including passwords, tokens, credit cards
4 logger.info('Incoming request', {
5 method: req.method,
6 url: req.url,
7 body: req.body, // ❌ Could contain password, CC number
8 headers: req.headers, // ❌ Contains Authorization tokens
9 cookies: req.cookies, // ❌ Contains session tokens
10 });
11 next();
12});
13
14// Pattern 2: Logging user objects
15async function updateProfile(userId: string, updates: any) {
16 const user = await User.findById(userId);
17 // ❌ Logs entire user object including passwordHash, SSN
18 logger.info('Updating user profile', { user, updates });
19 Object.assign(user, updates);
20 await user.save();
21}
22
23// Pattern 3: Error logging with context
24async function processPayment(order: Order) {
25 try {
26 await paymentGateway.charge(order.creditCard, order.total);
27 } catch (error) {
28 // ❌ Logs the full order object including credit card details
29 logger.error('Payment failed', {
30 error: error.message,
31 order: order, // ❌ Includes creditCard: { number, cvv, expiry }
32 stack: error.stack,
33 });
34 throw error;
35 }
36}
37
38// Pattern 4: Debug logging left in production
39function authenticateUser(email: string, password: string) {
40 // ❌ Debug line that was never removed
41 console.log(`Auth attempt: email=${email} password=${password}`);
42 // ...
43}1// ✅ Define a list of fields that must NEVER be logged
2const REDACTED_FIELDS = new Set([
3 'password', 'passwordHash', 'password_hash',
4 'ssn', 'socialSecurityNumber',
5 'creditCard', 'cardNumber', 'cvv', 'ccv',
6 'token', 'accessToken', 'refreshToken', 'sessionId',
7 'secret', 'apiKey', 'privateKey',
8 'authorization',
9]);
10
11function sanitizeForLogging(obj: any, depth = 0): any {
12 if (depth > 5) return '[nested]';
13 if (obj === null || obj === undefined) return obj;
14 if (typeof obj !== 'object') return obj;
15
16 if (Array.isArray(obj)) {
17 return obj.map(item => sanitizeForLogging(item, depth + 1));
18 }
19
20 const sanitized: Record<string, any> = {};
21 for (const [key, value] of Object.entries(obj)) {
22 if (REDACTED_FIELDS.has(key.toLowerCase())) {
23 sanitized[key] = '[REDACTED]';
24 } else if (typeof value === 'string' && value.length > 200) {
25 sanitized[key] = value.substring(0, 50) + '...[truncated]';
26 } else {
27 sanitized[key] = sanitizeForLogging(value, depth + 1);
28 }
29 }
30 return sanitized;
31}
32
33// ✅ Safe request logging middleware
34app.use((req, res, next) => {
35 logger.info('Incoming request', {
36 method: req.method,
37 url: req.url,
38 // ✅ Only log safe fields
39 userAgent: req.headers['user-agent'],
40 contentType: req.headers['content-type'],
41 // ✅ Sanitize body before logging
42 body: sanitizeForLogging(req.body),
43 // ✅ Never log headers (contains auth tokens)
44 });
45 next();
46});
47
48// ✅ Safe error logging
49async function processPayment(order: Order) {
50 try {
51 await paymentGateway.charge(order.creditCard, order.total);
52 } catch (error) {
53 logger.error('Payment failed', {
54 error: error.message,
55 // ✅ Only log non-sensitive order fields
56 orderId: order.id,
57 amount: order.total,
58 // ✅ Never log credit card details
59 });
60 throw error;
61 }
62}A developer adds logger.error('Auth failed', { email, password, reason }) to debug login issues. What should you flag in code review?
05 //API Over-Exposure
API over-exposure (also called "Excessive Data Exposure" in the OWASP API Security Top 10) occurs when API endpoints return more data than the client needs. The most common pattern is SELECT * from the database piped directly into the API response, relying on the frontend to show only the relevant fields.
1// Pattern 1: SELECT * → response
2app.get('/api/users/:id', async (req, res) => {
3 // ❌ Fetches ALL columns including passwordHash, SSN, etc.
4 const user = await db.query('SELECT * FROM users WHERE id = $1', [req.params.id]);
5 // ❌ Returns entire row to the client
6 res.json(user);
7 // Client receives: { id, name, email, passwordHash, ssn,
8 // salary, internalNotes, loginAttempts, ... }
9});
10
11// Pattern 2: ORM includes related data by default
12app.get('/api/orders/:id', async (req, res) => {
13 const order = await Order.findById(req.params.id)
14 .populate('customer') // ❌ Includes full customer object
15 .populate('payments') // ❌ Includes payment card details
16 .populate('internalNotes'); // ❌ Includes staff comments
17 res.json(order);
18});
19
20// Pattern 3: List endpoint returns too much
21app.get('/api/users', async (req, res) => {
22 // ❌ Returns ALL user fields for ALL users
23 const users = await User.find({});
24 res.json(users);
25 // An attacker with a valid session can enumerate
26 // every user's email, phone, role, etc.
27});
28
29// Pattern 4: Search leaks data
30app.get('/api/search', async (req, res) => {
31 const results = await db.query(
32 "SELECT * FROM products WHERE name LIKE $1",
33 [`%${req.query.q}%`]
34 );
35 // ❌ Returns internal fields: cost_price, supplier_id,
36 // margin_percentage, internal_sku, warehouse_location
37 res.json(results);
38});1// ✅ Define response schemas for each endpoint
2interface UserListResponse {
3 id: string;
4 displayName: string;
5 avatarUrl: string;
6}
7
8interface UserDetailResponse {
9 id: string;
10 displayName: string;
11 email: string; // Only for the user themselves
12 avatarUrl: string;
13 memberSince: string;
14}
15
16// ✅ Select only needed columns
17app.get('/api/users/:id', authenticate, async (req, res) => {
18 const isOwnProfile = req.user.id === req.params.id;
19
20 // ✅ Different fields based on who is requesting
21 const fields = isOwnProfile
22 ? ['id', 'display_name', 'email', 'avatar_url', 'created_at']
23 : ['id', 'display_name', 'avatar_url', 'created_at'];
24
25 const user = await db.query(
26 `SELECT ${fields.join(', ')} FROM users WHERE id = $1`,
27 [req.params.id]
28 );
29
30 if (!user) return res.status(404).json({ error: 'Not found' });
31
32 // ✅ Map to response DTO (Data Transfer Object)
33 const response: UserDetailResponse = {
34 id: user.id,
35 displayName: user.display_name,
36 ...(isOwnProfile && { email: user.email }),
37 avatarUrl: user.avatar_url,
38 memberSince: user.created_at,
39 };
40
41 res.json(response);
42});
43
44// ✅ List endpoint with minimal fields
45app.get('/api/users', authenticate, async (req, res) => {
46 // ✅ Only return public profile fields
47 const users = await db.query(
48 'SELECT id, display_name, avatar_url FROM users LIMIT $1 OFFSET $2',
49 [Math.min(req.query.limit || 20, 100), req.query.offset || 0]
50 );
51
52 const response: UserListResponse[] = users.map(u => ({
53 id: u.id,
54 displayName: u.display_name,
55 avatarUrl: u.avatar_url,
56 }));
57
58 res.json({ data: response, total: users.length });
59});Your API returns full user objects from the database, and the frontend only displays name and avatar. A QA engineer says 'it works fine.' What do you say in code review?
06 //Insecure Data Storage
How data is stored determines how much damage occurs when (not if) an attacker gains database access. Plaintext passwords, unencrypted PII, and overly broad data retention multiply the impact of every data breach.
1// Pattern 1: Plaintext passwords
2async function createUser(email: string, password: string) {
3 // ❌ Storing password in plaintext!
4 await db.query(
5 'INSERT INTO users (email, password) VALUES ($1, $2)',
6 [email, password]
7 );
8}
9
10// Pattern 2: Weak hashing
11const crypto = require('crypto');
12function hashPassword(password: string) {
13 // ❌ MD5 is broken — rainbow tables can reverse it instantly
14 return crypto.createHash('md5').update(password).digest('hex');
15 // ❌ SHA-256 without salt is also insufficient
16 // return crypto.createHash('sha256').update(password).digest('hex');
17}
18
19// Pattern 3: PII stored in plaintext
20async function savePatientRecord(patient: any) {
21 // ❌ SSN, medical data stored without encryption
22 await db.query(
23 'INSERT INTO patients (name, ssn, diagnosis, insurance_id) VALUES ($1, $2, $3, $4)',
24 [patient.name, patient.ssn, patient.diagnosis, patient.insuranceId]
25 );
26}
27
28// Pattern 4: Sensitive data in client-side storage
29function rememberUser(user: any) {
30 // ❌ Storing sensitive data in localStorage (accessible to any JS)
31 localStorage.setItem('user', JSON.stringify({
32 id: user.id,
33 email: user.email,
34 ssn: user.ssn, // ❌ SSN in localStorage!
35 authToken: user.token, // ❌ Token in localStorage (XSS can steal it)
36 }));
37}
38
39// Pattern 5: No data retention limits
40// ❌ User data kept forever, even for deleted accounts
41// ❌ Logs with PII retained indefinitely
42// ❌ Database backups contain plaintext PII with no expiry1import bcrypt from 'bcrypt';
2
3// ✅ Password hashing with bcrypt (adaptive, salted)
4async function createUser(email: string, password: string) {
5 // ✅ bcrypt with cost factor 12 (auto-generates salt)
6 const passwordHash = await bcrypt.hash(password, 12);
7 await db.query(
8 'INSERT INTO users (email, password_hash) VALUES ($1, $2)',
9 [email, passwordHash]
10 );
11 // ✅ Original password is never stored anywhere
12}
13
14// ✅ Application-level encryption for PII
15import { createCipheriv, createDecipheriv, randomBytes } from 'crypto';
16
17class FieldEncryption {
18 private algorithm = 'aes-256-gcm';
19 private key: Buffer;
20
21 constructor(encryptionKey: string) {
22 this.key = Buffer.from(encryptionKey, 'hex');
23 }
24
25 encrypt(plaintext: string): string {
26 const iv = randomBytes(16);
27 const cipher = createCipheriv(this.algorithm, this.key, iv);
28 let encrypted = cipher.update(plaintext, 'utf8', 'hex');
29 encrypted += cipher.final('hex');
30 const tag = cipher.getAuthTag().toString('hex');
31 // ✅ Return IV + tag + ciphertext (all needed for decryption)
32 return iv.toString('hex') + ':' + tag + ':' + encrypted;
33 }
34
35 decrypt(ciphertext: string): string {
36 const [ivHex, tagHex, encrypted] = ciphertext.split(':');
37 const iv = Buffer.from(ivHex, 'hex');
38 const tag = Buffer.from(tagHex, 'hex');
39 const decipher = createDecipheriv(this.algorithm, this.key, iv);
40 decipher.setAuthTag(tag);
41 let decrypted = decipher.update(encrypted, 'hex', 'utf8');
42 decrypted += decipher.final('utf8');
43 return decrypted;
44 }
45}
46
47// ✅ Encrypt sensitive fields before storage
48const fieldEncryption = new FieldEncryption(process.env.FIELD_ENCRYPTION_KEY!);
49
50async function savePatientRecord(patient: PatientInput) {
51 await db.query(
52 'INSERT INTO patients (name_encrypted, ssn_encrypted, diagnosis_encrypted) VALUES ($1, $2, $3)',
53 [
54 fieldEncryption.encrypt(patient.name),
55 fieldEncryption.encrypt(patient.ssn),
56 fieldEncryption.encrypt(patient.diagnosis),
57 ]
58 );
59}A developer uses SHA-256 to hash passwords before storing them. Is this secure?
07 //Prevention Techniques
1// ✅ Response sanitization middleware
2function responseSanitizer() {
3 return (req: Request, res: Response, next: NextFunction) => {
4 const originalJson = res.json.bind(res);
5
6 res.json = (body: any) => {
7 // ✅ Strip sensitive fields from ANY response
8 const sanitized = deepOmit(body, [
9 'passwordHash', 'password_hash', 'password',
10 'ssn', 'socialSecurityNumber',
11 'creditCardNumber', 'cvv',
12 'internalNotes', 'internal_notes',
13 'costPrice', 'cost_price', 'margin',
14 ]);
15
16 // ✅ Strip internal database fields
17 const cleaned = deepOmit(sanitized, [
18 '__v', '_id', 'createdBy', 'updatedBy',
19 'deletedAt', 'is_deleted',
20 ]);
21
22 return originalJson(cleaned);
23 };
24
25 next();
26 };
27}
28
29// ✅ Security headers for data protection
30app.use((req, res, next) => {
31 // ✅ Prevent browser from caching sensitive responses
32 res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate');
33 res.setHeader('Pragma', 'no-cache');
34
35 // ✅ Prevent MIME type sniffing
36 res.setHeader('X-Content-Type-Options', 'nosniff');
37
38 // ✅ Strict Transport Security
39 res.setHeader('Strict-Transport-Security', 'max-age=63072000; includeSubDomains');
40
41 next();
42});
43
44// ✅ Data retention enforcement
45async function enforceRetentionPolicy() {
46 // ✅ Delete accounts inactive for > 2 years
47 await db.query(
48 "DELETE FROM users WHERE last_active < NOW() - INTERVAL '2 years' AND status = 'inactive'"
49 );
50
51 // ✅ Purge old logs with PII
52 await db.query(
53 "DELETE FROM audit_logs WHERE created_at < NOW() - INTERVAL '90 days'"
54 );
55
56 // ✅ Anonymize old order data (keep for analytics, remove PII)
57 await db.query(`
58 UPDATE orders SET
59 customer_name = 'ANONYMIZED',
60 customer_email = 'ANONYMIZED',
61 shipping_address = 'ANONYMIZED'
62 WHERE created_at < NOW() - INTERVAL '3 years'
63 `);
64}1// ✅ Error handler that never leaks internals
2app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
3 // ✅ Generate a unique error ID for correlation
4 const errorId = crypto.randomUUID();
5
6 // ✅ Log the FULL error internally (for debugging)
7 logger.error('Unhandled error', {
8 errorId,
9 message: err.message,
10 stack: err.stack,
11 url: req.url,
12 method: req.method,
13 userId: req.user?.id,
14 // ✅ Do NOT log request body (may contain PII)
15 });
16
17 // ✅ Return a GENERIC error to the client
18 const statusCode = (err as any).statusCode || 500;
19 res.status(statusCode).json({
20 error: statusCode === 500
21 ? 'An internal error occurred. Please try again later.'
22 : err.message, // Only expose message for expected errors (4xx)
23 errorId, // ✅ Client can reference this for support
24 // ✅ NEVER include: stack, sql, query, connectionString, path
25 });
26});Which approach provides the strongest protection against sensitive data exposure?
08 //Secure Error Handling
Error messages are one of the most overlooked data exposure vectors. In development, verbose errors are essential for debugging. In production, they become a goldmine for attackers — revealing database schemas, internal file paths, technology stack details, and sometimes the data itself.
Error Information Leakage by Technology
| Technology | What the Default Error Reveals | Attacker Gains |
|---|---|---|
| Express.js (dev mode) | Full stack trace with file paths and line numbers | Internal code structure, framework version, dependency paths |
| Django (DEBUG=True) | Full settings, SQL queries, template paths, installed apps | Database credentials, internal URLs, installed packages |
| ASP.NET | Yellow Screen of Death with source code snippets | Source code fragments, connection strings, internal IPs |
| PostgreSQL errors | Column names, table names, constraint names, query text | Database schema, query logic, column types |
| Java/Spring | Full exception chain with class names and method signatures | Package structure, class hierarchy, internal method names |
1// Database errors expose schema
2// Error: "duplicate key value violates unique constraint 'users_email_key'"
3// → Attacker learns: table name is "users", there's a unique constraint on "email"
4
5// Validation errors expose field names and types
6// Error: "Cast to ObjectId failed for value 'admin' at path 'user_id'"
7// → Attacker learns: MongoDB is used, field is "user_id", expects ObjectId
8
9// Authentication errors enable account enumeration
10if (!user) return res.status(401).json({ error: "No account with that email" });
11if (!validPassword) return res.status(401).json({ error: "Wrong password" });
12// → Attacker can enumerate which emails have accounts
13
14// File operation errors expose paths
15// Error: "ENOENT: no such file or directory, open '/srv/app/uploads/user_data/temp/file.pdf'"
16// → Attacker learns: server path structure, upload directory location
17
18// ORM errors expose relationships
19// Error: "Cannot read property 'creditCards' of undefined"
20// → Attacker learns: there's a 'creditCards' relation on the user model1class SecureErrorHandler {
2 private isDev: boolean;
3
4 constructor() {
5 this.isDev = process.env.NODE_ENV === 'development';
6 }
7
8 handleError(err: Error, req: Request, res: Response) {
9 const errorId = crypto.randomUUID();
10
11 // ✅ Always log the full error internally
12 this.logError(errorId, err, req);
13
14 // ✅ Classify the error
15 const classification = this.classifyError(err);
16
17 if (this.isDev) {
18 // ✅ In development: show details (but still redact secrets)
19 return res.status(classification.statusCode).json({
20 errorId,
21 message: err.message,
22 type: err.constructor.name,
23 stack: err.stack,
24 // ✅ Still redact credentials even in dev
25 hint: classification.devHint,
26 });
27 }
28
29 // ✅ In production: generic messages only
30 return res.status(classification.statusCode).json({
31 errorId,
32 message: classification.publicMessage,
33 });
34 }
35
36 private classifyError(err: Error): ErrorClassification {
37 // ✅ Map internal errors to safe public messages
38 if (err.name === 'ValidationError') {
39 return {
40 statusCode: 400,
41 publicMessage: 'The request contains invalid data.',
42 devHint: err.message,
43 };
44 }
45 if (err.name === 'UnauthorizedError') {
46 // ✅ Same message for all auth failures (prevent enumeration)
47 return {
48 statusCode: 401,
49 publicMessage: 'Invalid credentials.',
50 devHint: err.message,
51 };
52 }
53 if (err.message?.includes('duplicate key')) {
54 // ✅ Don't reveal which field has the duplicate
55 return {
56 statusCode: 409,
57 publicMessage: 'A resource with this information already exists.',
58 devHint: err.message,
59 };
60 }
61 // Default: internal server error
62 return {
63 statusCode: 500,
64 publicMessage: 'An internal error occurred. Please try again later.',
65 devHint: err.message,
66 };
67 }
68}09 //Advanced Leakage Vectors
Beyond the obvious sources (logs, API responses, errors), sensitive data can leak through subtle channels that are easy to miss during code review.
Advanced Data Leakage Vectors
| Vector | How It Leaks | Example | Detection |
|---|---|---|---|
| URL Parameters | Sensitive data in query strings — logged by proxies, browsers, analytics | /api/reset?token=abc123&email=user@company.com | Grep for req.query containing token, password, email |
| Referer Headers | Full URL (including query params) sent to third-party resources | Page with ?ssn=123 loads a third-party script that sees the full URL | Check Referrer-Policy header, avoid PII in URLs |
| Browser History / Autocomplete | Form values cached by the browser | SSN field without autocomplete="off" saved by browser | Check sensitive inputs for autocomplete attributes |
| Third-Party Scripts | Analytics, chat widgets, A/B testing scripts can read page DOM | Hotjar session recording captures credit card form inputs | Review third-party script access, use CSP |
| Git History | Secrets committed and then "deleted" remain in git history forever | .env file with API keys committed in early commit | Use git-secrets, trufflehog, or gitleaks |
| HTTP Caching | Responses with PII cached by CDN, browser, or proxy | Cache-Control not set → CDN caches user profile with SSN | Verify Cache-Control: no-store on sensitive endpoints |
| Timing Side Channels | Response time differences reveal information | Login takes 200ms for valid emails, 50ms for invalid — enumeration | Use constant-time comparisons, normalize response times |
1// ❌ Sensitive data in URL parameters
2app.get('/api/verify-identity', (req, res) => {
3 // SSN passed as query parameter!
4 const ssn = req.query.ssn;
5 // This URL will appear in:
6 // - Server access logs
7 // - Browser history
8 // - Proxy logs
9 // - Analytics tools (Google Analytics tracks full URLs)
10 // - Referer header sent to any linked resource
11 verifySSN(ssn);
12});
13
14// ❌ Password reset token in URL (leaks via Referer)
15// https://app.com/reset-password?token=secret123
16// If the reset page loads a Google Font, the full URL
17// including the token is sent to Google as the Referer header
18
19// ❌ Sensitive data in redirect URLs
20app.get('/api/oauth/callback', (req, res) => {
21 const accessToken = req.query.access_token;
22 // Token appears in server logs, browser history
23 // Should use authorization_code flow instead
24 res.redirect(`/dashboard?token=${accessToken}`);
25});1// ✅ Use POST for sensitive data (never in URLs)
2app.post('/api/verify-identity', (req, res) => {
3 const { ssn } = req.body; // ✅ In request body, not URL
4 verifySSN(ssn);
5});
6
7// ✅ Referrer-Policy to prevent URL leakage
8app.use((req, res, next) => {
9 res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
10 next();
11});
12
13// ✅ Password reset via short-lived POST-only tokens
14app.post('/api/reset-password', async (req, res) => {
15 const { token, newPassword } = req.body; // ✅ Token in body
16 // ✅ Token expires in 15 minutes
17 // ✅ Token is single-use
18 await resetPassword(token, newPassword);
19});
20
21// ✅ Autocomplete off for sensitive form fields
22// <input type="text" name="ssn" autocomplete="off"
23// inputMode="numeric" />
24
25// ✅ Content Security Policy to control third-party script access
26app.use((req, res, next) => {
27 res.setHeader('Content-Security-Policy',
28 "default-src 'self'; script-src 'self'; connect-src 'self'"
29 );
30 next();
31});
32
33// ✅ Prevent caching of sensitive pages
34app.get('/api/account/settings', authenticate, (req, res) => {
35 res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, private');
36 res.setHeader('Pragma', 'no-cache');
37 res.setHeader('Expires', '0');
38 res.json(getAccountSettings(req.user.id));
39});10 //Real-World Case Studies
Case Study 1: Facebook API Over-Exposure (2018-2019)
Facebook's Graph API returned far more user data than third-party apps needed. Cambridge Analytica exploited this to harvest personal data of 87 million users through a quiz app that only 270,000 users installed. The API returned not just the app user's data but their entire friend network's profiles. This is the canonical example of API over-exposure: the API returned all fields by default, friend-of-friend data was accessible without consent, and there was no field-level access control. Facebook was fined $5 billion by the FTC.
Case Study 2: Uber S3 Data Breach (2016)
Uber stored 57 million user and driver records in an Amazon S3 bucket. Attackers found AWS access keys hardcoded in a private GitHub repository used by Uber engineers. Using these credentials, they accessed the S3 bucket containing unencrypted names, email addresses, phone numbers, and driver's license numbers. The breach combined multiple failures: secrets in source code, PII stored without encryption, and overly broad S3 bucket permissions.
Case Study 3: Optus Telecom API Exposure (2022)
Australia's second-largest telecom, Optus, exposed 9.8 million customer records through an unauthenticated API endpoint. The API was a customer identity verification endpoint that returned full customer details (including passport and driver's license numbers) and required no authentication. An attacker simply incremented customer IDs to extract records for nearly half of Australia's population. This is a textbook case of both missing authentication and API over-exposure.
Case Study 4: Elasticsearch Exposed Instances (2018-2024)
Thousands of Elasticsearch and MongoDB instances exposed on the internet without authentication have resulted in hundreds of data breaches. These databases often contain application logs with full request/response data — including passwords, tokens, and PII. The root cause is twofold: 1) the databases default to no authentication, and 2) application logs contain sensitive data that should have been redacted. Researchers regularly find exposed instances with billions of records containing email addresses, passwords, medical records, and financial data.
Notable Sensitive Data Exposure Incidents
| Target | Year | Data Exposed | Records | Root Cause |
|---|---|---|---|---|
| Facebook/Cambridge Analytica | 2018 | Profile data, likes, friend networks | 87 million | API over-exposure — returned friend-of-friend data |
| Uber | 2016 | Names, emails, phone numbers, license numbers | 57 million | AWS keys in GitHub, unencrypted S3 storage |
| Optus | 2022 | Names, DOB, passport/license numbers | 9.8 million | Unauthenticated API, excessive data in response |
| Elasticsearch instances | 2018-24 | Passwords, tokens, medical records, PII | Billions | No auth on databases, PII in application logs |
| T-Mobile | 2021 | Names, SSN, DOB, driver's license | 76 million | Unencrypted PII in database, weak access controls |
| Equifax | 2017 | SSN, DOB, addresses, credit card numbers | 147 million | Unpatched Apache Struts + unencrypted PII storage |
The Optus breach exposed 9.8 million records through an API that returned full customer details and required no authentication. What was the FIRST line of defense that should have prevented this?
11 //Tools & Resources
Sensitive Data Protection Tools
| Category | Name | Description |
|---|---|---|
| Secret Scanning | trufflehog | Scan git history, file systems, and S3 buckets for leaked credentials and API keys |
| Secret Scanning | gitleaks | Git repository scanner for hardcoded secrets — CI/CD integration available |
| Secret Scanning | detect-secrets (Yelp) | Pre-commit hook to prevent secrets from being committed to repositories |
| PII Detection | Microsoft Presidio | Open-source PII detection and anonymization engine for text and images |
| PII Detection | AWS Macie | Automatically discover and protect sensitive data in S3 using ML |
| Log Redaction | pino-redact / winston-redact | Node.js logging libraries with built-in field redaction support |
| API Security | OWASP ZAP | Intercept API responses and check for excessive data exposure |
| API Security | Burp Suite | Proxy for inspecting API responses for sensitive field leakage |
| Compliance | OneTrust / TrustArc | Data mapping and privacy compliance platforms for GDPR/CCPA |
| Encryption | Vault (HashiCorp) | Centralized secrets management with field-level encryption as a service |
Essential Reading: OWASP Top 10 (A02:2021 Cryptographic Failures), OWASP API Security Top 10 (API3: Excessive Data Exposure), NIST SP 800-122 (Guide to Protecting PII), IBM Cost of a Data Breach Report, GDPR Article 25 (Data Protection by Design), PCI DSS Requirement 3 (Protect Stored Account Data).
12 //Conclusion & Code Review Checklist
Sensitive data exposure is the most common and often the most costly category of security vulnerability. Unlike injection attacks that require active exploitation, data exposure happens passively — through logging, API responses, error messages, and URLs during normal application operation. The defense is systematic: classify your data, minimize what you collect, encrypt what you store, redact what you log, and return only what the consumer needs.
Sensitive Data Exposure Code Review Checklist
| Category | Check | Priority |
|---|---|---|
| API Responses | Do endpoints return only the fields needed by the client (no SELECT *)? | Critical |
| API Responses | Are response schemas defined as DTOs/view models separate from DB models? | Critical |
| API Responses | Is the response different based on the requester's role/ownership? | High |
| Logging | Are passwords, tokens, and PII redacted from all log output? | Critical |
| Logging | Are request bodies sanitized before logging? | Critical |
| Logging | Are Authorization headers excluded from logs? | Critical |
| Errors | Do production error responses omit stack traces, SQL, and file paths? | Critical |
| Errors | Are authentication errors consistent (no account enumeration)? | High |
| Storage | Are passwords hashed with bcrypt/scrypt/Argon2 (not MD5/SHA)? | Critical |
| Storage | Is PII encrypted at rest with field-level encryption? | High |
| Storage | Is there a data retention policy enforced in code? | Medium |
| URLs | Are sensitive values (tokens, PII) in POST bodies, not URL parameters? | High |
| Headers | Is Cache-Control: no-store set on sensitive API responses? | High |
| Headers | Is Referrer-Policy set to prevent URL leakage to third parties? | Medium |
| Third-Party | Is CSP configured to restrict third-party script access? | Medium |
| Third-Party | Are session recordings (Hotjar, FullStory) configured to mask sensitive fields? | High |