HIGH api rate abuseadonisjssession cookies

Api Rate Abuse in Adonisjs with Session Cookies

Api Rate Abuse in Adonisjs with Session Cookies — how this specific combination creates or exposes the vulnerability

Rate abuse in AdonisJS when using session cookies occurs because session-based authentication does not inherently enforce per-identity request limits at the API layer. AdonisJS applications typically rely on session identifiers stored in HTTP-only cookies to recognize authenticated users. If routes that perform create, update, or billing operations do not explicitly enforce rate limits, an authenticated session can be used to flood endpoints with repeated requests.

When a session cookie is accepted but no complementary rate-limiting strategy is applied, the server may process many operations in a short window. This can manifest as brute-force-like behavior on password reset tokens, mass creation of records, or repeated calls to expensive operations such as payments or notifications. Even though the session proves identity, it does not prove intent or rate, so the API surface remains exposed to denial-of-service impacts and resource exhaustion.

The risk is compounded if the session store or cookie configuration is permissive. For example, a broad session cookie scope across subdomains or missing SameSite attributes can allow cross-origin requests to carry the session identifier into requests that the developer did not intend to be rate-able from that context. Without explicit per-session or per-IP throttling tied to the authenticated subject, AdonisJS endpoints default to trusting the session alone, which is insufficient for abuse prevention.

Consider an endpoint like POST /api/invoices that creates a new invoice when a session cookie is present. Without a rate limit, an attacker who has obtained a valid session can submit hundreds of invoices in minutes, leading to financial anomalies or database bloat. MiddleBrick detects such patterns by correlating authenticated requests with high request volumes per session, highlighting missing rate controls alongside the presence of session-based authentication in the scan findings.

Effective mitigation combines server-side session validation with explicit rate-limiting rules that consider the authenticated subject. This ensures that even if a session cookie is accepted, the API enforces strict ceilings on actions per user per time window, reducing the impact of credential compromise and protecting backend resources from overload.

Session Cookies-Specific Remediation in Adonisjs — concrete code fixes

To secure AdonisJS APIs using session cookies, apply rate limiting at the route or controller level and harden cookie attributes to reduce abuse surfaces. Below are focused code examples that demonstrate these protections.

1) Apply rate limits using the built-in Throttle provider

AdonisJS offers a throttle provider that can be configured per route or globally. This example limits a sensitive endpoint to 10 requests per minute per authenticated user identified by their session ID.

// start/routes.ts
import Route from '@ioc:Adonis/Core/Route'
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'

Route.post('/api/invoices', async ({ request, auth, response }: HttpContextContract) => {
  const user = auth.getUserOrFail()
  // business logic here
  return response.created({ invoiceId: 'inv_123' })
}).throttle({ max: 10, duration: 60, identifier: () => auth.user?.id ?? 'anonymous' })

2) Tighten session cookie attributes

Ensure cookies are scoped narrowly and protected in transit with secure, same-site, and partitioned attributes.

// start/hooks.ts
import { HttpServer } from '@ioc:Adonis/Core/HttpServer'

export const hooks = {
  async beforeHandle({ request, response }: { request: any; response: any }) {
    if (response.hasHeader('Set-Cookie')) {
      const base = 'Path=/; HttpOnly; Secure; SameSite=Strict;'
      response.appendHeader('Set-Cookie', `Partitioned=${base}; Secure;`)
    }
  },
}

In config/session.ts, prefer strict SameSite and short lifetimes for high-risk routes:

// config/session.ts
export const sessionConfig = {
  driver: 'cookie',
  key: '__session',
  maxAge: 7200000, // 2 hours
  sameSite: 'strict',
  secure: true,
  httpOnly: true,
  partitioned: true,
}

3) Combine route-level checks with session validation

For critical mutations, verify session freshness and enforce per-identity caps before processing.

// controllers/InvoicesController.ts
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import { throttleBySession } from 'App/Services/RateService'

export default class InvoicesController {
  public async store({ request, auth, response }: HttpContextContract) {
    const user = auth.getUserOrFail()
    const allowed = await throttleBySession(user.id, 5, 60) // 5 per minute
    if (!allowed) {
      return response.status(429).send({ error: 'Too many requests' })
    }
    // proceed with creation
    return response.created({ invoiceId: 'inv_456' })
  }
}

4) Use IP and user composite identifiers for broader protection

When user context is unavailable or for unauthenticated flows, tie limits to IP and session fingerprint.

// middleware/rateLimitSession.ts
import { Exception } from '@ioc:Adonis/Core/Exception'
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'

export default async function rateLimitSession({ request, response }: HttpContextContract) {
  const key = `rate:${request.ip()}:${request.session().get('sessionId')}`
  const current = request.ctx.get('rateCounter') || 0
  if (current > 100) {
    throw new Exception('Rate limit exceeded', 429, 'RATE_LIMIT_EXCEEDED')
  }
  request.ctx.set('rateCounter', current + 1)
}

5) Centralize limits via provider registration

Register a global throttle for session-authenticated routes to enforce organization-wide caps.

// start/kernel.ts
import { HttpServer } from '@ioc:Adonis/Core/HttpServer'
import { rateLimiter } from 'App/Middleware/RateLimiter'

const server = use(HttpServer)
server.globalMiddlewares.push(rateLimiter)

Frequently Asked Questions

How does middleBrick detect rate abuse when session cookies are used in AdonisJS?
MiddleBrick correlates authenticated requests with high request volumes per session. It flags endpoints where a session identifier drives repeated calls to sensitive routes without corresponding server-side rate limits, surfacing missing throttling alongside session cookie usage in the findings.
Does middleBrick provide specific AdonisJS code examples for fixing rate abuse with session cookies?
MiddleBrick reports include actionable remediation guidance. For AdonisJS, guidance recommends using route-level throttle configurations, tightening session cookie attributes, and applying per-identity caps to sensitive operations, with code examples for route middleware and controller-level enforcement.