From a47e46c0b857f4934f06b2ed5bba5f7817733a8b Mon Sep 17 00:00:00 2001 From: Romain Lanz Date: Mon, 12 Oct 2026 11:40:52 +0000 Subject: [PATCH] perf: register ShieldMiddleware as a singleton MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Router middleware are resolved from the container on every request. Because the provider used `container.bind`, each request read the shield config, resolved the encryption service, ran a dynamic `import('edge.js')` and rebuilt every guard. The middleware and its guards keep no per-request state (everything goes through the HTTP context), so build them once with `container.singleton`. On a minimal route that goes through session and shield, server CPU drops from ~174 to ~136 µs per request. The shield config and the encryption service are now read on the first resolution only. Changing them at runtime after the first request has no effect. --- providers/shield_provider.ts | 6 ++- tests/helpers.ts | 5 ++- tests/provider.spec.ts | 78 ++++++++++++++++++++++++++++++++++++ 3 files changed, 87 insertions(+), 2 deletions(-) create mode 100644 tests/provider.spec.ts diff --git a/providers/shield_provider.ts b/providers/shield_provider.ts index d8e357f..38b9e9c 100644 --- a/providers/shield_provider.ts +++ b/providers/shield_provider.ts @@ -37,9 +37,13 @@ export default class ShieldProvider { * Registers ShieldMiddleware to the container with proper configuration * and dependencies. This method binds the middleware to the IoC container * and sets up Edge.js integration when available. + * + * The middleware is registered as a singleton because router middleware + * are resolved on every request and the middleware keeps no per-request + * state (everything goes through the HTTP context). */ async register() { - this.app.container.bind(ShieldMiddleware, async () => { + this.app.container.singleton(ShieldMiddleware, async () => { const config = this.app.config.get('shield', {}) const encryptionManager = await this.app.container.make('encryption') const encryption = encryptionManager.use() diff --git a/tests/helpers.ts b/tests/helpers.ts index cb7c0ad..3cb099f 100644 --- a/tests/helpers.ts +++ b/tests/helpers.ts @@ -19,6 +19,7 @@ import { defineConfig as defineSessionConfig } from '@adonisjs/session' import { sessionApiClient } from '@adonisjs/session/plugins/api_client' import { type IncomingMessage, type ServerResponse, createServer } from 'node:http' +import type { ShieldConfig } from '../src/types.ts' import { shieldApiClient } from '../src/plugins/api_client.ts' export const BASE_URL = new URL('./tmp/', import.meta.url) @@ -35,7 +36,7 @@ export const httpServer = { }, } -export async function setup() { +export async function setup(options: { shield?: ShieldConfig } = {}) { const ignitor = new IgnitorFactory() .withCoreProviders() .withCoreConfig() @@ -43,11 +44,13 @@ export async function setup() { config: { views: { cache: { enabled: false } }, session: defineSessionConfig({ enabled: true, store: 'memory', stores: {} }), + ...(options.shield ? { shield: options.shield } : {}), }, rcFileContents: { providers: [ () => import('@adonisjs/session/session_provider'), () => import('@adonisjs/core/providers/edge_provider'), + ...(options.shield ? [() => import('../providers/shield_provider.ts')] : []), ], }, }) diff --git a/tests/provider.spec.ts b/tests/provider.spec.ts new file mode 100644 index 0000000..dbdc099 --- /dev/null +++ b/tests/provider.spec.ts @@ -0,0 +1,78 @@ +/* + * @adonisjs/shield + * + * (c) AdonisJS + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +import { test } from '@japa/runner' + +import { httpServer, setup } from './helpers.ts' +import { defineConfig } from '../src/define_config.ts' +import ShieldMiddleware from '../src/shield_middleware.ts' + +const shieldConfig = defineConfig({ + csrf: { enabled: true, methods: ['POST', 'PUT', 'PATCH', 'DELETE'] }, + xFrame: { enabled: true, action: 'DENY' }, + contentTypeSniffing: { enabled: true }, +}) + +test.group('Shield provider', () => { + test('construct the middleware only once', async ({ assert }) => { + const app = await setup({ shield: shieldConfig }) + + let constructions = 0 + app.container.resolving(ShieldMiddleware, () => { + constructions++ + }) + + const first = await app.container.make(ShieldMiddleware) + const second = await app.container.make(ShieldMiddleware) + const fromResolver = await app.container.createResolver().make(ShieldMiddleware) + + assert.instanceOf(first, ShieldMiddleware) + assert.strictEqual(first, second) + assert.strictEqual(first, fromResolver) + assert.equal(constructions, 1) + }) + + test('reuse the middleware instance across HTTP requests', async ({ assert }) => { + const app = await setup({ shield: shieldConfig }) + + let constructions = 0 + app.container.resolving(ShieldMiddleware, () => { + constructions++ + }) + + const router = await app.container.make('router') + router.use([ + () => import('@adonisjs/session/session_middleware'), + () => import('../src/shield_middleware.ts'), + ]) + router.get('/', ({ request }) => ({ token: request.csrfToken })) + router.post('/', () => 'ok') + + const server = await app.container.make('server') + await server.boot() + + const nodeServer = httpServer.create(server.handle.bind(server)) + await new Promise((resolve) => nodeServer.listen(0, resolve)) + const { port } = nodeServer.address() as { port: number } + const url = `http://localhost:${port}/` + + const getResponse = await fetch(url) + assert.equal(getResponse.status, 200) + assert.equal(getResponse.headers.get('x-frame-options'), 'DENY') + assert.equal(getResponse.headers.get('x-content-type-options'), 'nosniff') + const body = (await getResponse.json()) as { token: string } + assert.isString(body.token) + + const postResponse = await fetch(url, { method: 'POST' }) + assert.equal(postResponse.status, 403) + + await fetch(url) + assert.equal(constructions, 1) + }) +})