HIGH broken access controlhapicockroachdb

Broken Access Control in Hapi with Cockroachdb

Broken Access Control in Hapi with Cockroachdb — how this specific combination creates or exposes the vulnerability

Broken Access Control (BOLA/IDOR) occurs when an API exposes functionality that allows attackers to bypass authorization and access or modify resources that should be restricted. Using Hapi with CockroachDB can inadvertently expose this risk when route handlers construct database queries using user-supplied identifiers without verifying that the authenticated subject has the right to access those records.

Hapi provides request pre-processing hooks and route parameter extraction, but it does not enforce object-level permissions by default. If a developer writes a route like /users/{userId}/profile and directly uses userId to query CockroachDB without confirming that the requesting user owns or is allowed to view that ID, an attacker can change the parameter to access another user’s data. CockroachDB, as a distributed SQL database, does not enforce application-level permissions; it only enforces SQL-level privileges. Therefore, if the application uses a single database role with broad read/write rights, compromised authorization logic in Hapi can lead to mass data exposure.

Additionally, when APIs expose list-like endpoints such as /api/teams/{teamId}/members, missing ownership checks can allow enumeration across teams. An attacker can iterate over valid team IDs harvested from other sources and read membership data they should not see. This becomes more impactful if the CockroachDB schema stores sensitive fields (e.g., roles, permissions, or PII) without encryption at the column level and the application relies solely on query logic for access control.

OpenAPI/Swagger analysis can highlight these risks by showing that a path parameter like userId is used in a way that is not constrained by security schemes or scope checks. When combined with unauthenticated or weakly authenticated endpoints, this increases the attack surface. The 12 security checks running in parallel on middleBrick include BOLA/IDOR and will flag routes where identifiers are directly passed to the database without contextual authorization, providing prioritized findings with severity and remediation guidance.

Cockroachdb-Specific Remediation in Hapi — concrete code fixes

Remediation centers on enforcing ownership or role checks before executing SQL against CockroachDB. Always treat client-supplied identifiers as untrusted and validate them against the requesting user’s context. Below are concrete, working Hapi and CockroachDB examples that implement proper access control.

1. Parameterized query with ownership verification

Ensure that every query includes a tenant or user ownership filter. Use placeholders to avoid SQL injection and enforce that the subject owning the resource matches the authenticated subject.

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

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

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

  server.route({
    method: 'GET',
    path: '/users/{userId}/profile',
    options: {
      auth: 'session-auth',
      handler: async (request) => {
        const { userId } = request.params;
        const authenticatedUserId = request.auth.credentials.userId; // from session strategy

        if (userId !== authenticatedUserId) {
          throw Boom.forbidden('You cannot access this profile');
        }

        const query = 'SELECT id, email, display_name FROM users WHERE id = $1 AND tenant_id = $2';
        const values = [userId, request.auth.credentials.tenantId];
        const { rows } = await pool.query(query, values);

        if (rows.length === 0) {
          throw Boom.notFound('User not found');
        }
        return rows[0];
      },
    },
  });

  await server.register(require('@hapi/inert'));
  await server.start();
};

init().catch(console.error);

2. Team membership check before returning members

For endpoints that expose related resources, validate membership using an explicit join rather than trusting the caller’s ID.

server.route({
  method: 'GET',
  path: '/api/teams/{teamId}/members',
  options: {
    auth: 'session-auth',
    handler: async (request) => {
      const { teamId } = request.params;
      const userId = request.auth.credentials.userId;

      const membershipQuery = `
        SELECT m.user_id, m.role, u.email
        FROM team_members m
        JOIN users u ON m.user_id = u.id
        WHERE m.team_id = $1 AND m.user_id = $2
      `;
      const membership = await pool.query(membershipQuery, [teamId, userId]);

      if (membership.rows.length === 0) {
        throw Boom.forbidden('You are not a member of this team');
      }

      const listQuery = `
        SELECT u.id, u.email, tm.role
        FROM team_members tm
        JOIN users u ON tm.user_id = u.id
        WHERE tm.team_id = $1
      `;
      const { rows } = await pool.query(listQuery, [teamId]);
      return rows;
    },
  },
});

3. Use CockroachDB role-based access and row-level security where applicable

While application-level checks are mandatory, you can complement them with CockroachDB roles and policies. For example, create limited-privilege roles per service and use tenant-aware queries to prevent cross-tenant reads.

-- Example SQL setup (run separately via a migration tool)
CREATE TABLE users (
  id UUID PRIMARY KEY,
  tenant_id UUID NOT NULL,
  email TEXT NOT NULL,
  display_name TEXT
);

-- Application connects using a role with SELECT on users restricted by tenant_id
GRANT SELECT ON users TO api_reader;

middleBrick’s scans include BOLA/IDOR checks that map findings to frameworks such as OWASP API Top 10 and can highlight missing authorization logic in Hapi routes backed by CockroachDB. The Pro plan adds continuous monitoring so that regressions in access control are caught early in CI/CD pipelines.

Frequently Asked Questions

How does middleBrick detect broken access control in Hapi endpoints backed by CockroachDB?
middleBrick runs unauthenticated and authenticated scenario tests, sending modified identifiers in requests and checking whether the API enforces ownership or role-based constraints before querying CockroachDB. It flags endpoints where parameters are used directly in SQL without contextual authorization.
Can I rely on CockroachDB roles alone to prevent broken access control in my Hapi API?
No. Database roles enforce SQL-level permissions but do not replace application-level checks. You must validate ownership or scope in Hapi handlers; otherwise, any authenticated user with valid SQL credentials could exploit overly permissive routes.