HIGH cross site request forgeryadonisjs

Cross Site Request Forgery in Adonisjs

How Cross Site Request Forgery Manifests in Adonisjs

Cross Site Request Forgery (CSRF) in Adonisjs applications occurs when an attacker tricks authenticated users into executing unwanted actions on your application without their knowledge. The vulnerability exploits the fact that browsers automatically include cookies with requests to the same domain, allowing attackers to craft malicious requests that appear legitimate.

In Adonisjs, CSRF manifests through several specific attack vectors. The most common is state-changing operations performed via GET requests. Adonisjs developers sometimes create endpoints that modify data when accessed via GET, such as:

Route.get('/delete-user/:id', async ({ params, auth }) => {
  const user = await User.findOrFail(params.id)
  await user.delete()
  return { success: true }
})

This pattern is dangerous because GET requests are easily triggered by simply loading an image or script tag. An attacker could embed: <img src="https://yourapp.com/delete-user/123"> in a malicious page, causing the victim's browser to execute the deletion when the page loads.

Another Adonisjs-specific manifestation involves improper use of route middleware. Developers might forget to apply the verifyCsrfToken middleware to routes that modify state:

Route.post('api/users', async ({ request, response }) => {
  const userData = request.body()
  const user = await User.create(userData)
  return user
})

Without CSRF protection, this endpoint is vulnerable to cross-site POST requests. An attacker could create a form that posts to this endpoint from their malicious domain, and if the victim is authenticated, the request would succeed.

Adonisjs applications are particularly vulnerable when using Inertia.js or Livewire for full-stack applications, as these frameworks often rely on GET requests for navigation while maintaining user state through cookies. An attacker could craft a malicious page that navigates to a state-changing route while the user is authenticated.

Adonisjs-Specific Detection

Detecting CSRF vulnerabilities in Adonisjs requires examining both the codebase and runtime behavior. Start by reviewing your route definitions for state-changing operations using GET methods. In Adonisjs, this means searching for patterns like:

Route.get('/endpoint', async ({ auth }) => { ... modifyData() })

Check your middleware configuration in start/kernel.ts to ensure verifyCsrfToken is included in your global middleware or applied to specific routes that handle state changes:

const globalMiddleware = [
  'Adonis/Core/BodyParser',
  'Adonis/Core/Session',
  'Adonis/Core/VerifyCsrfToken'
]

middleBrick's automated scanning can identify CSRF vulnerabilities in Adonisjs applications without requiring source code access. The scanner tests unauthenticated attack surfaces by attempting to execute state-changing operations and checking if they succeed without proper CSRF tokens. For Adonisjs specifically, middleBrick verifies:

  • Whether state-changing endpoints accept requests without CSRF tokens
  • If GET requests modify server state
  • Whether the application properly validates CSRF tokens on POST/PUT/DELETE requests
  • If session-based authentication is properly protected against CSRF

The scanner provides a security risk score and specific findings with remediation guidance. For example, it might report: "POST /api/users accepts requests without CSRF token - add verifyCsrfToken middleware to protect against CSRF attacks."

middleBrick also analyzes your OpenAPI/Swagger specifications if available, cross-referencing documented endpoints with actual runtime behavior to identify discrepancies in security controls.

Adonisjs-Specific Remediation

Remediating CSRF vulnerabilities in Adonisjs applications involves several layers of defense. The primary approach is using Adonisjs's built-in CSRF protection middleware. First, ensure verifyCsrfToken is properly configured in your middleware stack:

const globalMiddleware = [
  'Adonis/Core/BodyParser',
  'Adonis/Core/Session',
  'Adonis/Core/VerifyCsrfToken'
]

For routes that modify state, always use appropriate HTTP methods (POST, PUT, DELETE, PATCH) instead of GET:

Route.post('/users', async ({ request, response }) => {
  const userData = request.body()
  const user = await User.create(userData)
  return user
})

In your views, include the CSRF token in forms using Adonisjs's helper:

<form method="POST" action="/users">
  {{ csrfField() }}
  <input type="text" name="email" placeholder="Email">
  <button type="submit">Create User</button>
</form>

For AJAX requests, include the CSRF token in headers:

fetch('/api/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
  },
  body: JSON.stringify({ email: 'test@example.com' })
})

Adonisjs also provides the Route.resource method which automatically applies proper HTTP methods and includes CSRF protection:

Route.resource('users', 'UserController')
 .apiOnly()

For API-only applications where CSRF protection isn't appropriate (since APIs typically use tokens rather than cookies), ensure you're using proper authentication mechanisms like API keys or JWT tokens, and avoid relying on session cookies for authentication.

middleBrick's CLI tool can help verify your remediation efforts. After implementing fixes, run middlebrick scan https://yourapp.com to confirm the CSRF vulnerabilities have been resolved and your security score has improved.

Frequently Asked Questions

How does Adonisjs's CSRF protection differ from other frameworks?
Adonisjs provides built-in CSRF middleware that automatically validates tokens for state-changing requests. Unlike some frameworks that require manual token generation and validation, Adonisjs integrates this directly into its middleware system. The framework also provides convenient helpers like csrfField() for forms and automatically includes CSRF tokens in Inertia.js requests, making protection seamless for full-stack applications.
Can middleBrick scan my Adonisjs API without access to the source code?
Yes, middleBrick performs black-box scanning of your Adonisjs API endpoints. It tests the unauthenticated attack surface by sending requests to your endpoints and analyzing responses, without requiring source code, credentials, or agents. The scanner identifies CSRF vulnerabilities by attempting state-changing operations and checking if they succeed without proper CSRF tokens, providing actionable findings even without internal access to your application.