Jwt Misconfiguration in Adonisjs with Cockroachdb
Jwt Misconfiguration in Adonisjs with Cockroachdb — how this specific combination creates or exposes the vulnerability
When AdonisJS applications use JSON Web Tokens (JWT) for authentication and rely on CockroachDB as the backing data store, specific configuration and usage patterns can expose authentication bypass or token validation weaknesses. JWT misconfiguration in this stack often arises from insecure token settings, missing validation steps, or improper handling of token claims, and these issues can be amplified by how session state or user records are stored in CockroachDB.
For example, if an AdonisJS app uses the @adonisjs/auth package with JWT provider and stores user sessions or token metadata in CockroachDB, developers might inadvertently disable critical token checks or accept unsigned tokens during local development and forget to revert them for production. A common mistake is setting allowInsecureRequest to true in production or failing to enforce HTTPS-only cookie flags when tokens are stored in cookies, which can lead to token interception over unencrypted channels.
Another vulnerability pattern involves clock skew and token expiration. CockroachDB’s distributed SQL nature provides strong consistency guarantees, but if token revocation checks rely on database timestamps without accounting for time synchronization across nodes, an attacker could reuse a token that should have been invalidated. Additionally, if the JWT secret is stored in environment variables that are not properly managed or if weak secrets are used, attackers can forge tokens and authenticate as any user, including administrative accounts.
Middleware misconfiguration is also prevalent. AdonisJS middleware that verifies JWTs may incorrectly skip verification for certain routes or rely on incomplete payload validation, such as not checking the iss (issuer), aud (audience), or nbf (not before) claims. When combined with CockroachDB’s role-based access controls that might be bypassed due to application-level logic flaws, this can lead to privilege escalation or unauthorized data access.
Real-world attack patterns like token replay or injection become more feasible when API endpoints do not validate token scope or when logging mechanisms inadvertently expose tokens stored in CockroachDB diagnostic tables. Without proper input validation and strict token validation logic, an attacker who obtains a token can escalate privileges or move laterally within the system, especially if token blacklisting or revocation lists are not properly maintained in the database.
Cockroachdb-Specific Remediation in Adonisjs — concrete code fixes
To mitigate JWT misconfiguration risks in AdonisJS with CockroachDB, implement strict token validation, secure secret management, and robust database interactions. Below are concrete code examples demonstrating secure practices.
1. Secure JWT Provider Configuration
Ensure your JWT provider is configured to reject insecure tokens and enforce strong algorithms. In start/app.js, configure the auth package as follows:
const { defineConfig } = require('@ioc/Adonis/Addons/Auth')
module.exports = defineConfig({
guards: {
web: {
driver: 'jwt',
provider: 'database',
tokenProvider: 'database',
secret: process.env.JWT_SECRET,
options: {
allowInsecureRequest: false,
expiresIn: '2h',
algorithm: 'HS256'
}
}
}
})
2. CockroachDB Token Revocation Check
Store token identifiers (jti) or revocation timestamps in CockroachDB and validate them on each request. First, define a model for revoked tokens:
// app/Models/RevokedToken.js
'use strict'
const Model = use('Model')
class RevokedToken extends Model {
static get table() {
return 'revoked_tokens'
}
static get createdAtColumn() {
return 'revoked_at'
}
}
module.exports = RevokedToken
Then, implement a custom JWT validator in start/hooks.js to check revocation before authentication succeeds:
const RevokedToken = use('App/Models/RevokedToken')
const checkTokenRevocation = async (tokenPayload, { request }) => {
const isRevoked = await RevokedToken.query()
.where('jti', tokenPayload.jti)
.andWhere('revoked_at', '>', tokenPayload.iat)
.first()
return !isRevoked
}
module.exports = {
hooks: {
'auth:token': checkTokenRevocation
}
}
3. CockroachDB User Record and Secure Token Storage
Use CockroachDB to store user credentials securely with hashed passwords and enforce HTTPS-only communication. Define a user model with proper password hashing:
// app/Models/User.js
'use strict'
const Hash = use('Hash')
class User extends Model {
static get table() {
return 'users'
}
static get hidden() {
return ['password']
}
static async verifyPassword(email, password) {
const user = await this.query().where('email', email).first()
if (!user) return false
return await Hash.verify(password, user.password)
}
}
module.exports = User
In your login controller, ensure tokens are issued only after successful verification and enforce secure cookie attributes:
// app/Controllers/Http/AuthController.js
'use strict'
const { validate } = use('Validator')
const User = use('App/Models/User')
const Token = use('App/Models/Token')
async login({ request, auth, response }) {
const rules = {
email: 'required|email',
password: 'required'
}
const validation = await validate(request.all(), rules)
if (!validation.fails()) {
const user = await User.verifyPassword(request.input('email'), request.input('password'))
if (user) {
const token = await auth.generate(user)
response.cookie('auth_token', token, {
httpOnly: true,
secure: true,
sameSite: 'strict',
path: '/'
})
return { success: true }
}
}
response.status(400).send({ error: 'Invalid credentials' })
}
These configurations align with OWASP API Security Top 10 controls and help prevent common JWT-related vulnerabilities when operating in CockroachDB-backed environments.
Related CWEs: authentication
| CWE ID | Name | Severity |
|---|---|---|
| CWE-287 | Improper Authentication | CRITICAL |
| CWE-306 | Missing Authentication for Critical Function | CRITICAL |
| CWE-307 | Brute Force | HIGH |
| CWE-308 | Single-Factor Authentication | MEDIUM |
| CWE-309 | Use of Password System for Primary Authentication | MEDIUM |
| CWE-347 | Improper Verification of Cryptographic Signature | HIGH |
| CWE-384 | Session Fixation | HIGH |
| CWE-521 | Weak Password Requirements | MEDIUM |
| CWE-613 | Insufficient Session Expiration | MEDIUM |
| CWE-640 | Weak Password Recovery | HIGH |