Denial Of Service in Adonisjs with Basic Auth
Denial Of Service in Adonisjs with Basic Auth — how this specific combination creates or exposes the vulnerability
AdonisJS does not provide built-in protections against resource exhaustion when Basic Authentication is used without additional safeguards. Basic Authentication in AdonisJS is typically implemented by validating credentials on each request, for example within an authentication provider or an AuthMiddleware. If the authentication logic performs synchronous or expensive operations—such as repeated database queries, bcrypt comparisons, or file I/O—and is applied to every incoming request, an attacker can induce a Denial of Service (DoS) by sending a high volume of unauthenticated or invalid authentication requests.
The combination of Basic Auth and missing rate limiting or request throttling exposes the unauthenticated attack surface. An attacker does not need valid credentials; they simply need to send many requests with arbitrary Authorization: Basic dXNlcjpwYXNz headers. Each request triggers the authentication provider, which may resolve the user, verify the password hash, and potentially access application services. If these operations are not bounded or cached, CPU and memory usage increase, potentially saturating the event loop and raising the Authentication and Rate Limiting check findings in a middleBrick scan.
For example, an AdonisJS application that calls User.findBy('email', email) and then await password.verify(plainText, hashed) for every request will perform two I/O-bound steps per request. Under a high request rate, this pattern can lead to thread exhaustion (in the worker context), increased latency, and timeouts for legitimate users. The vulnerability is not in Basic Auth itself but in how authentication is implemented and protected. A middleBrick scan running the Rate Limiting and Authentication checks can surface these risks by observing elevated response times or error rates under simulated load.
Because the scan tests the unauthenticated attack surface, middleBrick can detect whether authentication endpoints are disproportionately expensive. Findings may reference patterns seen in OWASP API Top 10 DoS01: Denial of Service and can align with PCI-DSS availability controls when such exposure impacts payment interfaces. Remediation focuses on bounding computational work, applying per-client rate limits, and avoiding expensive operations in the hot path of request handling.
Basic Auth-Specific Remediation in Adonisjs — concrete code fixes
Secure remediation in AdonisJS centers on reducing the cost of authentication checks and preventing unbounded resource consumption. Use lightweight token validation for repeated requests, cache verification results, and enforce strict rate limits on authentication endpoints. Below are concrete patterns to implement these controls.
1. Basic Auth with cached token exchange
After validating Basic credentials once, issue a short-lived token (e.g., signed JWT) to avoid repeated expensive verification. This keeps the authentication handler lean and moves cost to connection setup rather than every request.
// start/hooks.ts or a custom provider
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import { DateTime } from 'luxon'
import jwt from 'jsonwebtoken'
export class AuthHook {
public async onRequest({ request, response }: HttpContextContract) {
const auth = request.headers().authorization
if (!auth || !auth.startsWith('Basic ')) return
const base64 = auth.split(' ')[1]
const [username, password] = Buffer.from(base64, 'base64').toString().split(':')
// Perform one expensive lookup and hash verification only during auth phase
const user = await User.findBy('email', username)
if (!user) {
response.unauthorized('Invalid credentials')
return
}
const isValid = await verifyPassword(password, user.passwordHash)
if (!isValid) {
response.unauthorized('Invalid credentials')
return
}
// Issue short-lived token to protect subsequent requests
const token = jwt.sign({ sub: user.id }, process.env.JWT_SECRET!, {
expiresIn: '15m',
})
response.setCookie('auth_token', token, {
httpOnly: true,
sameSite: 'strict',
secure: true,
})
}
}
2. Apply rate limiting on authentication routes
Use AdonisJS rate limiter to cap requests per IP on endpoints that perform Basic validation. This directly addresses the DoS surface by throttling attackers.
// start/routes.ts
import Route from '@ioc:Adonis/Core/Route'
import RateLimiter from '@ioc:Extra/RateLimiter'
Route.post('/login-basic', async ({ request, response }) => {
const { username, password } = request.only(['username', 'password'])
const user = await User.findBy('email', username)
if (!user) {
return response.unauthorized('Invalid credentials')
}
const isValid = await verifyPassword(password, user.passwordHash)
if (!isValid) {
return response.unauthorized('Invalid credentials')
}
// issue token as above
return response.ok({ token })
}).middleware([RateLimiter.make({ identifier: (ctx) => ctx.request.ip(), duration: 60, max: 10 })])
3. Lightweight validation for subsequent requests
For requests protected by the issued token, avoid re-running Basic validation. Validate the token signature and claims only, which is computationally cheap and reduces load.
// start/middleware/verify_jwt.ts
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import jwt from 'jsonwebtoken'
export default class VerifyJwt {
public async handle({ request, response, next }: HttpContextContract) {
const token = request.headers().authorization?.replace('Bearer ', '')
if (!token) {
return response.unauthorized('Unauthorized')
}
try {
const payload = jwt.verify(token, process.env.JWT_SECRET!) as { sub: number }
request.authUser = { id: payload.sub }
await next()
} catch {
response.unauthorized('Invalid token')
}
}
}
These changes reduce the per-request cost, bound CPU-intensive work, and lower the risk highlighted by findings in the Authentication and Rate Limiting checks. A middleBrick scan after applying these fixes should show improved scores in the Authentication category and better resilience against resource exhaustion.
Related CWEs: resourceConsumption
| CWE ID | Name | Severity |
|---|---|---|
| CWE-400 | Uncontrolled Resource Consumption | HIGH |
| CWE-770 | Allocation of Resources Without Limits | MEDIUM |
| CWE-799 | Improper Control of Interaction Frequency | MEDIUM |
| CWE-835 | Infinite Loop | HIGH |
| CWE-1050 | Excessive Platform Resource Consumption | MEDIUM |