HIGH cors wildcardhapicockroachdb

Cors Wildcard in Hapi with Cockroachdb

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

A CORS wildcard (Access-Control-Allow-Origin: *) in a Hapi server that also connects to Cockroachdb can unintentionally expose database-backed responses to any origin. When routes fetch rows from Cockroachdb and reflect data in HTTP responses, a wildcard allows any external page to make authenticated-style requests via cookies or tokens and read the returned data. This becomes a CORS-based information disclosure that compounds database exposure risks.

Hapi applications often use routes like /api/users/{id} that query Cockroachdb with a SQL SELECT keyed by an authenticated subject. If the route sets cors: { origin: '*' } and does not validate an Origin against a whitelist, an attacker’s page can invoke the endpoint via fetch and, if the browser includes credentials, observe reflected user-specific data. The presence of Cockroachdb means the data is authoritative and potentially sensitive; a wildcard removes a layer of policy enforcement that should exist before data leaves the service.

Attack patterns mirror OWASP API Top 10 #5 (Broken Function Level Authorization) and #7 (Data Exposure). An unauthenticated attacker does not need to compromise Cockroachdb directly; they abuse a relaxed CORS policy to coax the Hapi backend into returning information it should restrict to known clients. For example, a route that returns SELECT email, role FROM users WHERE id = $1 can be triggered cross-origin if the Hapi CORS configuration permits *, and the response is delivered with credentials. This can facilitate account enumeration when error messages differ by presence of data, or expose PII when the response includes sensitive fields.

In practice, developers sometimes enable a wildcard to simplify initial integration with Cockroachdb, then forget to tighten it after authentication is added. Because Hapi can serve both public metadata and user-specific Cockroachdb results from the same service, a single wildcard can apply broadly, undermining row-level security assumptions. The risk is higher when endpoints expose identifiers that can be iterated, because the attacker can probe the API from any domain and collect data without needing API keys, provided the browser’s credential storage is used.

To identify this during a scan, middleBrick tests CORS behavior with unauthenticated probes and cross-references findings with the API’s data sources. If the scanner detects a wildcard and observes responses that contain user-specific content from Cockroachdb, it flags a high-severity finding with remediation guidance to replace the wildcard with an explicit origin list and enforce server-side checks before database queries.

Cockroachdb-Specific Remediation in Hapi — concrete code fixes

Remediation focuses on tightening CORS in Hapi while preserving correct access to Cockroachdb. The goal is to avoid wildcard origins and validate origins server-side, especially when queries reference authenticated subjects. Below are concrete examples that align with best practices for Hapi and Cockroachdb integration.

1. Whitelist origins instead of using wildcard

Replace { origin: '*' } with a controlled list. For Hapi, this can be done via the server route CORS options:

const Hapi = require('@hapi/hapi');
const { Pool } = require('pg');

const pool = new Pool({
  connectionString: process.env.COCKROACHDB_URL,
});

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

  server.route({
    method: 'GET',
    path: '/api/users/{id}',
    options: {
      cors: {
        origin: ['https://app.example.com', 'https://admin.example.com'],
        additionalHeaders: ['authorization', 'content-type'],
      },
      handler: async (request) => {
        const { id } = request.params;
        const client = await pool.connect();
        try {
          const res = await client.query('SELECT id, email, role FROM users WHERE id = $1', [id]);
          if (res.rows.length === 0) {
            return { error: 'not_found' };
          }
          return res.rows[0];
        } finally {
          client.release();
        }
      },
    },
  });

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

process.on('unhandledRejection', (err) => {
  console.error(err);
  process.exit(1);
});

init();

2. Validate Origin dynamically for Cockroachdb tenant isolation

When origins depend on runtime data (e.g., tenant domains stored in Cockroachdb), validate against a database-backed allowlist. Perform the check before executing SQL that returns user-specific data:

const validateOrigin = async (origin) => {
  const client = await pool.connect();
  try {
    const res = await client.query('SELECT 1 FROM trusted_origins WHERE origin = $1', [origin]);
    return res.rowCount > 0;
  } finally {
    client.release();
  }
};

server.route({
  method: 'GET',
    path: '/api/profile',
    options: {
      cors: {
        origin: async (origin, callback) => {
          if (!origin) return callback(null, true);
          const allowed = await validateOrigin(origin);
          callback(null, allowed || false);
        },
        additionalHeaders: ['authorization'],
      },
      handler: async (request) => {
        const userAgent = request.headers['user-agent'] || '';
        const client = await pool.connect();
        try {
          const tenantId = request.auth.credentials.tenantId;
          const res = await client.query(
            'SELECT profile_data FROM tenant_profiles WHERE tenant_id = $1',
            [tenantId]
          );
          return res.rows[0]?.profile_data || {};
        } finally {
          client.release();
        }
      },
    },
});

3. Enforce server-side checks before Cockroachdb queries

Even with a strict origin list, ensure that authorization is evaluated per request. Do not rely on CORS alone to protect data. Combine CORS with authentication/authorization logic that verifies the requesting user can access the targeted rows:

server.route({
  method: 'GET',
  path: '/api/records/{recordId}',
  options: {
    cors: {
      origin: ['https://app.example.com'],
    },
    auth: {
      mode: 'required',
      strategy: 'jwt',
    },
    handler: async (request) => {
      const { recordId } = request.params;
      const userId = request.auth.credentials.sub;
      const client = await pool.connect();
      try {
        const res = await client.query(
          'SELECT * FROM records WHERE id = $1 AND user_id = $2',
          [recordId, userId]
        );
        if (res.rows.length === 0) {
          throw Boom.notFound();
        }
        return res.rows[0];
      } finally {
        client.release();
      },
    },
  },
});

These patterns ensure that CORS does not become an inadvertent data channel to Cockroachdb. By combining explicit origins, runtime origin validation, and per-request authorization, the service reduces the chance that a wildcard-style misconfiguration leads to unintended exposure of database-backed responses.

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 CORS wildcard be safe if the backend has no authentication?
No. Even without authentication, a wildcard allows any site to read responses, which can lead to information disclosure when the backend returns user-specific data from Cockroachdb. Always use explicit origins or strict server-side checks.
Does fixing CORS in Hapi automatically protect Cockroachdb?
No. CORS is a browser-enforced policy; fixing it prevents unauthorized web origins from triggering requests. You must also enforce authentication, authorization, and SQL-level permissions to protect Cockroachdb directly.