HIGH api key exposurehapijwt tokens

Api Key Exposure in Hapi with Jwt Tokens

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

Hapi is a rich framework for building services and APIs in Node.js. When JWT tokens are used for authentication, developers often focus on verifying token validity and payload claims while inadvertently exposing sensitive artifacts through logs, error messages, or misconfigured endpoints. Api key exposure in this context refers to scenarios where static keys, secrets, or token material are unintentionally revealed to unauthenticated parties.

One common pattern involves using Hapi routes to introspect or manage JWT-related configuration, such as exposing debug endpoints that return signing keys or secrets. For example, a route like /debug/jwt-config might return the server’s secret or public key in responses, which becomes an api key exposure issue if accessible without authentication. In Hapi, route handlers that log token payloads or errors with full stack traces can inadvertently print secrets to centralized logging systems, effectively leaking keys.

The combination of Hapi’s plugin-based routing and JWT’s reliance on securely managed secrets amplifies risk when endpoints are unintentionally included in the unauthenticated attack surface. During black-box scanning, middleBrick tests routes that may reveal configuration or keys through verbose error messages or misconfigured CORS settings. For instance, a route accepting an Authorization header may mishandle invalid tokens and respond with detailed errors that include the expected token format or key identifiers, aiding an attacker in crafting token-related attacks.

Another exposure vector involves improper storage or handling of secrets within Hapi applications. If secrets are hardcoded in route files or configuration modules, scanners can detect them through source code analysis or by probing endpoints that return environment details. Even when using environment variables, if the application serves a route that echoes configuration for debugging, it can expose keys to unauthenticated users.

SSRF and unsafe consumption patterns can also lead to api key exposure in Hapi with JWT tokens. An SSRF vulnerability might allow an attacker to coerce the server into making requests to internal metadata services where JWT signing keys are temporarily stored or retrieved. If Hapi services consume untrusted inputs to build JWTs or validate tokens without strict validation, attackers can exploit this to leak sensitive material through crafted responses.

Inventory management and unsafe consumption checks by middleBrick identify routes that disclose configuration or keys and flag them as high-risk findings. These findings typically include severity levels and remediation guidance to ensure JWT secrets remain protected and are not exposed through debug or introspection endpoints in Hapi services.

Jwt Tokens-Specific Remediation in Hapi — concrete code fixes

To remediate api key exposure when using JWT tokens in Hapi, ensure that no route exposes signing keys, secrets, or sensitive token metadata. Below are concrete code examples that demonstrate secure handling of JWT tokens in Hapi without leaking keys.

Secure JWT Verification Route

Define a route that verifies JWT tokens without returning sensitive information. Use jwt.verify with proper error handling that does not expose secrets or internal details.

const Hapi = require('@hapi/hapi');
const jwt = require('jsonwebtoken');

const init = async () => {
  const server = Hapi.server({ port: 3000, host: 'localhost' });

  server.route({
    method: 'POST',
    path: '/api/protected',
    options: {
      auth: false,
      handler: (request, h) => {
        const token = request.headers.authorization?.split(' ')[1];
        if (!token) {
          return { error: 'Unauthorized' };
        }
        try {
          const decoded = jwt.verify(token, process.env.JWT_SECRET);
          return { message: 'Access granted', user: decoded.sub };
        } catch (err) {
          // Do not expose err.message or err.stack
          return { error: 'Invalid token' };
        }
      }
    }
  });

  await server.start();
  console.log('Server running on %s', server.info.uri);
};

init();

Removing Debug Endpoints

Avoid routes that return JWT configuration or keys. If debugging is required, use controlled environments and ensure such routes are protected with strong authentication or disabled in production.

// Do not include routes like this in production:
// server.route({
//   method: 'GET',
//   path: '/debug/jwt-config',
//   options: {
//     auth: 'jwt-admin', // even this may be insufficient
//     handler: (request, h) => {
//       return { secret: process.env.JWT_SECRET }; // dangerous
//     }
//   }
// });

Environment and Secret Management

Load secrets from secure sources and avoid logging them. Configure Hapi to use environment variables and validate inputs strictly.

if (!process.env.JWT_SECRET) {
  throw new Error('Missing JWT_SECRET');
}

// Use helmet-like headers in Hapi via route or server extensions
server.ext('onPreResponse', (request, h) => {
  const response = request.response;
  if (response.variety === 'view') {
    response.header('X-Content-Type-Options', 'nosniff');
  }
  return h.continue;
});

Input Validation and SSRF Mitigation

Validate all inputs that influence JWT construction. Use Joi schemas in Hapi to enforce strict payloads and avoid SSRF-related leaks.

const Joi = require('joi');

server.route({
  method: 'POST',
  path: '/api/token',
  options: {
    auth: false,
    validate: {
      payload: Joi.object({
        sub: Joi.string().required(),
        scope: Joi.array().items(Joi.string())
      })
    },
    handler: (request, h) => {
      const { sub, scope } = request.payload;
      const token = jwt.sign({ sub, scope }, process.env.JWT_SECRET, { expiresIn: '1h' });
      return { token };
    }
  }
});

These practices reduce the likelihood of api key exposure and align with secure handling of JWT tokens in Hapi. middleBrick scans can validate that such routes are not exposing sensitive configuration and that error handling does not leak secrets.

Frequently Asked Questions

Can middleBrick detect JWT secret exposure in Hapi APIs?
Yes, middleBrick scans for routes or configurations that may expose JWT secrets or related keys and flags them with severity and remediation guidance.
Does Hapi middleware automatically protect JWT tokens?
Hapi does not automatically protect JWT tokens; developers must ensure secrets are not exposed through routes, logs, or error responses and validate all inputs.