HIGH missing authenticationfeathersjscockroachdb

Missing Authentication in Feathersjs with Cockroachdb

Missing Authentication in Feathersjs with Cockroachdb — how this specific combination creates or exposes the vulnerability

FeathersJS is a framework for creating JavaScript APIs with a service-oriented architecture. When a FeathersJS service is configured without authentication middleware and connects to a CockroachDB backend, unauthenticated requests directly reach the data layer. CockroachDB, while robust for distributed SQL workloads, does not enforce application-level authentication; it only validates SQL credentials. If the FeathersJS service uses a shared database user or connects with elevated privileges, an unauthenticated API consumer can invoke service methods (e.g., find, get, create, update) that translate to unguarded SQL queries or mutations.

This combination exposes the unauthenticated attack surface: the API endpoint accepts requests without requiring tokens, keys, or session checks, and the CockroachDB connection string (often configured in environment variables) remains static. middleBrick’s Authentication check detects this by sending unauthenticated requests and analyzing responses for data exposure or unauthorized behavior. Findings may include bypassing intended access controls, viewing other users’ data via IDOR patterns, or triggering mutations without identity verification. Because FeathersJS services often expose CRUD operations directly, an unauthenticated probe can return sensitive records or allow creation of arbitrary entries if input validation is weak.

OpenAPI/Swagger definitions help correlate the runtime behavior: if paths lack security schemes and the service uses $ref’d models that map to CockroachDB tables, the scanner highlights missing authentication alongside schema definitions. middleBrick’s LLM/AI Security checks are not designed to assess this category, but the standard authentication tests identify whether endpoints require credentials and whether tokens are validated before database operations proceed.

Remediation guidance centers on enforcing authentication in FeathersJS before data operations. This does not imply database-side blocking, which is outside the scanner’s scope, but rather ensuring the framework layer rejects unauthenticated calls. Developers should integrate authentication hooks, verify tokens, and apply role-based constraints so that CockroachDB connections execute only after identity is confirmed.

Cockroachdb-Specific Remediation in Feathersjs — concrete code fixes

Secure remediation involves adding authentication hooks in FeathersJS and ensuring database interactions respect verified identities. Below are concrete code examples for a FeathersJS service using an ORM/ODM (e.g., Sequelize or TypeORM) connected to CockroachDB.

1. Enforce authentication via a before hook

Use a before hook to verify an authenticated context for all operations. This example uses JWT verification via @feathersjs/authentication-jwt.

// src/services/records/records.hooks.js
const authentication = require('@feathersjs/authentication-hooks');

module.exports = {
  before: {
    all: [
      authentication.hooks.authenticate('jwt'),
      async context => {
        // Ensure the user exists in CockroachDB and is authorized for this operation
        const { user } = context;
        if (!user || !user.id) {
          throw new Error('Unauthenticated');
        }
        // Optionally attach user metadata for downstream service logic
        context.params.user = user;
        return context;
      }
    ],
    find: [],
    get: [],
    create: [],
    update: [],
    patch: [],
    remove: []
  }
};

2. Apply role-based access control (RBAC) in hooks

After authentication, enforce permissions so users can only access their own data or permitted scopes. This example adds a custom hook to validate ownership against CockroachDB records.

// src/services/records/records.hooks.js (continued)
const { iff, isProvider } = require('feathers-hooks-common');

module.exports = {
  before: {
    all: [ /* previous hooks */ ],
    find: [
      async context => {
        const { user, params } = context;
        // Example: restrict tenant-scoped queries in CockroachDB
        if (user && user.tenantId) {
          params.query = {
            ...params.query,
            tenantId: user.tenantId
          };
        } else {
          throw new Error('Forbidden: tenant context missing');
        }
        return context;
      }
    ],
    get: [
      async context => {
        const { user, params, app } = context;
        const recordId = params.id;
        // Fetch the record from CockroachDB to verify ownership
        const record = await app.service('records').Model.findOne({
          where: { id: recordId, tenantId: user.tenantId }
        });
        if (!record) {
          throw new Error('Not found or unauthorized');
        }
        return context;
      }
    ]
  }
};

3. Secure database connection configuration

Ensure the CockroachDB connection uses least-privilege credentials and that connection strings are injected securely (e.g., via environment variables). In production, avoid shared users for API services.

// src/app.js
const feathers = require('@feathersjs/feathers');
const configuration = require('@feathersjs/configuration');
const { Sequelize } = require('sequelize');

const app = feathers();
app.configure(configuration());

const sequelize = new Sequelize({
  dialect: 'cockroachdb',
  host: process.env.CRDB_HOST,
  port: process.env.CRDB_PORT,
  database: process.env.CRDB_DATABASE,
  username: process.env.CRDB_USER,
  password: process.env.CRDB_PASSWORD,
  // Ensure SSL is enabled in production
  ssl: process.env.NODE_ENV === 'production' ? {
    require: true,
    rejectUnauthorized: false
  } : false
});

// Example service model binding
const Records = sequelize.define('records', {
  id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true },
  tenantId: { type: Sequelize.INTEGER, allowNull: false },
  data: { type: Sequelize.JSON }
});

app.use('/records', require('./records.service')({
  Model: Records,
  paginate: { default: 10, max: 50 }
}));

4. Validate and sanitize inputs to prevent abuse

Even with authentication, ensure inputs are validated to prevent injection and over-fetching. Use hooks to sanitize queries and parameters before they reach CockroachDB.

// src/services/records/records.hooks.js
const { sanitizeQuery } = require('feathers-commons');

module.exports = {
  before: {
    find: [
      async context => {
        // Limit which fields can be selected and enforce pagination
        if (context.params.query) {
          sanitizeQuery(context.params.query, ['id', 'tenantId', 'data']);
          context.params.query = {
            ...context.params.query,
            limit: Math.min(context.params.query.limit || 10, 50)
          };
        }
        return context;
      }
    ]
  }
};

These steps align with OWASP API Security Top 10 controls, particularly Broken Object Level Authorization (BOLA) and Broken Authentication. middleBrick’s scans can validate whether the hooks are correctly applied in runtime by checking for authentication requirements and tenant-aware query constraints.

Related CWEs: authentication

CWE IDNameSeverity
CWE-287Improper Authentication CRITICAL
CWE-306Missing Authentication for Critical Function CRITICAL
CWE-307Brute Force HIGH
CWE-308Single-Factor Authentication MEDIUM
CWE-309Use of Password System for Primary Authentication MEDIUM
CWE-347Improper Verification of Cryptographic Signature HIGH
CWE-384Session Fixation HIGH
CWE-521Weak Password Requirements MEDIUM
CWE-613Insufficient Session Expiration MEDIUM
CWE-640Weak Password Recovery HIGH

Frequently Asked Questions

How does middleBrick detect missing authentication in a FeathersJS service connected to CockroachDB?
middleBrick sends unauthenticated requests to the API endpoints and examines whether responses expose data or functionality that should require credentials. It checks for missing security schemes in the OpenAPI spec and validates that runtime responses do not return sensitive records without authentication.
Can middleBrick fix missing authentication issues in FeathersJS with CockroachDB?
middleBrick detects and reports missing authentication with severity, findings, and remediation guidance. It does not automatically apply fixes; developers must implement authentication hooks, enforce RBAC, and secure database connections as shown in the remediation examples.