HIGH api key exposurekoabearer tokens

Api Key Exposure in Koa with Bearer Tokens

Api Key Exposure in Koa with Bearer Tokens — how this specific combination creates or exposes the vulnerability

In Koa, using Bearer tokens for authentication means tokens are typically passed in the Authorization header as Authorization: Bearer <token>. When APIs are implemented without strict transport and storage controls, these tokens can be exposed in logs, error messages, or via insecure referer headers. A common misconfiguration is logging the full request headers, which inadvertently captures bearer tokens and persists them in log stores that may be accessible to unauthorized parties.

Another exposure path arises when APIs accept bearer tokens via URL query parameters or fragments for convenience or legacy reasons. For example, a client might pass https://api.example.com/resource?access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9. Such tokens can leak through browser history, server logs, or proxy logs. MiddleBrick’s scan checks for these exposure vectors by inspecting how tokens are transmitted and whether they appear in locations where they should not, such as query strings or logs.

Koa applications that do not enforce HTTPS can also be susceptible to token interception in transit. Without mandatory HTTPS, bearer tokens sent in the Authorization header can be captured via man-in-the-middle attacks. MiddleBrick tests for encryption by verifying that endpoints require TLS and that responses are not delivered over plain HTTP. Additionally, if the token is embedded in JavaScript sent to the client (for example in initial page loads or SPA bootstrapping), it can be extracted by client-side scripts, leading to unintended access.

Middleware that improperly handles token parsing can also contribute to exposure. For instance, if a middleware component parses the Authorization header and attaches the token to the context object without validation or redaction, sensitive information might be included in debug output or passed inadvertently to downstream services. MiddleBrick’s checks include scanning for token leakage in responses and verifying that tokens are not reflected in JSON payloads or error details.

Because bearer tokens act as equivalent credentials, their exposure can lead to unauthorized access to protected resources. Attackers who obtain a token can impersonate the associated client or user until the token is revoked. MiddleBrick evaluates whether the API follows least-privilege principles, scopes tokens appropriately, and whether there are mechanisms to detect token misuse, such as unusual geographic access patterns or elevated permissions granted to bearer-authenticated requests.

Real-world examples include scenarios where a Koa server uses a library that logs req.headers without filtering. A scan might detect that the Authorization header is present in logs by checking for patterns that resemble bearer tokens in output destinations. Another scenario involves CORS misconfigurations that allow unauthorized origins to inspect responses containing bearer tokens, enabling cross-origin leakage. These findings are categorized with severity levels and mapped to controls in frameworks such as OWASP API Security Top 10 and SOC2, providing clear remediation guidance.

Bearer Tokens-Specific Remediation in Koa — concrete code fixes

To secure Bearer tokens in a Koa application, enforce HTTPS across all routes and reject requests that do not use TLS. Use HTTP Strict Transport Security (HSTS) headers to instruct browsers to always use HTTPS. Configure your server to redirect HTTP to HTTPS and ensure that cookies and tokens are never transmitted over unencrypted channels.

Example: Enforcing HTTPS in Koa

const Koa = require('koa');
const redirectHttps = require('koa-sslify');

const app = new Koa();
app.use(redirectHttps());

app.use(async (ctx) => {
  ctx.body = 'Secure endpoint';
});

app.listen(443);

Avoid logging sensitive headers, including Authorization. Implement a sanitized logging middleware that excludes bearer tokens and other credentials. This prevents tokens from being written to log files or external logging services where they could be exposed.

Example: Safe Logging Middleware in Koa

const Koa = require('koa');
const app = new Koa();

app.use(async (ctx, next) => {
  // Redact sensitive headers before logging
  const safeHeaders = { ...ctx.request.headers };
  if (safeHeaders.authorization) {
    safeHeaders.authorization = '[REDACTED]';
  }
  console.log('Request received', {
    method: ctx.method,
    url: ctx.url,
    headers: safeHeaders,
  });
  await next();
});

app.use(async (ctx) => {
  ctx.body = 'Request processed';
});

app.listen(3000);

When accepting tokens, validate their format and scope before use. Do not rely on tokens passed as query parameters. Instead, require the Authorization header and ensure tokens are not embedded in URLs. Validate the token structure and, where applicable, verify signatures if using JWTs.

Example: Validating Bearer Token Usage in Koa

const Koa = require('koa');
const app = new Koa();

app.use(async (ctx, next) => {
  const authHeader = ctx.request.header.authorization;
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    ctx.status = 401;
    ctx.body = { error: 'Unauthorized' };
    return;
  }
  const token = authHeader.substring(7);
  if (!token || token.length < 20) {
    ctx.status = 400;
    ctx.body = { error: 'Invalid token format' };
    return;
  }
  // Proceed with token validation (e.g., verify JWT, check revocation)
  ctx.state.token = token;
  await next();
});

app.use(async (ctx) => {
  ctx.body = { message: 'Authorized access' };
});

app.listen(3000);

Implement token scoping and avoid granting excessive permissions to bearer tokens. Use middleware to enforce that tokens are only valid for specific endpoints or operations. This limits the impact of a leaked token. MiddleBrick’s checks include verifying that tokens are not used across overly broad scopes and that API endpoints validate token permissions correctly.

Example: Scope-Based Authorization in Koa

const Koa = require('koa');
const app = new Koa();

const VALID_SCOPES = new Set(['read:data', 'write:data']);

app.use(async (ctx, next) => {
  const authHeader = ctx.request.header.authorization;
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    ctx.status = 401;
    ctx.body = { error: 'Unauthorized' };
    return;
  }
  const token = authHeader.substring(7);
  // Simulate token introspection or JWT payload extraction
  const payload = getTokenPayload(token); // Assume this function validates and decodes
  if (!payload.scopes || !payload.scopes.some(s => VALID_SCOPES.has(s))) {
    ctx.status = 403;
    ctx.body = { error: 'Insufficient scope' };
    return;
  }
  ctx.state.user = payload.sub;
  await next();
});

function getTokenPayload(token) {
  // In practice, verify signature and decode JWT
  return { sub: 'user-123', scopes: ['read:data'] };
}

app.use(async (ctx) => {
  ctx.body = { message: 'Access granted' };
});

app.listen(3000);

Frequently Asked Questions

What does MiddleBrick check for regarding Bearer token exposure in Koa APIs?
MiddleBrick checks whether Bearer tokens appear in logs, query strings, or are transmitted without HTTPS. It also verifies that tokens are not reflected in responses and that middleware does not inadvertently expose tokens through debug output or CORS misconfigurations.
Can MiddleBrick scan Koa APIs that use Bearer tokens without authentication for the scan itself?
Yes, MiddleBrick performs black-box scanning and does not require credentials. It tests the unauthenticated attack surface to identify exposure points related to Bearer token handling.