HIGH pii leakageexpressbasic auth

Pii Leakage in Express with Basic Auth

Pii Leakage in Express with Basic Auth — how this specific combination creates or exposes the vulnerability

Basic Authentication over unencrypted channels is a common cause of PII leakage in Express applications. When credentials are sent as a base64-encoded string in the Authorization header without TLS, an attacker on the network can intercept and decode the credentials to gain access and potentially access or modify PII through the API.

In an Express API, endpoints that return user profiles, account details, or other personal data often rely on the request user derived from Basic Auth. If transport security is absent or inconsistently applied, the same unencrypted path exposes both credentials and the PII returned by the API. For example, an endpoint like /api/users/me that reads the username from the decoded Basic Auth identity and returns email, name, and address will leak that PII to anyone who can observe the traffic.

Additionally, if the Express app does not enforce HTTPS universally (for example, by redirecting HTTP to HTTPS), an attacker can force or downgrade connections to HTTP. In this scenario, Basic Auth credentials and the resulting PII are transmitted in clear text. MiddleBrick’s unauthenticated scan detects whether endpoints exposed over HTTP return sensitive data and flags the absence of enforced transport security as a high-risk configuration issue related to PII leakage.

Another specific risk arises when error messages or logs inadvertently include Authorization headers or decoded identity information. An Express app that exposes stack traces or writes raw request headers to logs can disclose PII when Basic Auth is used. MiddleBrick’s checks include scanning response payloads and observing whether PII such as email addresses or names appear in error responses or in data returned to unauthenticated callers, highlighting how weak transport security compounds information exposure.

Basic Auth-Specific Remediation in Express — concrete code fixes

To mitigate PII leakage when using Basic Auth in Express, enforce HTTPS, avoid logging or echoing credentials, and ensure PII is only returned over secure, authenticated channels. Below are concrete, working examples.

1. Enforce HTTPS and reject plain HTTP

Ensure the server only listens on HTTPS and redirect HTTP to HTTPS. Never serve authenticated endpoints over unencrypted HTTP.

const https = require('https');
const fs = require('fs');
const express = require('express');

const app = express();

// Reject HTTP entirely; use a separate redirect service or load balancer if needed.
// This example shows HTTPS server only.
const options = {
  key: fs.readFileSync('/path/to/private.key'),
  cert: fs.readFileSync('/path/to/certificate.crt')
};

https.createServer(options, app).listen(443, () => {
  console.log('HTTPS server running on port 443');
});

2. Use middleware to validate Authorization header and avoid credential leakage

Parse the Authorization header carefully and do not echo it back in responses or logs.

function basicAuthMiddleware(req, res, next) {
  const authHeader = req.headers['authorization'];
  if (!authHeader || !authHeader.startsWith('Basic ')) {
    return res.status(401).json({ error: 'Unauthorized' });
  }
  const base64 = authHeader.split(' ')[1];
  const decoded = Buffer.from(base64, 'base64').toString('utf-8');
  const [username, password] = decoded.split(':');
  // Validate credentials against a secure store (e.g., hashed comparison)
  if (username === process.env.USER && password === process.env.PASSWORD_HASH) {
    req.user = { username };
    return next();
  }
  return res.status(401).json({ error: 'Invalid credentials' });
}

const express = require('express');
const app = express();
app.use(basicAuthMiddleware);

app.get('/api/users/me', (req, res) => {
  // Return PII only over HTTPS and for validated users
  res.json({ name: 'Jane Doe', email: 'jane@example.com' });
});

3. Avoid logging Authorization headers and sanitize error output

Ensure your logging does not capture Authorization headers or PII unintentionally, and avoid exposing sensitive data in error responses.

const morgan = require('morgan');
const express = require('express');
const app = express();

// Custom token that excludes sensitive headers
morgan.token('auth-header', (req) => {
  return req.headers.authorization ? '[redacted]' : '';
});
app.use(morgan(':method :url :status :auth-header'));

app.use((err, req, res, next) => {
  // Do not include stack traces or PII in production error responses
  res.status(500).json({ error: 'Internal server error' });
});

app.get('/api/users/me', basicAuthMiddleware, (req, res) => {
  res.json({ name: 'Jane Doe', email: 'jane@example.com' });
});

4. Combine with other protections

Rate limiting and input validation reduce abuse and indirect information exposure, complementing transport and credential hygiene.

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

Does MiddleBrick detect PII leakage in Basic Auth APIs?
Yes. MiddleBrick scans unauthenticated endpoints over HTTP and HTTPS, detects whether responses include PII such as email addresses or names, and flags missing HTTPS or unsafe exposure of credentials and data as high-risk findings.
Is Base64 encoding sufficient protection for credentials in Express?
No. Base64 is encoding, not encryption. Always use HTTPS with Basic Auth. MiddleBrick checks for credentials transmitted over unencrypted channels and flags the absence of enforced TLS as a security risk.