Token Leakage in Express
How Token Leakage Manifests in Express
Token leakage in Express applications occurs when authentication tokens—whether JWTs, session cookies, or API keys—are inadvertently exposed through various Express-specific code patterns. The most common scenario involves improper error handling where stack traces containing tokens are returned to clients. When an Express route throws an error containing authentication headers, the default error handler might expose this sensitive information in development mode.
Consider this Express middleware pattern:
app.get('/api/user', authenticateToken, (req, res) => {
if (!req.user) {
return res.status(401).json({
error: 'Authentication failed',
details: req.headers.authorization // Token leakage here!
});
}
res.json({ user: req.user });
});Another Express-specific pattern involves logging middleware. Developers often log request headers for debugging, inadvertently capturing tokens:
app.use((req, res, next) => {
console.log('Request headers:', req.headers); // Captures Authorization headers
next();
});Express's error handling middleware can also contribute to token leakage. If an error occurs after token validation, the error object might contain token information:
app.use((err, req, res, next) => {
if (err.token) {
res.status(500).json({
message: err.message,
token: err.token // Direct token exposure
});
}
res.status(500).json({ message: 'Internal Server Error' });
});Query parameter handling in Express routes presents another vulnerability. Tokens passed as URL parameters can appear in server logs, browser history, and referrer headers:
app.get('/api/data', (req, res) => {
const token = req.query.token; // Token in URL
// Vulnerable to logging, caching, and referrer leakage
});Middleware ordering is critical in Express. Placing authentication middleware after logging middleware can cause tokens to be logged before validation:
app.use(requestLogger); // Logs before auth
app.use(authenticateToken); // Auth comes second
Express-Specific Detection
Detecting token leakage in Express applications requires examining both code patterns and runtime behavior. middleBrick's Express-specific scanning identifies these vulnerabilities through black-box testing of your API endpoints. The scanner examines response bodies, headers, and error messages for token patterns without requiring access to your source code.
middleBrick tests for token leakage by sending requests with various authentication headers and analyzing responses. It looks for patterns like:
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...The scanner also tests error responses by intentionally triggering failures and examining what information is returned. For Express applications, middleBrick specifically checks for:
- Bearer tokens in JSON error responses
- Session identifiers in stack traces
- API keys in validation error messages
- Tokens in redirect URLs
- Sensitive data in development mode error pages
middleBrick's LLM/AI Security module adds another layer of detection for Express applications using AI features. It tests for system prompt leakage and prompt injection vulnerabilities that could expose authentication tokens used by AI-powered endpoints.
For continuous monitoring, the Pro plan's scheduled scanning can detect token leakage as your Express application evolves. The GitHub Action integration allows you to scan your staging API before deployment, ensuring new routes don't introduce token exposure vulnerabilities.
middleBrick's OpenAPI analysis also helps detect token leakage by cross-referencing your API specification with runtime findings. If your Express app's OpenAPI spec documents token parameters but middleBrick detects those tokens being exposed in responses, it flags this as a configuration mismatch.
Express-Specific Remediation
Remediating token leakage in Express requires implementing proper error handling, logging practices, and middleware ordering. Start with centralized error handling that never exposes token information:
function errorHandler(err, req, res, next) {
console.error('Error:', err.message); // Log error without tokens
if (process.env.NODE_ENV === 'production') {
return res.status(500).json({
error: 'Internal Server Error'
});
}
res.status(500).json({
error: 'Internal Server Error',
requestId: req.id // Use request IDs instead of sensitive data
});
}
app.use(errorHandler);Implement secure logging middleware that filters sensitive headers:
function secureLogger(req, res, next) {
const filteredHeaders = Object.fromEntries(
Object.entries(req.headers)
.filter(([key]) => !['authorization', 'cookie'].includes(key.toLowerCase()))
);
console.log('Request:', {
method: req.method,
url: req.path,
headers: filteredHeaders,
timestamp: new Date().toISOString()
});
next();
}
app.use(secureLogger);Use Express's built-in features for secure token handling. The express-rate-limit middleware helps prevent brute force attacks that could lead to token exposure:
const rateLimit = require('express-rate-limit');
const authLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 5, // limit each IP to 5 requests per windowMs
message: 'Too many authentication attempts'
});
app.post('/login', authLimiter, (req, res) => {
// Authentication logic
});For JWT handling in Express, use secure patterns that avoid token exposure:
const jwt = require('jsonwebtoken');
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (!token) {
return res.status(401).json({ error: 'Access denied' });
}
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => {
if (err) {
return res.status(403).json({ error: 'Invalid token' });
}
req.user = user;
next();
});
}Configure Express to prevent token leakage in development mode:
if (process.env.NODE_ENV === 'development') {
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({
error: 'Internal Server Error',
requestId: req.id
});
});
}Finally, use middleBrick's CLI to scan your Express application after implementing these fixes:
npx middlebrick scan https://your-express-app.com/api
The Pro plan's continuous monitoring will ensure these remediation measures remain effective as your Express application evolves.
Frequently Asked Questions
How does token leakage differ in Express vs other Node.js frameworks?
Can middleBrick detect token leakage in my local Express development environment?
npx middlebrick scan http://localhost:3000 to scan your Express app running on your machine. The scanner tests unauthenticated endpoints and examines responses for token patterns, helping you catch leakage issues before they reach production. The GitHub Action integration can also scan your staging environment as part of your CI/CD pipeline.