HIGH regex dosadonisjsbasic auth

Regex Dos in Adonisjs with Basic Auth

Regex Dos in Adonisjs with Basic Auth — how this specific combination creates or exposes the vulnerability

AdonisJS applications that use HTTP Basic Authentication can be vulnerable to Regular Expression Denial-of-Service (Regex DoS) when route or validation logic uses poorly crafted regular expressions. In this context, the combination of Basic Auth and regex-heavy processing creates conditions where an attacker can send specially crafted inputs that cause catastrophic backtracking in the pattern matcher.

Basic Auth in AdonisJS is typically implemented by parsing the Authorization header, decoding the Base64 credential, and validating the username and password. If the validation logic or subsequent route constraints rely on JavaScript regular expressions—especially those with nested quantifiers or ambiguous groupings—malformed credentials can trigger exponential time complexity. For example, a regex used to validate a username format like /^(a+)+$/ becomes dangerous when an attacker provides a long string of a characters followed by a non-matching character, causing the regex engine to explore an exponentially large number of paths before failing.

In a real-world scenario, an AdonisJS route might enforce credential constraints with a pattern such as /^[a-zA-Z0-9._-]{1,16}$/. While this pattern is generally safe, adjacent routes or middleware that handle authentication tokens or API keys might use more complex patterns that are vulnerable. An attacker can probe the API with long, repetitive strings in the username or password fields, consuming significant CPU time and leading to service degradation or unresponsiveness without requiring authentication success.

Because middleBrick scans the unauthenticated attack surface, it can detect endpoints that accept Basic Auth headers and flag regex patterns present in request validation logic. The scanner identifies risky expressions by correlating runtime behavior with known vulnerable patterns such as nested quantifiers, ambiguous alternations, and overly broad character classes in constrained repetition. These findings appear in the security report with severity ratings and remediation guidance, helping developers understand where regex usage intersects with authentication flows.

Key OWASP API Top 10 categories relevant to this issue include API1:2023 – Broken Object Level Authorization when regex checks are bypassed through malformed inputs, and API2:2023 – Broken Authentication when authentication logic is impacted by inefficient pattern matching. The presence of Basic Auth headers does not inherently introduce regex DoS, but it expands the attack surface by ensuring that credential validation paths are exercised for every request.

Basic Auth-Specific Remediation in Adonisjs — concrete code fixes

To mitigate Regex DoS in AdonisJS with Basic Auth, focus on simplifying validation patterns, avoiding nested quantifiers, and enforcing strict input length limits. The following examples demonstrate secure approaches for handling Basic Auth credentials.

Insecure pattern example (vulnerable):

// Risky: nested quantifiers can cause catastrophic backtracking
const usernameRegex = /^(a+)+$/;
const isValid = usernameRegex.test(username);

Secure remediation example 1 — simplified character validation:

// Safe: linear character class with bounded length
const usernameRegex = /^[a-zA-Z0-9._-]{1,16}$/;
const isValid = usernameRegex.test(username);
if (!isValid) {
  throw new Error('Invalid username format');
}

Secure remediation example 2 — explicit length and allowed characters without nesting:

// Safe: no nested quantifiers, clear length boundaries
const safeRegex = /^[A-Za-z0-9]{4,20}$/;
if (!safeRegex.test(credential)) {
  throw new Error('Invalid credential format');
}

AdonisJS route handling with Basic Auth header parsing (secure):

import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'

export default class AuthController {
  public async login({ request, response }: HttpContextContract) {
    const authHeader = request.headers().authorization
    if (!authHeader || !authHeader.startsWith('Basic ')) {
      return response.unauthorized()
    }

    const base64 = authHeader.split(' ')[1]
    const decoded = Buffer.from(base64, 'base64').toString('utf-8')
    const [username, password] = decoded.split(':')

    // Validate using a safe, non-backtracking pattern
    const userRegex = /^[A-Za-z0-9._-]{1,16}$/
    const passRegex = /^[A-Za-z0-9!@#$%^&*]{8,64}$/

    if (!userRegex.test(username) || !passRegex.test(password)) {
      return response.badRequest({ error: 'Invalid credentials format' })
    }

    // Proceed with authentication logic
    return response.ok({ authenticated: true })
  }
}

Additional recommendations:

  • Avoid regex for simple length or character set checks; use string methods like length and charCodeAt where possible.
  • Set explicit timeouts for request processing at the infrastructure level to interrupt long-running regex evaluations.
  • Use middleBrick’s CLI to scan your codebase and detect risky patterns: middlebrick scan <url> for unauthenticated surface checks or integrate via the GitHub Action to fail builds on risky regex findings.
  • For continuous assurance, enable the Pro plan’s continuous monitoring to track changes in regex usage and receive alerts when new risky patterns are introduced.

Related CWEs: inputValidation

CWE IDNameSeverity
CWE-20Improper Input Validation HIGH
CWE-22Path Traversal HIGH
CWE-74Injection CRITICAL
CWE-77Command Injection CRITICAL
CWE-78OS Command Injection CRITICAL
CWE-79Cross-site Scripting (XSS) HIGH
CWE-89SQL Injection CRITICAL
CWE-90LDAP Injection HIGH
CWE-91XML Injection HIGH
CWE-94Code Injection CRITICAL

Frequently Asked Questions

Can middleBrick detect Regex DoS risks in Basic Auth flows?
Yes. middleBrick scans unauthenticated endpoints and flags risky regular expressions in validation logic, including patterns used in Basic Auth handling. Findings include severity, affected endpoints, and remediation guidance.
Does fixing regex patterns alone fully secure Basic Auth in AdonisJS?
No. Regex remediation reduces DoS risk, but you must also enforce transport encryption, protect credentials in storage, implement rate limiting, and validate input length and character sets to achieve a robust authentication posture.