Regex Dos in Fiber with Api Keys
Regex Dos in Fiber with Api Keys — how this specific combination creates or exposes the vulnerability
A Regular Expression Denial of Service (Regex DoS) occurs when an attacker provides input that causes a poorly designed regular expression to exhibit catastrophic backtracking, consuming excessive CPU time. In Fiber, this risk is amplified when API keys are handled as path or query parameters and processed by complex or unanchored patterns. For example, if a route uses a middleware or handler that validates an API key with a loose regex (e.g., .*api_key=.*) and the key contains repeating substrings, the regex engine may enter exponential time complexity as it tries and backtracks through many possible matches.
Consider a Fiber route that extracts an API key from a query string and validates it with a non-anchored pattern:
const app = new fiber();
app.get('/resource', (c) => {
const apiKey = c.query('key');
const pattern = /^([A-Za-z0-9_-]+|)*$/; // Dangerous: nested quantifiers
if (!pattern.test(apiKey)) {
return c.status(401).send('Invalid key');
}
return c.send('OK');
});
In this example, the regex contains nested quantifiers (|)*, which can cause catastrophic backtracking on crafted input like key=aaaaaaaaaaaaaaaaaaaa!. Because API keys are often long, alphanumeric strings, an attacker can send a specially designed key that triggers this pathological behavior, leading to high CPU usage and potential service disruption. Even when validation is moved to a middleware layer, the same vulnerability persists if the regex is not carefully constrained.
The interaction with unauthenticated scan capabilities is relevant: middleBrick tests input validation and Regex patterns as part of its 12 security checks. It does not rely on internal architecture but observes runtime behavior and spec definitions to detect patterns that could lead to ReDoS. When OpenAPI/Swagger specs define query parameters as strings without explicit pattern constraints or with overly permissive formats, this can indicate a surface where Regex DoS with API keys may exist. The scanner correlates spec-defined parameter formats with runtime tests to highlight findings related to Input Validation and Property Authorization, mapping them to OWASP API Top 10 and other compliance frameworks.
In practice, any endpoint that accepts API keys in the request path or query parameters and validates them with complex or unanchored regular expressions should be reviewed. The risk is not theoretical; there are real-world CVEs involving ReDoS in parsers that use similar patterns. Because middleBrick performs black-box scanning and analyzes OpenAPI specs with full $ref resolution, it can identify such risky patterns without requiring credentials, providing prioritized findings with severity and remediation guidance to help teams address the issue before it is weaponized.
Api Keys-Specific Remediation in Fiber — concrete code fixes
To mitigate Regex DoS when handling API keys in Fiber, avoid nested quantifiers and ensure regex patterns are anchored and non-backtracking. Use simple character class checks or, when possible, replace regex validation with constant-time string operations. Below are concrete, safe examples for validating API keys in Fiber routes.
Instead of a complex regex, validate API keys by length and allowed characters using a straightforward approach:
const app = new Fiber();
// Safe: simple alphanumeric and underscore check without nested quantifiers
app.get('/resource', (c) => {
const apiKey = c.query('key');
if (!apiKey || apiKey.length < 32 || apiKey.length > 128) {
return c.status(400).send('Invalid key length');
}
const allowed = /^[A-Za-z0-9_-]+$/;
if (!allowed.test(apiKey)) {
return c.status(401).send('Invalid key format');
}
return c.send('OK');
});
For higher assurance, compare the provided key against a stored set of valid keys using a constant-time comparison to avoid timing attacks. This removes regex entirely from the critical path:
const validKeys = new Set([
'abc123_456-def789-ghi012',
'xyz789_012-uvw345-rst678'
]);
app.get('/secure', (c) => {
const apiKey = c.query('key');
if (!apiKey) {
return c.status(401).send('Missing key');
}
if (validKeys.has(apiKey)) {
return c.send('Authorized');
}
return c.status(401).send('Invalid key');
});
If you must use regex, anchor it and avoid repetition or nested groups. For example, to validate a specific key format, use a non-repeating pattern:
const apiKeyPattern = /^[A-Za-z0-9_-]{32,64}$/;
app.get('/v1/data', (c) => {
const apiKey = c.query('token');
if (!apiKey || !apiKeyPattern.test(apiKey)) {
return c.status(401).send('Invalid key');
}
return c.send('OK');
});
Additionally, consider rate limiting and monitoring for repeated invalid key attempts as part of your overall security posture. middleBrick’s Pro plan supports continuous monitoring and GitHub Action integration, which can help detect abnormal request patterns tied to API key abuse. Its scans can highlight endpoints with risky regex patterns in the OpenAPI spec, giving you actionable remediation guidance tied to compliance frameworks. The MCP Server allows you to run these checks directly from development environments, integrating API security into your workflow without requiring agents or credentials.
Related CWEs: inputValidation
| CWE ID | Name | Severity |
|---|---|---|
| CWE-20 | Improper Input Validation | HIGH |
| CWE-22 | Path Traversal | HIGH |
| CWE-74 | Injection | CRITICAL |
| CWE-77 | Command Injection | CRITICAL |
| CWE-78 | OS Command Injection | CRITICAL |
| CWE-79 | Cross-site Scripting (XSS) | HIGH |
| CWE-89 | SQL Injection | CRITICAL |
| CWE-90 | LDAP Injection | HIGH |
| CWE-91 | XML Injection | HIGH |
| CWE-94 | Code Injection | CRITICAL |