HIGH api key exposurehapiapi keys

Api Key Exposure in Hapi with Api Keys

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

Hapi is a rich framework for building services and APIs in Node.js. When developers use Api Keys for authorization in Hapi, misconfigurations can inadvertently expose those keys or allow unauthorized access. Api Key Exposure occurs when keys are transmitted, stored, or logged in a way that external parties can discover or intercept them. This risk is amplified when keys are embedded in URLs, query parameters, or HTTP headers without additional protections, and when Hapi routes do not enforce strict validation and scoping.

In Hapi, developers often rely on built-in validation and route pre-processing to manage authorization. However, if Api Keys are passed via query strings (e.g., ?api_key=...), they can leak in server logs, browser history, and network monitoring tools. Even when using headers, if the application does not enforce strict referrer policies or transport security, keys may be exposed through cross-origin requests or insecure proxies. Hapi’s flexibility in handling multiple authentication strategies can also lead to accidental fallbacks to less secure methods if not explicitly configured.

Another vector involves improper route definitions where sensitive keys are included in error messages or debug output. Hapi’s built-in logging and error reporting can inadvertently surface Api Keys if developers do not sanitize request payloads and responses. Additionally, if routes accepting Api Keys do not implement rigorous input validation, attackers may probe for IDOR patterns or manipulate parameters to enumerate valid keys. The framework’s support for multiple authentication schemes means that without careful route configuration, an Api Key intended for a specific scope might be accepted in a broader context, increasing the exposure surface.

Real-world attack patterns include intercepting keys through unencrypted HTTP traffic, extracting keys from source code repositories, or leveraging insecure third-party integrations that log full request URLs. In regulated environments, such exposures can lead to compliance violations related to data protection and access control. Because Api Keys often provide broad access to backend services, their leakage can result in unauthorized data access or manipulation. This is especially critical in microservice architectures where Hapi services communicate internally and rely on keys for service-to-service authentication.

middleBrick scans such scenarios by checking whether Api Keys are transmitted over insecure channels, whether they appear in logs or error responses, and whether route configurations enforce appropriate constraints. The scanner evaluates the unauthenticated attack surface and flags instances where keys might be exposed through common misconfigurations. By correlating these findings with the OpenAPI specification, it identifies inconsistencies between declared security schemes and actual runtime behavior, helping developers understand where their key management practices may fall short.

Api Keys-Specific Remediation in Hapi — concrete code fixes

To secure Api Keys in Hapi, apply defense-in-depth measures that protect keys at rest, in transit, and during processing. Always transmit keys over HTTPS using strict transport security headers. Avoid exposing keys in URLs; prefer custom headers and ensure routes reject requests that omit or misuse them. Use Hapi’s built-in validation and pre-authentication hooks to enforce strict checks before allowing access to protected resources.

Secure Header-Based Api Key Handling

Define a custom authentication strategy that validates Api Keys present in request headers. This approach prevents keys from appearing in logs or browser history. Below is a complete, working Hapi example that demonstrates secure header-based key validation with scope checks.

const Hapi = require('@hapi/hapi');
const ApiKeyValidator = async (request, h) => {
  const key = request.headers['x-api-key'];
  const validKeys = {
    'prod-key-abc123': { scope: 'readWrite' },
    'internal-key-xyz789': { scope: 'readOnly' }
  };

  if (!key || !validKeys[key]) {
    return { isValid: false };
  }

  return { isValid: true, credentials: { scope: validKeys[key].scope } };
};

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

  server.auth.strategy('apiKeyAuth', 'custom', {
    validate: ApiKeyValidator
  });

  server.route([
    {
      method: 'GET',
      path: '/public',
      handler: (request, h) => ({ message: 'Public endpoint' })
    },
    {
      method: 'GET',
      path: '/secure',
      options: {
        auth: 'apiKeyAuth',
        handler: (request, h) => ({
          message: 'Authorized access',
          scope: request.auth.credentials.scope
        })
      }
    }
  ]);

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

init().catch(err => {
  console.error(err);
});

Rejecting Query Parameter Keys and Enforcing HTTPS

Configure Hapi to reject requests that include Api Keys in query strings. Combine this with a require-secure-transport policy to enforce HTTPS. The following example shows how to define a server extension that inspects incoming requests and blocks those with query parameters that resemble keys.

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

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

  server.ext('onPreHandler', (request, h) => {
    if (request.query.api_key) {
      return h.response({ error: 'Forbidden' }).code(403);
    }
    return h.continue;
  });

  server.auth.strategy('strictApiKey', 'custom', {
    validate: (request, key) => {
      // Assume key is passed via header only
      const valid = key === 'strict-key-2025';
      return { isValid: valid };
    }
  });

  server.route({
    method: 'POST',
    path: '/data',
    options: {
      auth: 'strictApiKey',
      handler: (request, h) => h.response({ success: true })
    }
  });

  await server.start();
  console.log('Secure server running');
};

init().catch(console.error);

Complementary Practices

  • Never log full request URLs or headers that may contain keys.
  • Rotate keys regularly and revoke compromised keys immediately.
  • Use middleware to sanitize error messages before they reach the client.
  • Define route schemas that explicitly reject unexpected parameters.

By adopting these patterns, you reduce the likelihood of Api Key Exposure in Hapi services. These measures align with secure authentication practices and help ensure that authorization mechanisms remain robust against common web vulnerabilities.

Frequently Asked Questions

How does middleBrick detect Api Key Exposure in Hapi configurations?
middleBrick scans whether Api Keys appear in query strings, are transmitted over non-HTTPS connections, or are logged in error responses. It cross-references runtime behavior with OpenAPI declarations to identify inconsistencies in how keys are defined and used.
Can middleBrick automatically fix Api Key Exposure issues in Hapi?
middleBrick detects and reports findings with remediation guidance, but it does not automatically fix configurations. Developers must apply the suggested code changes and validation practices to secure their Hapi services.