HIGH cors wildcardhapijavascript

Cors Wildcard in Hapi (Javascript)

Cors Wildcard in Hapi with Javascript — how this specific combination creates or exposes the vulnerability

In Hapi, a JavaScript web framework for Node.js, configuring CORS with a wildcard origin (origin: '*') while exposing credentials or sensitive headers can expose a critical cross-origin data leak. When credentials: true is set alongside a wildcard origin, browsers block the response in secure contexts, but misconfigured servers may still permit requests that appear valid from non-browser clients or less strict environments, enabling unauthorized cross-site data access.

During a black-box scan, middleBrick tests CORS behavior by sending preflight and simple requests from simulated origins and inspecting response headers for Access-Control-Allow-Origin and Access-Control-Allow-Credentials. If the server returns * for Access-Control-Allow-Origin and also includes Access-Control-Allow-Credentials: true, this inconsistency is flagged as a high-severity finding because it violates the same-origin policy expectations of browsers and can lead to unauthorized cross-origin reads when combined with other weaknesses.

Hapi’s CORS implementation relies on the cors option in server configuration. A common vulnerable setup uses a wildcard origin with exposed headers that reference authenticated resources, for example:

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

const init = async () => {
  const server = Hapi.server({
    port: 4000,
    host: 'localhost',
    routes: {
      cors: {
        origin: ['*'],
        credentials: true,
        additionalHeaders: ['x-api-key', 'authorization']
      }
    }
  });

  server.route({
    method: 'GET',
    path: '/profile',
    handler: (request, h) => {
      return { user: request.auth.credentials.user };
    }
  });

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

init();

In this example, the server responds with Access-Control-Allow-Origin: * and Access-Control-Allow-Credentials: true. Browsers treat this as insecure and suppress the response to web applications, but the configuration still signals that credentials may be shared broadly. An attacker hosting a malicious site can craft authenticated requests if session tokens or cookies are also transmitted, leveraging browser behavior to probe for data leakage or combine this with other misconfigurations to escalate impact.

middleBrick’s 12 security checks run in parallel and include a dedicated CORS evaluation under the Authentication and Property Authorization checks. The scanner detects whether wildcard origins coexist with credentialed responses and maps findings to the OWASP API Top 10 and relevant compliance frameworks. The report includes prioritized findings with severity, a per-category breakdown, and remediation guidance, helping teams understand the risk without implying automatic fixes.

Javascript-Specific Remediation in Hapi — concrete code fixes

To remediate CORS wildcard issues in Hapi with JavaScript, replace the wildcard origin with an explicit allowlist and conditionally set credentials only when necessary. For single-origin applications, specify the exact origin string; for multi-origin scenarios, implement a dynamic validator that checks against trusted values instead of relying on *.

Below are two concrete, working examples for a Hapi server in Node.js that address the vulnerability while preserving functionality.

Single trusted origin

Use a specific origin and enable credentials only when the frontend and backend share the same security boundary:

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

const init = async () => {
  const server = Hapi.server({
    port: 4000,
    host: 'localhost',
    routes: {
      cors: {
        origin: ['https://app.example.com'],
        credentials: true,
        additionalHeaders: ['x-api-key', 'authorization']
      }
    }
  });

  server.route({
    method: 'GET',
    path: '/profile',
    handler: (request, h) => {
      return { user: request.auth.credentials.user };
    }
  });

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

init();

Dynamic origin validation

For applications that must support multiple origins, use a function to validate the request origin against a trusted list:

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

const trustedOrigins = new Set([
  'https://app.example.com',
  'https://dashboard.example.com'
]);

const init = async () => {
  const server = Hapi.server({
    port: 4000,
    host: 'localhost',
    routes: {
      cors: {
        origin: (request) => {
          const incoming = request.headers.origin;
          if (trustedOrigins.has(incoming)) {
            return incoming;
          }
          return null; // Deny
        },
        credentials: true,
        additionalHeaders: ['x-api-key', 'authorization']
      }
    }
  });

  server.route({
    method: 'GET',
    path: '/profile',
    handler: (request, h) => {
      return { user: request.auth.credentials.user };
    }
  });

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

init();

These configurations ensure that Access-Control-Allow-Origin never returns * when credentials are exposed, reducing the risk of unauthorized cross-origin access. Developers should also audit which headers are necessary in additionalHeaders and avoid exposing sensitive headers unless required by the client application.

For teams using the middleBrick ecosystem, the CLI tool can be integrated into scripts with middlebrick scan <url> to validate CORS behavior after changes, while the GitHub Action can enforce security gates in CI/CD. The MCP Server allows AI coding assistants to trigger scans directly from the development environment, supporting continuous awareness without altering remediation responsibilities.

Related CWEs: dataExposure

CWE IDNameSeverity
CWE-200Exposure of Sensitive Information HIGH
CWE-209Error Information Disclosure MEDIUM
CWE-213Exposure of Sensitive Information Due to Incompatible Policies HIGH
CWE-215Insertion of Sensitive Information Into Debugging Code MEDIUM
CWE-312Cleartext Storage of Sensitive Information HIGH
CWE-359Exposure of Private Personal Information (PII) HIGH
CWE-522Insufficiently Protected Credentials CRITICAL
CWE-532Insertion of Sensitive Information into Log File MEDIUM
CWE-538Insertion of Sensitive Information into Externally-Accessible File HIGH
CWE-540Inclusion of Sensitive Information in Source Code HIGH

Frequently Asked Questions

Why is returning * for Access-Control-Allow-Origin considered risky when credentials are enabled?
Browsers block credentialed responses when Access-Control-Allow-Origin is *; however, non-browser clients may honor the combination, potentially allowing unauthorized cross-origin access. The inconsistency increases the risk of data exposure and should be avoided.
Can middleBrick fix CORS misconfigurations automatically?
No. middleBrick detects and reports CORS misconfigurations with remediation guidance, but it does not fix, patch, block, or remediate. Teams must apply the suggested configuration changes in their Hapi server code.