Hallucination Attacks in Adonisjs with Jwt Tokens
Hallucination Attacks in Adonisjs with Jwt Tokens — how this specific combination creates or exposes the vulnerability
A hallucination attack in the context of AdonisJS with JWT tokens occurs when an attacker manipulates the authentication or authorization flow such that the application produces or accepts incorrect claims, leading to unauthorized access or logic bypass. This typically arises when JWT validation is incomplete or when tokens are accepted without strict verification of issuer, audience, expiration, or signature. In AdonisJS, if the application relies on loosely configured JWT middleware or uses default secret/key handling, an attacker may supply a malformed or unsigned token that the framework incorrectly trusts, causing it to hallucinate an authenticated identity.
For example, an attacker might intercept a valid JWT, modify its payload to escalate privileges (e.g., changing role from user to admin), and present it to an AdonisJS endpoint that does not enforce strict signature validation or audience checks. Because AdonisJS can be configured to use symmetric or asymmetric keys, if the server accepts tokens signed with a public key but does not validate the key ID (kid) or properly resolve the correct public key, an attacker could supply a token signed with a different key, causing the server to hallucinate a valid identity based on an untrusted payload.
Another scenario involves token expiration manipulation. If AdonisJS does not enforce strict time-based validation (e.g., relying solely on the exp claim without clock-skew tolerance checks), an attacker might reuse an expired token and the framework might treat it as valid, hallucinating an authenticated session. This vulnerability is compounded when the application uses per-request token generation without proper nonce or session binding, allowing an attacker to inject crafted claims that the server hallucinates as legitimate.
These hallucination risks are particularly acute when JWTs are used across multiple services or when AdonisJS acts as a resource server without validating the original authorization server’s metadata. Without proper introspection or JWKS validation, the framework may accept tokens that appear valid but contain forged or hallucinated claims, leading to unauthorized data access or actions.
Jwt Tokens-Specific Remediation in Adonisjs — concrete code fixes
Remediation centers on strict JWT validation and avoiding assumptions about token integrity. In AdonisJS, configure the JWT provider to enforce signature verification, audience, and issuer checks. Use the official @adonisjs/auth package with explicit configuration rather than relying on defaults.
First, ensure your start/hash.ts or relevant provider configuration specifies a strong, environment-specific secret and algorithm:
import { Hash } from '@ioc:Adonis/Core/Hash'
export const jwt = {
secret: process.env.JWT_SECRET,
algorithm: 'HS256',
expiresIn: '2h',
}
Second, when verifying tokens manually (e.g., in a custom provider or middleware), use the JWT service to validate claims explicitly:
import { Jwt } from '@ioc:Adonis/Addons/Jwt'
export async function verifyToken(token: string) {
try {
const payload = await Jwt.verify(token, {
secret: process.env.JWT_SECRET,
algorithms: ['HS256'],
audience: 'my-api.example.com',
issuer: 'auth.example.com',
})
return payload
} catch (error) {
// Handle invalid token
throw new Error('Invalid token')
}
}
Third, if using asymmetric keys (e.g., RS256), load the correct public key and validate the kid header to prevent key confusion attacks:
import { Jwt } from '@ioc:Adonis/Addons/Jwt'
import fs from 'fs'
const publicKey = fs.readFileSync('path/to/public.key')
export async function verifyTokenWithKid(token: string) {
const decoded = Jwt.decode(token)
const kid = decoded.header.kid
// Resolve key based on kid, e.g., from a JWKS endpoint or local store
const resolvedKey = getKeyForKid(kid)
const payload = await Jwt.verify(token, {
publicKey: resolvedKey,
algorithms: ['RS256'],
audience: 'my-api.example.com',
issuer: 'auth.example.com',
})
return payload
}
Finally, integrate these checks into AdonisJS middleware to reject malformed or hallucinated tokens early:
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import { Jwt } from '@ioc:Adonis/Addons/Jwt'
export default class JwtAuthMiddleware {
public async handle({ request, response, auth }: HttpContextContract, next: () => Promise) {
const token = request.headers().authorization?.replace('Bearer ', '')
if (!token) {
return response.unauthorized('Missing token')
}
try {
const payload = await Jwt.verify(token, {
secret: process.env.JWT_SECRET,
audience: 'my-api.example.com',
issuer: 'auth.example.com',
})
request.authUser = payload
await next()
} catch {
return response.forbidden('Invalid token')
}
}
}
Related CWEs: llmSecurity
| CWE ID | Name | Severity |
|---|---|---|
| CWE-754 | Improper Check for Unusual or Exceptional Conditions | MEDIUM |