HIGH api key exposurerestifybearer tokens

Api Key Exposure in Restify with Bearer Tokens

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

When Restify servers expose bearer tokens through misconfiguration or insecure handling, the API key exposure risk becomes tangible. Restify is often used to build JSON/HTTP APIs, and developers may inadvertently leak secrets via logs, error messages, or overly permissive CORS and route handlers. In a black-box scan, middleBrick tests unauthenticated endpoints and checks whether bearer tokens or other credentials are returned in responses, reflected in headers, or discoverable through enumeration.

One common pattern is attaching bearer tokens as URL query parameters or custom headers for internal service communication. If these are echoed back in HTTP responses or logs, an attacker who can observe network traffic or error responses can capture the token. middleBrick’s checks include Data Exposure and Unsafe Consumption, which look for sensitive data leaking in responses, insecure HTTP methods, and verbose error traces that reveal stack paths or configuration details.

Bearer tokens used for authorization can become API keys if they are treated as static secrets shared across services. Without proper rotation and without scoping, a leaked bearer token effectively functions as an API key, granting access to protected endpoints. middleBrick’s Authentication and Authorization checks probe endpoints that accept bearer tokens in the Authorization header and then test whether resources intended for specific users or roles are accessible when the token is swapped or omitted (BOLA/IDOR). If endpoints do not enforce strict ownership checks, the combination of bearer token misuse and missing authorization controls leads to unauthorized data access.

Another vector is insecure OpenAPI/Swagger exposure. If an API served by Restify includes an OpenAPI spec at a well-known path (for example, /openapi.json or /swagger/v1/swagger.json) and that spec contains example values with bearer tokens or placeholder keys, those secrets can be harvested by scanners. middleBrick performs full $ref resolution across OpenAPI 2.0, 3.0, and 3.1 specs and cross-references definitions with runtime findings, so any example tokens present in the spec are surfaced as findings under Data Exposure and Inventory Management.

SSRF and External Request handlers in Restify can also contribute to exposure. If user-supplied URLs are used to make outbound HTTP requests and the server includes authorization headers automatically, an attacker can trick the service into making requests to internal metadata services or external endpoints that return credentials. middleBrick tests SSRF by supplying internal IPs and cloud metadata URLs to see if the server responds with sensitive information, which can include bearer tokens stored in environment variables or injected headers.

Finally, rate limiting and authentication bypass issues can amplify exposure. Without proper rate limiting on authentication endpoints, attackers can perform token enumeration or credential stuffing. middleBrick’s Rate Limiting check verifies whether authentication paths are protected and whether repeated requests with invalid bearer tokens trigger appropriate throttling. When combined with missing authentication on administrative routes, this can lead to token extraction through brute-force or timing-based techniques.

Bearer Tokens-Specific Remediation in Restify — concrete code fixes

To reduce api key exposure when using bearer tokens in Restify, apply strict handling rules and avoid leaking tokens in responses, logs, or error traces. Below are concrete remediation steps with code examples.

1. Never echo bearer tokens in responses or logs

Ensure that token values are not included in HTTP response bodies or headers. Avoid logging authorization headers directly. Instead, log only metadata such as request IDs.

const restify = require('restify');
const server = restify.createServer();

server.use((req, res, next) => {
  // Safe: do not log bearer token
  const authHeader = req.headers.authorization || '';
  const masked = authHeader.replace(/Bearer\s\S+/, 'Bearer ***');
  server.log.info({ reqId: req.id, auth: masked }, 'incoming request');
  return next();
});

server.get('/profile', (req, res, next) => {
  const token = req.headers.authorization;
  if (!token || !token.startsWith('Bearer ')) {
    return next(new restify.UnauthorizedError('Missing bearer token'));
  }
  const tokenValue = token.slice(7);
  // Use tokenValue to validate with auth provider; do not send it back
  res.send({ message: 'profile data' });
  return next();
});

server.listen(8080, () => console.log('Listening on port 8080'));

2. Validate and scope bearer tokens strictly

Check token format, issuer, audience, and scope. Do not accept bearer tokens intended for other services. If using JWTs, validate signature and claims instead of treating them as opaque API keys.

const jwt = require('jsonwebtoken');

function verifyBearer(req, res, next) {
  const auth = req.headers.authorization;
  if (!auth || !auth.startsWith('Bearer ')) {
    return next(new restify.UnauthorizedError('Invalid authorization'));
  }
  const token = auth.slice(7);
  try {
    const decoded = jwt.verify(token, process.env.JWT_PUBLIC_KEY, {
      audience: 'my-api',
      issuer: 'https://auth.example.com/',
    });
    req.user = decoded;
    return next();
  } catch (err) {
    return next(new restify.UnauthorizedError('Invalid token'));
  }
}

server.pre(restify.plugins.preValidation(verifyBearer));

3. Avoid bearer tokens as API keys in examples and specs

When publishing an OpenAPI spec, remove example bearer tokens or replace them with placeholder values. Do not embed real secrets in the spec served at runtime.

// openapi.json — safe example values
{
  "paths": {
    "/users/{id}": {
      "get": {
        "securitySchemes": {
          "bearerAuth": {
            "type": "http",
            "scheme": "bearer"
          }
        },
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "example": {
                  "id": "123",
                  "name": "demo"
                }
              }
            }
          }
        }
      }
    }
  },
  "components": {
    "securitySchemes": {
      "bearerAuth": {
        "type": "http",
        "scheme": "bearer"
      }
    }
  }
}

4. Isolate token acquisition and use

Do not allow bearer tokens to be used as generic API keys across unrelated endpoints. Scope tokens to specific routes and enforce ownership checks to prevent BOLA/IDOR. Combine with rate limiting on authentication paths to reduce brute-force risk.

server.get('/users/:ownerId', (req, res, next) => {
  const tokenUser = req.user.sub; // from verified JWT
  const paramOwner = req.params.ownerId;
  if (tokenUser !== paramOwner) {
    return next(new restify.ForbiddenError('Cannot access this resource'));
  }
  res.send({ data: 'private' });
  return next();
});

5. Secure spec exposure and disable debug in production

Do not serve OpenAPI specs containing sensitive examples in production. Disable debug or dev routes that might reveal internal configuration or token handling logic.

if (process.env.NODE_ENV !== 'production') {
  server.get('/openapi.json', (req, res, next) => {
    res.send(openapiDocument); // only in non-production
  });
}

// Disable verbose error stack traces in production
server.on('restifyInvalidRequest', (req, res, err) => {
  res.send(400, { error: 'Invalid request' });
});

6. Use environment variables and avoid hardcoded keys

Never commit bearer token values to source control. Load secrets from environment variables and rotate them regularly. If a token is exposed, have a revocation and rotation plan.

// server configuration — do not hardcode tokens
const AUTH_TOKEN = process.env.SERVICE_TOKEN;
if (!AUTH_TOKEN) {
  throw new Error('Missing SERVICE_TOKEN environment variable');
}

Frequently Asked Questions

How does middleBrick detect API key exposure in Restify APIs?
middleBrick scans unauthenticated endpoints and inspects responses, headers, and spec examples for leaked bearer tokens. It checks Data Exposure, Unsafe Consumption, and OpenAPI/Swagger $ref resolution to identify tokens in specs or verbose error messages that may reveal secrets.
Can middleBrick fix exposed bearer tokens in Restify?
middleBrick detects and reports findings with remediation guidance; it does not fix, patch, or block. Developers should apply secure coding practices, avoid echoing tokens, validate bearer tokens, and remove secrets from specs and logs.