HIGH integer overflowadonisjsfirestore

Integer Overflow in Adonisjs with Firestore

Integer Overflow in Adonisjs with Firestore — how this specific combination creates or exposes the vulnerability

An integer overflow in an AdonisJS application that interacts with Google Cloud Firestore can occur when numeric values derived from user input, request parameters, or computed fields exceed the safe integer range supported by JavaScript (Number.MAX_SAFE_INTEGER = 2^53 - 1) before being used in Firestore operations. Because Firestore expects numeric values to be within safe integer bounds for operations such as increments, batch writes, and query filters, an overflow can cause unexpected behavior, including incorrect data storage, unauthorized data access, or write failures.

In AdonisJS, this often manifests when processing numeric identifiers, counters, or financial-like values without proper validation or conversion to BigInt. For example, if an endpoint accepts a query parameter like quantity or increment and directly applies it in a Firestore update using field increments, an excessively large value may wrap around to a negative number or zero. This can bypass business logic, such as inventory checks, and may enable privilege escalation or data inconsistency across related documents.

The risk is compounded when Firestore security rules rely on numeric comparisons without accounting for overflowed values. An attacker could supply a crafted number that, after wrapping, satisfies an access condition that should otherwise be denied. Because the scan includes checks for Input Validation and Property Authorization, middleBrick can detect mismatches between expected numeric constraints and runtime behavior when unsafe integer operations reach Firestore.

Real-world patterns include using Firestore FieldValue.increment() with user-controlled integers or constructing numeric arrays for batch operations without range checks. These patterns are common in AdonisJS controllers that manage counters, votes, or usage metrics. Without explicit validation and conversion to a safe representation (e.g., BigInt or server-side arithmetic), the application exposes an unauthenticated attack surface that middleBrick tests through active input validation probes and property authorization checks.

Firestore-Specific Remediation in Adonisjs — concrete code fixes

To prevent integer overflow when using Firestore in AdonisJS, validate and sanitize all numeric inputs before they are used in Firestore operations. Prefer server-side arithmetic for increments and avoid directly trusting client-supplied numbers. Use JavaScript BigInt for large integers and enforce strict ranges for values that affect security-sensitive operations.

Example 1: Safe increment with validation and BigInt

const { schema, rules } = use('@ioc:Adonis/Core/Validator')
const { Firestore } = require('@google-cloud/firestore')
const firestore = new Firestore()

const validationSchema = schema.create({
  incrementBy: schema.number([
    rules.unsigned(),
    rules.range({ max: 10000 })
  ])
})

async function safeIncrementProductQuantity(productId, payload) {
  const validated = await validator.validate({
    schema: validationSchema,
    data: payload
  })

  const docRef = firestore.collection('products').doc(productId)
  // Use server-side increment with a validated safe integer
  await docRef.update({
    quantity: firestore.FieldValue.increment(validated.incrementBy)
  })

  return docRef.get()
}

Example 2: BigInt usage for large counters with Firestore transaction

const { Firestore } = require('@google-cloud/firestore')
const firestore = new Firestore()

async function updateLargeCounterWithTransaction(docId, bigIntDelta) {
  const delta = BigInt(bigIntDelta)
  const docRef = firestore.collection('counters').doc(docId)

  await firestore.runTransaction(async (transaction) => {
    const snapshot = await transaction.get(docRef)
    if (!snapshot.exists) {
      throw new Error('Counter document does not exist')
    }
    const current = BigInt(snapshot.data().value)
    const next = current + delta

    // Enforce application-specific safe range
    if (next < 0n || next > BigInt(Number.MAX_SAFE_INTEGER)) {
      throw new Error('Counter out of safe range')
    }

    transaction.update(docRef, { value: Number(next) })
  })
}

// Usage: provide delta as a string to avoid client-side overflow
await updateLargeCounterWithTransaction('siteStats', '9007199254740991')

Example 3: Batch write with validated numeric arrays

const { Firestore } = require('@google-cloud/firestore')
const firestore = new Firestore()

async function safeBatchUpdate(items) {
  const batch = firestore.batch()
  const updates = []

  for (const item of items) {
    // Validate each numeric field
    if (typeof item.score !== 'number' || !Number.isFinite(item.score) || item.score < 0) {
      throw new Error('Invalid score value')
    }
    const docRef = firestore.collection('results').doc(item.id)
    batch.update(docRef, { score: item.score })
    updates.push(docRef)
  }

  await batch.commit()
  return updates
}

These examples emphasize server-side validation, bounded ranges, and safe numeric handling to mitigate overflow risks. middleBrick supports this remediation path by mapping findings to OWASP API Top 10 and compliance frameworks, and the Pro plan can enable continuous monitoring to catch regressions in numeric handling across API changes.

Frequently Asked Questions

How does middleBrick detect integer overflow risks involving Firestore in AdonisJS?
middleBrick runs parallel security checks including Input Validation and Property Authorization. It tests unauthenticated endpoints that use numeric inputs in Firestore operations (e.g., increments, filters) and flags cases where values can overflow or bypass authorization logic, providing severity and remediation guidance.
Can the Pro plan help prevent integer overflow issues in CI/CD for AdonisJS apps using Firestore?
Yes. With the Pro plan, you can enable continuous monitoring and integrate the GitHub Action to fail builds if a scan detects numeric handling issues or a security score drop, helping catch integer overflow risks before deployment.