HIGH cors wildcardexpressapi keys

Cors Wildcard in Express with Api Keys

Cors Wildcard in Express with Api Keys — how this specific combination creates or exposes the vulnerability

In Express, using a CORS wildcard (origin: '*') while also protecting routes with API key validation can inadvertently expose sensitive endpoints to unauthorized cross-origin requests. The vulnerability occurs when CORS headers are applied globally, but authentication (API key checks) is implemented inconsistently or conditionally. An attacker can craft a web page that makes a cross-origin request to your Express API; the browser will first send a preflight OPTIONS request. If the server responds with Access-Control-Allow-Origin: * and does not require credentials or strict origin validation, the browser may allow the subsequent request to proceed even when the API key is missing or leaked.

Consider an Express setup where CORS is configured permissively:

const cors = require('cors');
app.use(cors({
  origin: '*',
  methods: ['GET', 'POST'],
}));

If API key validation is applied as a middleware but not enforced for all routes, a preflight request can pass CORS checks and lead to unauthorized access. For example:

app.use((req, res, next) => {
  const key = req.headers['x-api-key'];
  if (!key || key !== process.env.API_KEY) {
    return res.status(401).json({ error: 'Unauthorized' });
  }
  next();
});

The risk is compounded when the API key is embedded in client-side code or exposed in logs, as the wildcard CORS policy allows any domain to initiate requests that may carry the key. This combination can lead to sensitive data exposure or unauthorized actions, mapping to OWASP API Top 10 controls such as authentication and authorization failures. The scanner checks for such misconfigurations under Authentication and BOLA/IDOR categories, noting when permissive CORS intersects with weak or inconsistent API key enforcement.

Additionally, if the API responds to preflight requests with Access-Control-Allow-Credentials: true while using a wildcard origin, browsers may block the request, but inconsistent implementations can still allow credentials to be sent cross-origin. This nuance is important because real-world integrations often involve multiple frontend domains, and a misconfigured wildcard can bypass intended isolation. middleBrick detects these patterns during its 12 parallel security checks, highlighting how CORS and authentication mechanisms interact.

Api Keys-Specific Remediation in Express — concrete code fixes

To remediate the risk, enforce strict origin validation and ensure API key checks are applied uniformly before any route handler. Avoid wildcard origins when API keys are used; instead, specify trusted origins explicitly and conditionally apply CORS based on authentication state.

Use the following secure Express configuration:

const cors = require('cors');

const allowedOrigins = ['https://app.yourcompany.com', 'https://admin.yourcompany.com'];

const corsOptions = {
  origin: function (origin, callback) {
    if (!origin || allowedOrigins.indexOf(origin) !== -1) {
      callback(null, true);
    } else {
      callback(new Error('Not allowed by CORS'));
    }
  },
  methods: ['GET', 'POST'],
  credentials: true,
};

app.use(cors(corsOptions));

Combine this with a centralized API key validation middleware that runs for all relevant routes:

app.use((req, res, next) => {
  if (req.path.startsWith('/api/')) {
    const key = req.headers['x-api-key'];
    if (!key || key !== process.env.API_KEY) {
      return res.status(403).json({ error: 'Forbidden' });
    }
  }
  next();
});

For finer control, apply the key check only to specific routes or route groups:

app.get('/api/data', (req, res, next) => {
  const key = req.headers['x-api-key'];
  if (!key || key !== process.env.API_KEY) {
    return res.status(401).json({ error: 'Unauthorized' });
  }
  res.json({ data: 'secure' });
});

When using the middleBrick CLI (middlebrick scan <url>) or integrating the GitHub Action into CI/CD, these configurations help ensure that scans report a lower security risk by aligning CORS and authentication. The dashboard can track changes over time, and the Pro plan’s continuous monitoring can alert you if a future scan detects a wildcard origin alongside API key routes.

Remember that middleBrick detects and reports these issues but does not fix them; the remediation guidance provided should be implemented in your codebase to reduce exposure.

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

Can a wildcard CORS origin be safe if API keys are required?
No. A wildcard origin allows any domain to make requests; if an attacker can trick a user’s browser into sending a request with the API key, the key may be exposed. Always specify explicit origins and avoid wildcard when credentials or keys are involved.
How does middleBrick detect CORS and API key misconfigurations?
middleBrick runs 12 parallel security checks including Authentication and BOLA/IDOR. It analyzes your OpenAPI spec and runtime behavior to identify permissive CORS policies and inconsistent API key enforcement, then reports findings with severity and remediation guidance.