HIGH cors wildcardsailscockroachdb

Cors Wildcard in Sails with Cockroachdb

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

When a Sails.js application uses a wildcard CORS origin while connecting to a CockroachDB cluster, it can unintentionally expose database-backed endpoints to any requesting origin. Sails routes map directly to controller actions that often issue queries against the database; if those actions rely on session or cookie-based authorization while also responding to cross-origin requests, the wildcard setting allows malicious sites to make authenticated calls on behalf of users.

Consider a typical Sails controller that queries CockroachDB for user-specific records:

// api/controllers/UserController.js
module.exports = {
  getUserProfile: async function (req, res) {
    const userId = req.session.userId;
    const pool = req.app.get('cockroachPool');
    const result = await pool.query('SELECT id, email, settings FROM users WHERE id = $1', [userId]);
    return res.ok(result.rows[0]);
  }
};

If CORS is configured with origin: '*' in config/cors.js, any site can invoke getUserProfile with a valid session cookie. Because CockroachDB returns rows tied to the authenticated user, the wildcard CORS policy allows a malicious site to perform unauthorized reads via cross-origin requests, effectively turning the endpoint into an inadvertent data exposure channel. This becomes more impactful when endpoints return sensitive tables or join results that include personally identifiable information (PII).

The issue is compounded when preflight requests are handled permissively. Sails may respond to OPTIONS requests with broad headers, signaling to browsers that any origin is acceptable. Attackers can chain this with CSRF-like techniques, where a form or script triggers state-changing requests that rely on the session identity established via cookies. CockroachDB’s transactional guarantees do not mitigate this; the vulnerability lies in the combination of permissive CORS and insufficient origin validation before executing SQL.

Additionally, if the Sails app serves both web and API clients, a wildcard CORS rule can blur the boundary between public and privileged operations. Endpoints that should be limited to authenticated internal consumers may accept cross-origin calls simply because the CORS configuration does not differentiate origins. This increases the risk of sensitive CockroachDB data being harvested through compromised browser contexts or malicious browser extensions.

Cockroachdb-Specific Remediation in Sails — concrete code fixes

Remediation focuses on tightening CORS configuration and ensuring that origin checks are enforced before any CockroachDB query runs. Use an allowlist approach in config/cors.js instead of a wildcard, and validate origins against a known set of domains.

// config/cors.js
module.exports.cors = {
  origin: ['https://app.example.com', 'https://admin.example.com'],
  credentials: true,
  exposedHeaders: ['X-Request-ID'],
  maxAge: 3600
};

In your controllers or policies, add an explicit origin verification step for endpoints that interact with CockroachDB. This prevents a misconfigured global CORS rule from affecting sensitive routes.

// api/policies/check-origin.js
module.exports = function checkOrigin(req, res, next) {
  const allowed = [
    'https://app.example.com',
    'https://admin.example.com'
  ];
  const origin = req.headers.origin;
  if (!origin || allowed.indexOf(origin) === -1) {
    return res.forbidden('CORS origin not allowed');
  }
  return next();
};

Apply the policy to relevant controllers in config/policies.js:

// config/policies.js
module.exports.policies = {
  UserController: {
    getUserProfile: ['check-origin', 'sessionAuth']
  },
  SettingsController: {
    updatePreference: ['check-origin', 'sessionAuth']
  }
};

On the CockroachDB side, ensure that connection pools are scoped with least-privilege credentials and that queries remain bound to the authenticated user context. Avoid constructing dynamic SQL that could be influenced by client-supplied values.

// api/services/CockroachService.js
const { Pool } = require('@cockroachdb/pg');

const pool = new Pool({
  connectionString: process.env.COCKROACH_URL,
  ssl: {
    rejectUnauthorized: true
  }
});

async function getUserById(client, userId) {
  const query = {
    text: 'SELECT id, email, role FROM users WHERE id = $1',
    values: [userId]
  };
  const result = await client.query(query);
  return result.rows[0];
}

module.exports = { pool, getUserById };

Combine this with route-specific checks that confirm the requesting user matches the requested user ID before executing the query. This layered approach reduces the impact of any residual CORS misconfiguration and ensures that CockroachDB access is tightly coupled with verified identity.

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

Does middleBrick detect CORS misconfigurations during scans?
Yes, middleBrick includes CORS checks in its 12 parallel security checks and reports overly permissive origins with remediation guidance.
Can the middleBrick CLI or GitHub Action enforce a maximum CORS origin list?
The middleBrick CLI can scan from terminal and the GitHub Action can fail builds if security scores drop below your threshold, but specific CORS policy enforcement must be implemented separately in your Sails configuration.