Data Exposure in Adonisjs with Basic Auth
Data Exposure in Adonisjs with Basic Auth — how this specific combination creates or exposes the vulnerability
When AdonisJS applications use HTTP Basic Authentication without additional protections, sensitive authentication data can be exposed in ways that amplify the risk of credential leakage and unauthorized access. Basic Auth transmits credentials in the request header using Base64 encoding, which is easily reversible and does not provide confidentiality by itself. If an application does not enforce HTTPS, credentials can be intercepted in transit. Even when HTTPS is used, improper handling of authentication headers can lead to exposure in logs, error messages, or server configurations.
AdonisJS does not enforce transport-layer security by default. A developer might configure the auth:basic provider in config/auth.ts and assume that the framework handles security implicitly. However, if routes using Basic Auth are accessible over HTTP, or if the application inadvertently logs request headers, credentials can be exposed. The framework may also expose stack traces or detailed validation errors during development, inadvertently revealing which usernames are valid through timing differences or error messages. These issues fall under the Data Exposure checks performed by middleBrick, which tests unauthenticated endpoints for sensitive data leakage in responses, headers, and error payloads.
Another exposure vector involves caching mechanisms. Reverse proxies, CDNs, or browser caches might store responses from authenticated routes if cache-control headers are not explicitly set. Because Basic Auth credentials are tied to each request, cached responses containing sensitive user data can be served to unauthorized users. middleBrick’s Data Exposure checks examine whether responses include sensitive information such as email addresses, internal identifiers, or session tokens in plaintext. In AdonisJS applications using Basic Auth, findings commonly include missing Cache-Control: no-store headers, verbose error details in production, and unprotected backup or debug endpoints that return user data without requiring re-authentication.
The interaction between AdonisJS authentication providers and route middleware can also contribute to exposure. If route guards are misconfigured, authenticated routes might be accessible to unauthenticated requests under certain conditions, such as when authentication headers are stripped or when CORS policies are too permissive. middleBrick’s Authentication and BOLA/IDOR checks validate whether authenticated endpoints correctly reject unauthenticated access and whether one user can access another user’s resources. In AdonisJS, a developer might define a policy that checks for a user record but fails to validate ownership consistently, allowing an attacker to iterate through numeric IDs and observe differences in response behavior or data returned when using Basic Auth credentials belonging to other users.
Finally, data exposure in AdonisJS with Basic Auth can be detected through runtime scanning that compares OpenAPI specifications with actual endpoint behavior. If the specification describes an endpoint as requiring authentication but the implementation does not enforce it, or if the response schema includes fields that should never be exposed without proper authorization, middleBrick identifies these inconsistencies. For example, an endpoint documented as requiring Basic Auth might return full user objects including password hashes or internal flags in error cases. These discrepancies are surfaced in the report with remediation guidance focused on enforcing HTTPS, tightening CORS policies, and ensuring consistent authorization checks across all routes that handle sensitive data.
Basic Auth-Specific Remediation in Adonisjs — concrete code fixes
To mitigate Data Exposure risks when using HTTP Basic Authentication in AdonisJS, developers must enforce HTTPS, secure headers, and strict authorization logic. The following code examples demonstrate secure configurations and request handling patterns that align with remediation guidance provided by tools like middleBrick.
1. Enforce HTTPS and secure headers
Ensure all routes using Basic Auth are served over HTTPS and include security headers that prevent caching of sensitive responses. This can be done in the start/hooks.ts file by adding middleware that sets headers before the request proceeds.
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
export default function secureHeadersMiddleware({ response }: HttpContextContract) {
response.header('Strict-Transport-Security', 'max-age=31536000; includeSubDomains')
response.header('Cache-Control', 'no-store, no-cache, must-revalidate, private')
response.header('X-Content-Type-Options', 'nosniff')
response.header('X-Frame-Options', 'DENY')
}
2. Configure Basic Auth provider securely
Define the Basic Auth provider in config/auth.ts using a custom user resolver that validates credentials against a database while avoiding information leakage. Do not expose which field is used for authentication in error messages.
import { User } from 'App/Models/User'
import { Hash } from '@ioc:Adonis/Core/Hash'
export const authConfig = {
defaults: {
guard: 'api',
},
guards: {
api: {
driver: 'basic',
provider: 'users',
},
},
providers: {
users: {
driver: 'lucid',
model: User,
},
},
}
3. Implement a secure login route with constant-time validation
Create a dedicated route for authentication that uses constant-time comparison to avoid timing attacks. Return generic error messages to prevent user enumeration.
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import { schema } from '@ioc:Adonis/Core/Validator'
export default class AuthController {
public async login({ request, auth, response }: HttpContextContract) {
const validationSchema = schema.create({
username: schema.string({ trim: true }),
password: schema.string(),
})
const validatedData = await request.validate({ schema: validationSchema })
// Use auth.attempt with constant-time behavior
const user = await auth.use('api').attempt(validatedData.username, validatedData.password, {
expiresIn: '2h',
})
if (!user) {
// Always return the same response shape and status
return response.unauthorized({ message: 'Invalid credentials' })
}
return response.ok({ token: user.generateJwt() })
}
}
4. Apply authorization checks on every protected route
Use route middleware or policies to ensure that authenticated users can only access their own data. Avoid relying solely on Basic Auth for row-level security.
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import User from 'App/Models/User'
export async function ensureUserOwnership({ params, auth, response }: HttpContextContract) {
const requestedUser = await User.findOrFail(params.id)
const currentUser = auth.user!
if (requestedUser.id !== currentUser.id) {
return response.forbidden({ message: 'Access denied' })
}
}
5. Disable Basic Auth in non-production environments
During development, avoid using Basic Auth unless necessary. If used, ensure that test credentials are not shared and that endpoints are not exposed publicly. middleBrick’s CLI can scan development URLs to confirm that authentication requirements are correctly enforced before deployment.
By combining these code-level fixes with continuous scanning using the middleBrick CLI and Web Dashboard, teams can detect regressions in authentication handling and ensure that Basic Auth implementations do not contribute to Data Exposure. The GitHub Action can enforce a minimum security score before allowing merges, while the MCP Server enables developers to validate API security directly within their IDE during coding sessions.
Related CWEs: dataExposure
| CWE ID | Name | Severity |
|---|---|---|
| CWE-200 | Exposure of Sensitive Information | HIGH |
| CWE-209 | Error Information Disclosure | MEDIUM |
| CWE-213 | Exposure of Sensitive Information Due to Incompatible Policies | HIGH |
| CWE-215 | Insertion of Sensitive Information Into Debugging Code | MEDIUM |
| CWE-312 | Cleartext Storage of Sensitive Information | HIGH |
| CWE-359 | Exposure of Private Personal Information (PII) | HIGH |
| CWE-522 | Insufficiently Protected Credentials | CRITICAL |
| CWE-532 | Insertion of Sensitive Information into Log File | MEDIUM |
| CWE-538 | Insertion of Sensitive Information into Externally-Accessible File | HIGH |
| CWE-540 | Inclusion of Sensitive Information in Source Code | HIGH |