HIGH token leakageexpressapi keys

Token Leakage in Express with Api Keys

Token Leakage in Express with Api Keys — how this specific combination creates or exposes the vulnerability

Token leakage in Express applications that rely on API keys occurs when secret values are exposed in logs, error messages, URLs, or client‑side code. Because API keys are often bearer tokens, any exposure effectively grants the same access as the compromised key.

In Express, common patterns that lead to leakage include:

  • Accidental logging of request headers that contain Authorization: ApiKey {key} or custom headers such as x-api-key.
  • Returning full configuration or debug objects in error responses, which may include the key or parts of it.
  • Constructing redirect URLs or links that embed the API key as a query parameter, which can be stored in browser history, Referer headers, or server logs.
  • Using the key in server‑side templates or responses that are rendered to the client.

These issues map to the Data Exposure check in middleBrick’s 12 security checks. During a black‑box scan, the tool submits unauthenticated requests and inspects responses and logs where possible (via observable side‑effects), looking for patterns that resemble API keys or bearer tokens. If a scan discovers that an API key appears in a response body or in a redirect location, it flags Token Leakage with severity and remediation guidance.

For example, an Express route that echoes a header into a JSON response can disclose the key:

app.get('/debug', (req, res) => {
  res.json({
    authorization: req.headers['authorization'], // Risk: exposes the key
    'x-api-key': req.headers['x-api-key']
  });
});

An attacker who can invoke /debug obtains the key. Similarly, improper error handling can reveal the key:

app.get('/resource', (req, res) => {
  const key = req.headers['x-api-key'];
  if (!validateKey(key)) {
    throw new Error('Invalid API key: ' + key); // Risk: key in error message
  }
  res.send('OK');
});

middleBrick’s Input Validation and Data Exposure checks are designed to detect such patterns by analyzing OpenAPI specs (including $ref resolution) and runtime behavior, then providing prioritized findings with remediation guidance.

When using middleBrick’s GitHub Action, you can add API security checks to your CI/CD pipeline and fail builds if risk scores exceed your threshold, helping prevent leaked keys from reaching production.

Api Keys-Specific Remediation in Express — concrete code fixes

To prevent token leakage when using API keys in Express, apply the following secure coding practices and configuration changes.

1. Never echo API keys in responses or logs

Strip or redact sensitive headers before logging or sending responses. Use a logging middleware that filters known secret headers.

const sensitiveHeaders = new Set(['authorization', 'x-api-key']);
app.use((req, res, next) => {
  const cleanLog = {
    method: req.method,
    url: req.url,
    headers: {}
  };
  for (const [key, value] of Object.entries(req.headers)) {
    cleanLog.headers[key] = sensitiveHeaders.has(key.toLowerCase())
      ? '[REDACTED]'
      : value;
  }
  console.log('Request:', cleanLog);
  next();
});

2. Avoid embedding keys in URLs or client‑side code

Use POST bodies or Authorization headers instead of query parameters. Ensure templates do not interpolate keys.

// Good: key passed via header
app.get('/service', (req, res) => {
  const apiKey = req.headers['x-api-key'];
  if (!apiKey) {
    return res.status(401).json({ error: 'Missing API key' });
  }
  // Use apiKey for backend call, do not forward to client
  res.json({ status: 'authorized' });
});

3. Secure error handling

Do not include secrets in error messages. Use generic messages and log details securely server‑side only.

app.use((err, req, res, next) => {
  // Log full error internally with secure storage
  console.error('Server error:', err && err.message ? err.message : err);
  res.status(500).json({ error: 'Internal server error' });
});

4. Validate and restrict key usage

Check key format and scope early, and enforce rate limiting to reduce abuse impact.

function validateKey(key) {
  return typeof key === 'string' && key.length >= 32 && /^[A-F0-9]+$/i.test(key);
}
app.use((req, res, next) => {
  const key = req.headers['x-api-key'];
  if (!key || !validateKey(key)) {
    return res.status(401).json({ error: 'Invalid API key' });
  }
  next();
});

For larger deployments, the middleBrick Pro plan includes continuous monitoring and configurable schedules to detect regressions. Its CLI tool allows you to scan from the terminal with middlebrick scan <url>, and the GitHub Action can enforce security gates in your CI/CD pipeline.

Frequently Asked Questions

How can I test if my Express endpoints leak API keys without exposing them in production?
Use unauthenticated scans with a tool that inspects responses and observable side‑effects. For example, configure a test request that hits debug or error endpoints and verify that no Authorization or x-api-key values appear in responses, logs, or redirects. Avoid sending real keys to testing environments.
What should I do if a scan reports Token Leakage involving API keys?
Immediately rotate the exposed keys, remove any code that echoes headers in responses or logs, and ensure error messages are generic. Redeploy the fixed code and re‑scan to confirm the findings are resolved.