Timing Attack in Express with Bearer Tokens
Timing Attack in Express with Bearer Tokens — how this specific combination creates or exposes the vulnerability
A timing attack in an Express API that uses Bearer tokens occurs when the server's comparison of the provided token to the expected token does not run in constant time. If the comparison short-circuits on the first mismatching character, an attacker can measure response times to infer how many leading characters are correct. Over many requests, these small timing differences can reveal the full token. This is especially relevant when tokens are compared using simple equality checks rather than constant-time comparison utilities.
Express does not enforce authentication itself; Bearer tokens are typically validated via middleware that extracts the token from the Authorization header and compares it to a stored value. A naive implementation might look like:
const express = require('express');
const app = express();
const VALID_TOKEN = 's3cr3t_t0k3n_abcdef123456';
app.use((req, res, next) => {
const auth = req.headers['authorization'];
if (!auth || !auth.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Unauthorized' });
}
const token = auth.slice(7);
if (token === VALID_TOKEN) { // Potential timing leak
return next();
}
res.status(401).json({ error: 'Invalid token' });
});
app.get('/profile', (req, res) => {
res.json({ user: 'alice', role: 'user' });
});
app.listen(3000);
In this example, an attacker who can send authentication requests and observe response times can progressively determine each character of VALID_TOKEN. The risk is compounded if the same endpoint behavior and timing are available over the network without rate limiting or other protections. Even without direct network access, hosted environments can introduce observable timing variance due to network jitter or shared infrastructure, making statistical analysis feasible.
The 12 security checks run by middleBrick include Authentication and Input Validation, which can surface weak token handling patterns. When scanning an Express endpoint that uses Bearer tokens, middleBrick tests whether authentication comparisons are susceptible to timing-based inference by evaluating runtime behavior across controlled probes. This helps identify whether token validation leaks information character by character, which aligns with findings mapped to the OWASP API Top 10 and common authentication weaknesses.
Remediation focuses on ensuring token comparisons execute in constant time and applying additional protections such as rate limiting and secure transport. This reduces the feasibility of extracting token material through timing measurements. Detection by middleBrick provides prioritized findings with severity and remediation guidance without implying automatic fixes.
Bearer Tokens-Specific Remediation in Express — concrete code fixes
To mitigate timing attacks on Bearer tokens in Express, replace equality checks with a constant-time comparison function. Node.js provides crypto.timingSafeEqual for this purpose. You should also normalize inputs, ensure HTTPS is enforced, and apply rate limiting to reduce the attacker's ability to make many probing requests.
Below is a secure implementation example:
const express = require('express');
const crypto = require('crypto');
const app = express();
const VALID_TOKEN = 's3cr3t_t0k3n_abcdef123456';
const TOKEN_BUFFER = Buffer.from(VALID_TOKEN);
function safeTokenCompare(provided) {
const providedBuffer = Buffer.from(provided);
if (providedBuffer.length !== TOKEN_BUFFER.length) {
return false;
}
return crypto.timingSafeEqual(providedBuffer, TOKEN_BUFFER);
}
app.use((req, res, next) => {
const auth = req.headers['authorization'];
if (!auth || !auth.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Unauthorized' });
}
const token = auth.slice(7);
if (!token) {
return res.status(401).json({ error: 'Invalid token' });
}
if (safeTokenCompare(token)) {
return next();
}
res.status(401).json({ error: 'Invalid token' });
});
app.get('/profile', (req, res) => {
res.json({ user: 'alice', role: 'user' });
});
app.listen(3000);
This approach ensures the comparison does not branch on secret data length or content, mitigating timing-based inference. For additional defense, enforce HTTPS to prevent token exposure in transit, and use short-lived tokens where possible. MiddleBrick scans can validate that your token handling avoids known weaknesses; the CLI can be used locally with middlebrick scan <url> to check your endpoints, while the GitHub Action can add API security checks to your CI/CD pipeline and fail builds if risk scores exceed your threshold. The MCP Server enables scanning APIs directly from AI coding assistants within your development environment.
Other measures include rate limiting to reduce brute-force feasibility and monitoring for anomalous request patterns. While these controls do not replace constant-time comparison, they complement it by lowering the attack surface. middleBrick’s findings include prioritized guidance to help you address such issues as part of broader compliance mappings to frameworks like OWASP API Top 10 and SOC2.