HIGH integer overflowadonisjsjwt tokens

Integer Overflow in Adonisjs with Jwt Tokens

Integer Overflow in Adonisjs with Jwt Tokens

An integer overflow in an AdonisJS application that issues or validates JWT tokens can occur when numeric claims (such as exp, nbf, iat, or custom numeric payload fields) are handled with insufficient range checks. JavaScript numbers are IEEE-754 double-precision floating point values, which can safely represent integers only up to Number.MAX_SAFE_INTEGER (2^53 - 1). If a token payload includes a large integer—either supplied by an attacker or derived from untrusted input—and the application performs arithmetic or comparisons without validation, the integer can exceed this safe range, causing wraparound and unexpected behavior.

In the context of JWT tokens in AdonisJS, this often surfaces during token creation or verification when timestamps or numeric identifiers are used. For example, an attacker might supply a crafted exp value like 9999999999999999 (beyond safe integer limits). If AdonisJS code computes differences (e.g., time-to-expiry) or converts the value without range validation, the result may wrap to a small positive number or zero, causing the token to be considered valid far into the future or appearing not expired when it should be. This can lead to privilege escalation or bypass of expiration controls, intersecting with BOLA/IDOR and authentication checks that rely on token validity windows.

Consider an endpoint that accepts a JWT and uses a numeric userId claim to look up a user. If the server computes an offset using unchecked arithmetic (e.g., userId + offset) and the attacker provides a large userId, the computation may overflow and resolve to an unintended ID. The same risk applies when using numeric fields in JWTs for authorization decisions, such as tenant IDs or permissions masks, especially if the code later compares these values or uses them in loops or pagination. Because the scan testing is unauthenticated, an attacker can probe endpoints that accept JWTs with manipulated numeric claims and observe behavioral changes indicative of overflow, such as incorrect user mapping or unexpected access grants.

AdonisJS does not inherently protect against these overflows; developers must enforce safe integer ranges before using numeric values from JWT payloads. This aligns with broader API security checks such as Input Validation and Authentication, where malformed or extreme values are tested to ensure they do not alter intended logic. Real-world patterns mirror CVE-classic issues where integer overflows lead to authentication bypass or authorization flaws, emphasizing the need to validate and sanitize all numeric data originating from tokens.

Jwt Tokens-Specific Remediation in Adonisjs

Remediation focuses on validating and sanitizing numeric values extracted from JWT tokens before any arithmetic or authorization logic. Use explicit integer range checks and prefer BigInt for large or unbounded values. Ensure that standard JWT registered claims like exp, nbf, and iat are validated using library-provided checks rather than custom numeric comparisons.

Below are concrete code examples for AdonisJS that demonstrate safe handling of JWT tokens with numeric payload values.

import { base64urlDecode } from 'os' // helper for safe decoding
import jwt from 'jsonwebtoken'

// Example 1: Validate a numeric claim with range checks before use
function validateNumericClaim(value: number, max: number): boolean {
  return Number.isInteger(value) && value >= 0 && value <= Number.MAX_SAFE_INTEGER && value <= max
}

// Example 2: Parsing and verifying a JWT with numeric userId safely
function verifyToken(token: string, secret: string): { userId: number, exp: number } | null {
  try {
    const payload = jwt.verify(token, secret) as { userId?: unknown; exp?: unknown }
    // Explicit type guards for numeric claims
    if (typeof payload.userId !== 'number' || !Number.isInteger(payload.userId)) {
      return null
    }
    if (typeof payload.exp !== 'number' || !Number.isInteger(payload.exp)) {
      return null
    }
    if (!validateNumericClaim(payload.userId, 1000000)) {
      return null
    }
    return { userId: payload.userId, exp: payload.exp }
  } catch {
    return null
  }
}

// Example 3: Using BigInt for potentially large integers from custom claims
function processLargeTenantId(token: string, secret: string): bigint | null {
  try {
    const payload = jwt.verify(token, secret) as { tid?: unknown }
    const tidRaw = payload.tid
    let tid: bigint
    if (typeof tidRaw === 'string') {
      tid = BigInt(tidRaw)
    } else if (typeof tidRaw === 'number') {
      tid = BigInt(tidRaw)
    } else {
      return null
    }
    // Enforce business-specific bounds
    if (tid <= 0n || tid > 1000000n) {
      return null
    }
    return tid
  } catch {
    return null
  }
}

In these examples, verifyToken demonstrates strict type checks and range validation for numeric claims commonly found in JWTs within AdonisJS routes or middleware. processLargeTenantId shows how to handle potentially large integers using BigInt to avoid safe integer limits, with explicit bounds aligned to your tenant model. Always prefer using established JWT libraries for expiration and not-before checks, and avoid manually comparing timestamps when built-in verification is available.

Additionally, apply these practices in CI/CD and runtime environments: use the middlebrick CLI to scan tokens and endpoints for improper handling of numeric claims, and consider integrating the GitHub Action to fail builds when risky patterns are detected. The MCP Server can also be used while developing in your IDE to catch unsafe integer handling early. These steps reduce the risk of overflow-related authorization or authentication bypass in AdonisJS applications that rely on JWT tokens.

Frequently Asked Questions

How can I detect integer overflow risks in JWT tokens without running a full scan?
Review code paths that parse numeric claims from tokens and verify that all arithmetic uses safe integer checks or BigInt, and that libraries validate exp/nbf/iat. You can also use the middlebrick CLI to scan specific endpoints for unsafe numeric handling without enabling continuous monitoring.
Does input validation alone prevent integer overflow in JWT numeric claims?
Input validation helps but must include explicit integer range checks and type guards. Use runtime validation libraries and avoid implicit conversions; prefer BigInt for values that may exceed Number.MAX_SAFE_INTEGER, and let the JWT library handle standard registered claims like exp.