HIGH auth bypassrestifybearer tokens

Auth Bypass in Restify with Bearer Tokens

Auth Bypass in Restify with Bearer Tokens — how this specific combination creates or exposes the vulnerability

Auth bypass in a Restify service that relies on Bearer Tokens typically occurs when token validation is incomplete, absent, or misapplied. A common pattern is initializing Restify with a security plugin but failing to enforce authentication on specific routes or applying it inconsistently across route prefixes.

For example, a server may apply authentication to an admin prefix but omit it from public or user-facing endpoints, creating a BOLA/IDOR-like path where an attacker can act on other users’ resources by simply omitting or guessing a valid token. Even when tokens are validated, weaknesses in how claims are checked—such as not verifying the scope or role—can allow higher-privilege operations on low-privilege routes.

Consider this intentionally vulnerable Restify setup:

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

// Insecure: no authentication guard on this route
server.get('/public/users/:id', (req, res, next) => {
  // Direct ID usage without verifying ownership or token claims
  const userId = req.params.id;
  res.send({ userId: userId, email: 'email' });
  return next();
});

// Token validation applied only to /admin, creating an auth bypass for /public
server.pre(restify.plugins.authorizationBearer({}));
server.all('/admin/*', (req, res, next) => {
  // Assume req.authorization is present and valid
  if (!req.authorization || !req.authorization.credentials) {
    return res.send(401, { error: 'Unauthorized' });
  }
  // Missing scope/role checks
  return next();
});

server.listen(8080, () => console.log('insecure server running'));

In this setup, an attacker can access /public/users/123 without a token or with a stolen token for another user, because the route lacks required authentication and does not validate whether the requesting subject matches the resource’s owner. This maps to OWASP API Top 10 API1:2023 Broken Object Level Authorization, and can be surfaced by middleBrick as a BOLA/IDOR finding with high severity.

Additionally, an unauthenticated LLM endpoint within a public API can expose system prompts or operational hints that facilitate further attacks. middleBrick’s LLM/AI Security checks specifically probe for such exposures via active prompt injection techniques and system prompt leakage detection, providing an additional layer of insight for API owners using AI components.

Proper remediation requires applying authentication consistently, validating tokens on every relevant route, and enforcing granular authorization checks at the resource level.

Bearer Tokens-Specific Remediation in Restify — concrete code fixes

Secure Restify APIs with Bearer Tokens by ensuring every route that handles user data requires a valid token and that token validation includes claims verification. Use a centralized pre-handler to avoid route-by-route omissions.

Here is a corrected Restify example with Bearer Token validation enforced uniformly:

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

// Centralized Bearer validation
server.pre((req, res, next) => {
  // Require Authorization header for protected routes
  const protectedPrefixes = ['/users', '/admin'];
  const isProtected = protectedPrefixes.some(p => req.path.startsWith(p));
  if (isProtected) {
    const auth = req.authorization;
    if (!auth || auth.scheme !== 'Bearer' || !auth.token) {
      return res.send(401, { error: 'Unauthorized: Missing Bearer token' });
    }
    // In production, validate token with your auth provider (e.g., introspect JWKS)
    // For this example, we assume a helper that returns decoded claims
    const claims = validateBearerToken(auth.token);
    if (!claims) {
      return res.send(403, { error: 'Forbidden: Invalid token' });
    }
    req.claims = claims;
  }
  return next();
});

function validateBearerToken(token) {
  // Placeholder: integrate with your identity provider
  // Return decoded claims if valid, else null
  if (token === 'valid_token_user') {
    return { sub: 'user-123', scope: 'read:users', role: 'user' };
  }
  if (token === 'valid_token_admin') {
    return { sub: 'admin-1', scope: 'read:users write:users', role: 'admin' };
  }
  return null;
}

// Protected route with ownership check
server.get('/users/:id', (req, res, next) => {
  const requestingUserId = req.claims.sub;
  const resourceUserId = req.params.id;
  if (requestingUserId !== resourceUserId && !req.claims.scope.includes('read:users')) {
    return res.send(403, { error: 'Forbidden: Insufficient scope' });
  }
  res.send({ userId: resourceUserId, email: 'email' });
  return next();
});

// Admin-only route with role check
server.get('/admin/settings', (req, res, next) => {
  if (req.claims.role !== 'admin') {
    return res.send(403, { error: 'Forbidden: Admin role required' });
  }
  res.send({ settings: { maintenance: false } });
  return next();
});

server.listen(8080, () => console('secure server running'));

Key points in this remediation:

  • Apply authentication to all sensitive routes via a server.pre handler, reducing the chance of missing guards.
  • Verify the token scheme is Bearer and ensure the token is present before attempting validation.
  • Enforce scope and role checks tailored to the operation, preventing privilege escalation even if a token is valid but lacks required permissions.
  • Use centralized logic so future route additions inherit the same protections, which is valuable when using the CLI (middlebrick scan <url>) or GitHub Action to monitor changes.

When using the Pro plan, continuous monitoring and CI/CD integration can alert you if a new route lacks required authentication, helping maintain these controls as the API evolves.

Related CWEs: authentication

CWE IDNameSeverity
CWE-287Improper Authentication CRITICAL
CWE-306Missing Authentication for Critical Function CRITICAL
CWE-307Brute Force HIGH
CWE-308Single-Factor Authentication MEDIUM
CWE-309Use of Password System for Primary Authentication MEDIUM
CWE-347Improper Verification of Cryptographic Signature HIGH
CWE-384Session Fixation HIGH
CWE-521Weak Password Requirements MEDIUM
CWE-613Insufficient Session Expiration MEDIUM
CWE-640Weak Password Recovery HIGH

Frequently Asked Questions

How does middleBrick detect auth bypass risks in Restify APIs using Bearer Tokens?
middleBrick runs unauthenticated black-box scans with 12 parallel security checks including Authentication, BOLA/IDOR, and Authorization. It tests endpoints without credentials, validates token requirements per route, and checks whether token claims (scope, role) are enforced, mapping findings to OWASP API Top 10 and returning prioritized remediation guidance.
Does middleBrick’s LLM/AI Security checking apply to Restify APIs with Bearer Tokens?
Yes. If your Restify API exposes unauthenticated LLM endpoints, middleBrick’s LLM/AI Security checks perform active prompt injection probes and system prompt leakage detection, scanning for PII or secrets in LLM responses to identify exposures specific to AI integration.