HIGH broken authenticationhapifirestore

Broken Authentication in Hapi with Firestore

Broken Authentication in Hapi with Firestore — how this specific combination creates or exposes the vulnerability

Broken Authentication in a Hapi application that uses Google Cloud Firestore often arises from misconfigured security rules and improper session or token handling. Hapi is a rich framework for building servers and APIs in Node.js, and it does not enforce authentication or authorization by default. When authentication logic is implemented at the application layer, Firestore security rules must complement that logic consistently. A common pattern is to use Firebase Admin SDK or a client-side SDK to read and write data after verifying a JWT or session cookie in Hapi routes. If these checks are incomplete, such as missing validation of token expiration, issuer, or audience, an attacker can supply a valid but stolen token and gain access to Firestore resources they should not see.

Firestore-specific risks emerge when security rules are either not enforced or are too permissive. For example, a rule like allow read, write: if request.auth != null; appears to require authentication, but if the Hapi endpoint does not strictly validate the token before attaching it to the Firestore client, an unauthenticated request may still reach Firestore if the client SDK is misconfigured or if the request bypasses Hapi entirely (for instance, by calling the Firestore REST API directly). Moreover, Firestore indexes and query behavior can unintentionally expose data if rules rely on client-supplied filters without server-side validation within Hapi routes. An attacker may manipulate query parameters to enumerate usernames or IDs, leading to user enumeration or IDOR-like behavior even when authentication appears intact.

Another vector specific to Hapi and Firestore is insecure direct object references facilitated by predictable document IDs. If Hapi generates or accepts identifiers such as user IDs or resource IDs via route parameters and passes them directly to Firestore without confirming ownership in server-side logic, an authenticated user can modify or access other users’ documents. This becomes critical when combined with weak session management in Hapi, such as missing secure flags on cookies, lack of HttpOnly settings, or insufficient token rotation. The interaction between Hapi’s routing and Firestore’s rule evaluation means that any gap in either layer can result in unauthorized data access or privilege escalation, making it essential to align application-level checks with robust, least-privilege Firestore rules and strict token validation in every route handler.

Firestore-Specific Remediation in Hapi — concrete code fixes

To remediate Broken Authentication when using Hapi with Firestore, enforce strict token validation in route handlers and align Firestore security rules with least-privilege principles. Below are concrete code examples for a Hapi server using the Firebase Admin SDK to verify ID tokens before allowing Firestore operations.

First, initialize the Admin SDK once in your application and use it in route pre-processing to validate the token:

// server.js
const Hapi = require('@hapi/hapi');
const { initializeApp, cert } = require('firebase-admin/app');
const { getAuth } = require('firebase-admin/auth');

initializeApp({
  credential: cert({
    projectId: process.env.FIREBASE_PROJECT_ID,
    clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
    privateKey: process.env.FIREBASE_PRIVATE_KEY.replace(/\\n/g, '\n'),
  }),
});

const validateFirebaseToken = async (request, h) => {
  const authHeader = request.headers.authorization;
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    throw Boom.unauthorized('Missing authentication token');
  }
  const idToken = authHeader.split('Bearer ')[1];
  try {
    const decodedToken = await getAuth().verifyIdToken(idToken);
    return { credentials: decodedToken };
  } catch (error) {
    throw Boom.unauthorized('Invalid token');
  }
};

const server = Hapi.server({ port: 3000, host: 'localhost' });
server.route({
  method: 'GET',
  path: '/users/{userId}',
  options: {
    auth: false,
    pre: [{ method: validateFirebaseToken, assign: 'user' }],
  },
  handler: async (request, h) => {
    const { userId } = request.params;
    const requestingUid = request.pre.user.uid;
    if (requestingUid !== userId) {
      throw Boom.forbidden('Access denied');
    }
    const { Firestore } = require('@google-cloud/firestore');
    const firestore = new Firestore();
    const doc = await firestore.collection('users').doc(userId).get();
    if (!doc.exists) {
      throw Boom.notFound('User not found');
    }
    return doc.data();
  },
});

server.start().catch(console.error);

This pattern ensures that every request to access a Firestore document is backed by a verified Firebase ID token and that the requesting user’s UID matches the document being requested, mitigating IDOR risks. For broader protection, define Firestore security rules that enforce ownership and least privilege:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
      allow read, write: if request.auth != null && request.auth.uid == userId;
    }
  }
}

Additionally, configure Hapi to use secure cookies for session tokens when managing web sessions, with isSecure and isHttpOnly flags, and rotate signing keys regularly. Combine these measures with rate limiting and input validation to reduce the attack surface. Using the middleBrick CLI, you can run middlebrick scan <url> to detect authentication misconfigurations, and with the Pro plan you can enable continuous monitoring to catch regressions early. The GitHub Action can enforce a minimum security score before allowing deployment, and the MCP Server lets you scan APIs directly from your AI coding assistant to validate rules and route handlers during development.

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 Firestore security rules interact with Hapi authentication checks?
Firestore rules run independently of your application code and must align with Hapi’s token validation. Even if Hapi validates a token, overly permissive Firestore rules can still expose data; likewise, strict rules can block legitimate requests if Hapi does not attach valid credentials. Always enforce verification in Hapi and keep rules scoped to the principle of least privilege.
Can middleBrick detect broken authentication issues in Hapi and Firestore setups?
Yes, middleBrick scans unauthenticated attack surfaces and can identify missing authentication enforcement, overly permissive rules, and common misconfigurations in integrations like Hapi and Firestore. Findings include severity, guidance, and mappings to frameworks such as OWASP API Top 10.