HIGH integer overflowexpresscockroachdb

Integer Overflow in Express with Cockroachdb

Integer Overflow in Express with Cockroachdb — how this specific combination creates or exposes the vulnerability

An integer overflow in an Express application that uses CockroachDB can occur when user-supplied numeric input is used to calculate sizes, limits, or offsets without proper bounds checking. In JavaScript, numbers are IEEE 754 double-precision floating-point values, which can safely represent integers up to 2^53 - 1 (Number.MAX_SAFE_INTEGER). Beyond this, integer precision is lost, and arithmetic can produce unexpected wraparound values. When such values are passed to CockroachDB, which enforces strict SQL integer types (e.g., INT, BIGINT), the application may construct queries with values that exceed the database column type range or cause logical boundary violations.

For example, an endpoint like /users/:id/invoices might compute an offset using offset = page * pageSize. If page or pageSize is controlled by the client and not validated, a large multiplication can overflow the safe integer range. The resulting value, when passed to a CockroachDB LIMIT or OFFSET clause, may produce incorrect pagination or, in combination with other logic, enable IDOR-like access to unintended rows. CockroachDB does not introduce the overflow; it executes the query as designed, but the corrupted numeric intent can bypass application-level authorization checks that rely on arithmetic assumptions.

Another scenario involves financial or quantity fields. An order endpoint that multiplies unitPrice * quantity and uses the result in a CockroachDB DECIMAL or NUMERIC insert may seem safe, but if intermediate JavaScript arithmetic overflows before the value reaches the database, the stored value can be incorrect or negative. This can violate business rules and data integrity expectations, and because CockroachDB adheres to strict type constraints, the application may not detect the anomaly until downstream logic consumes the bad data. The vulnerability is not in CockroachDB itself but in how Express computes and passes values to it, especially when authorization checks depend on numeric comparisons or derived identifiers.

In the context of the 12 security checks run by middleBrick, this class of issue maps to Input Validation and Property Authorization. Because the attack surface is unauthenticated, an attacker can probe endpoints with large numeric payloads to observe behavior changes, error messages, or data exposure. middleBrick’s scan would flag findings related to missing boundary checks and improper validation of numeric inputs that feed database operations, providing remediation guidance to enforce strict type, range, and format validation before values reach the database layer.

Cockroachdb-Specific Remediation in Express — concrete code fixes

Remediation focuses on validating and sanitizing all numeric inputs before they are used in arithmetic or passed to CockroachDB. Use explicit integer types in JavaScript (e.g., BigInt for arbitrary precision when necessary) and enforce range checks that align with CockroachDB column definitions. Below are concrete Express code examples with CockroachDB queries that demonstrate secure patterns.

Example 1: Safe pagination with bounds checking

const { Client } = require('pg');
const client = new Client({ connectionString: process.env.DATABASE_URL });

async function getInvoices(req, res) {
  const page = parseInt(req.query.page, 10) || 1;
  const pageSize = parseInt(req.query.pageSize, 10) || 10;

  // Validate ranges to prevent overflow and abuse
  if (!Number.isInteger(page) || page < 1 || page > 10000) {
    return res.status(400).json({ error: 'Invalid page' });
  }
  if (!Number.isInteger(pageSize) || pageSize < 1 || pageSize > 100) {
    return res.status(400).json({ error: 'Invalid page size' });
  }

  const offset = page * pageSize;
  // Use parameterized queries to CockroachDB
  const result = await client.query(
    'SELECT id, user_id, amount FROM invoices WHERE user_id = $1 ORDER BY id LIMIT $2 OFFSET $3',
    [req.user.id, pageSize, offset]
  );
  res.json(result.rows);
}

Example 2: Safe arithmetic for financial calculations

const { Client } = require('pg');
const client = new Client({ connectionString: process.env.DATABASE_URL });

async function createOrder(req, res) {
  const { unitPriceCents, quantity } = req.body;

  // Validate integer inputs and business limits
  if (!Number.isInteger(unitPriceCents) || unitPriceCents <= 0 || unitPriceCents > 100000000) {
    return res.status(400).json({ error: 'Invalid unit price' });
  }
  if (!Number.isInteger(quantity) || quantity <= 0 || quantity > 1000) {
    return res.status(400).json({ error: 'Invalid quantity' });
  }

  // Perform arithmetic in JavaScript with safe checks
  const totalCents = unitPriceCents * quantity;
  if (!Number.isSafeInteger(totalCents) || totalCents > 9007199254740991) {
    return res.status(400).json({ error: 'Order total overflow risk' });
  }

  // Insert into CockroachDB using DECIMAL for precision
  const result = await client.query(
    'INSERT INTO orders (user_id, unit_price_cents, quantity, total_cents) VALUES ($1, $2, $3, $4) RETURNING id',
    [req.user.id, unitPriceCents, quantity, totalCents]
  );
  res.status(201).json({ orderId: result.rows[0].id });
}

Example 3: Using BigInt for large IDs or counters

const { Client } = require('pg');
const client = new Client({ connectionString: process.env.DATABASE_URL });

async function updateCounter(req, res) {
  // Assume a high-volume counter stored as BIGINT in CockroachDB
  const increment = BigInt(req.body.increment || 1);
  const maxSafe = BigInt('9007199254740991'); // JS Number.MAX_SAFE_INTEGER

  if (increment <= 0n || increment > maxSafe) {
    return res.status(400).json({ error: 'Invalid increment' });
  }

  const result = await client.query(
    'UPDATE counters SET value = value + $1 WHERE id = $2 RETURNING value',
    [increment, 'global_seq']
  );
  res.json({ value: result.rows[0].value.toString() });
}

These examples emphasize input validation, use of safe integer checks, and proper parameterization. By constraining numeric ranges and using types that avoid silent overflow, Express applications can safely interact with CockroachDB without introducing arithmetic vulnerabilities that could lead to data corruption or unauthorized access.

Frequently Asked Questions

Why does integer overflow matter when Express sends data to CockroachDB?
Integer overflow in Express can produce corrupted numeric values that are passed to CockroachDB. Even though CockroachDB enforces SQL integer types, it executes queries based on application-supplied values; overflow can bypass authorization checks, cause incorrect pagination, or store invalid financial data.
How does middleBrick detect integer overflow risks in Express APIs using CockroachDB?
middleBrick runs unauthenticated checks focused on Input Validation and Property Authorization. It tests endpoints with large numeric payloads to identify missing bounds checks and validates that numeric inputs are sanitized before being used in database queries, surfacing findings with remediation guidance.