From d30f2689fbe7a4af573b0801016d05462f34be5d Mon Sep 17 00:00:00 2001 From: Brandon Corbett Date: Thu, 3 Dec 2026 10:24:38 -0500 Subject: [PATCH] fix(oidc): rate limit provider storage and signing per end client --- .changeset/oidc-per-client-limits.md | 5 + docs/ecosystem.md | 3 + src/middleware/requireOidcEdge.ts | 61 +++++--- src/routes/oidc.routes.ts | 12 +- .../oidc/oidcEdgeRateLimits.spec.ts | 133 ++++++++++++++++++ 5 files changed, 191 insertions(+), 23 deletions(-) create mode 100644 .changeset/oidc-per-client-limits.md create mode 100644 tests/integration/oidc/oidcEdgeRateLimits.spec.ts diff --git a/.changeset/oidc-per-client-limits.md b/.changeset/oidc-per-client-limits.md new file mode 100644 index 00000000..06057631 --- /dev/null +++ b/.changeset/oidc-per-client-limits.md @@ -0,0 +1,5 @@ +--- +'seamless-auth-api': patch +--- + +The `/oidc/*` provider routes now rate limit each end client on its own, ahead of the existing shared ceilings. Payload writes, signatures and events are counted per client address, which the OpenID Provider service already forwards in `x-seamless-client-ip` and the API honours only alongside that service's token. One client may use a fifth of each shared ceiling (1200 payload writes per model, 600 signatures and 600 events a minute), and IPv6 clients are counted by /56. Calls that carry no client address, such as those from an older provider service, keep the shared ceilings alone, so no provider upgrade is required. diff --git a/docs/ecosystem.md b/docs/ecosystem.md index 32ce1316..037f02bf 100644 --- a/docs/ecosystem.md +++ b/docs/ecosystem.md @@ -119,6 +119,9 @@ It builds on `@seamless-auth/express` for first-party sign-in and calls the version, or one that answers 404 because `oidc_provider_enabled` is off. - **Breaks if changed here:** any `/oidc/*` route, request or response shape, the `/oidc/sign` refusal codes, the `acr`/`amr` derivation, or the service-token check. +- Forwards the end client's address in `x-seamless-client-ip`. The `/oidc/*` limiters count + each client by it (honoured only beside the provider's service token), so an edge that stops + sending it falls back to the shared ceilings alone. ## Tier 2 — downstream consumers (transitively affected) diff --git a/src/middleware/requireOidcEdge.ts b/src/middleware/requireOidcEdge.ts index 9b364f54..e294b2ae 100644 --- a/src/middleware/requireOidcEdge.ts +++ b/src/middleware/requireOidcEdge.ts @@ -5,7 +5,7 @@ */ import { NextFunction, Request, RequestHandler, Response } from 'express'; -import rateLimit from 'express-rate-limit'; +import rateLimit, { ipKeyGenerator } from 'express-rate-limit'; import { getSystemConfig } from '../config/getSystemConfig.js'; import { validateOidcEdgeServiceToken } from './authenticateServiceToken.js'; @@ -43,32 +43,59 @@ async function oidcEdgeGuard(req: Request, res: Response, next: NextFunction) { export const requireOidcEdge = oidcEdgeGuard as SecuritySchemeAwareHandler; requireOidcEdge.seamlessSecurityScheme = OIDC_EDGE_SECURITY_SCHEME; -// A fixed ceiling rather than a config key: it exists so a misbehaving edge cannot flood -// the store, and a correct one at sign-in rates stays far below it. +// Fixed ceilings rather than config keys: they exist so a misbehaving edge cannot flood the +// store, and a correct one at sign-in rates stays far below them. const PAYLOAD_WRITES_PER_MINUTE_PER_MODEL = 6000; +const SIGNATURES_PER_MINUTE = 3000; +const EVENTS_PER_MINUTE = 3000; -function fixedLimiter(limit: number, key: (req: Request) => string) { +// One end client may take a fifth of each ceiling, so no single one can spend it for the rest. +const CLIENT_SHARE = 5; + +function trustedClientKey(req: Request): string | null { + const address = (req as Request & { trustedClientIp?: string }).trustedClientIp; + + return address ? ipKeyGenerator(address) : null; +} + +function limiter( + limit: number, + key: (req: Request) => string, + skip: (req: Request) => boolean = rateLimitsDisabled, +) { return rateLimit({ windowMs: 60 * 1000, limit, keyGenerator: key, standardHeaders: true, legacyHeaders: false, - skip: rateLimitsDisabled, + skip, message: TOO_MANY_REQUESTS_BODY, }); } +/** + * A ceiling for each end client ahead of the shared one. The edge names the client with + * `x-seamless-client-ip`, which `applyTrustedClientContext` honours only beside a valid + * service token. A call that names none (an edge that predates this, or work outside a + * browser request) meets the shared ceiling alone. + */ +function perClientThenShared(limit: number, scope: (req: Request) => string): RequestHandler[] { + return [ + limiter( + Math.ceil(limit / CLIENT_SHARE), + (req) => `${scope(req)}:client:${trustedClientKey(req)}`, + (req) => rateLimitsDisabled() || trustedClientKey(req) === null, + ), + limiter(limit, scope), + ]; +} + // Each refused signature and each event writes an audit row. -export const oidcSignLimiter = fixedLimiter(3000, () => 'oidc-sign'); -export const oidcEventLimiter = fixedLimiter(3000, () => 'oidc-events'); - -export const oidcPayloadWriteLimiter = rateLimit({ - windowMs: 60 * 1000, - limit: PAYLOAD_WRITES_PER_MINUTE_PER_MODEL, - keyGenerator: (req) => `oidc-payload:${String(req.params.model)}`, - standardHeaders: true, - legacyHeaders: false, - skip: rateLimitsDisabled, - message: TOO_MANY_REQUESTS_BODY, -}); +export const oidcSignLimiters = perClientThenShared(SIGNATURES_PER_MINUTE, () => 'oidc-sign'); +export const oidcEventLimiters = perClientThenShared(EVENTS_PER_MINUTE, () => 'oidc-events'); + +export const oidcPayloadWriteLimiters = perClientThenShared( + PAYLOAD_WRITES_PER_MINUTE_PER_MODEL, + (req) => `oidc-payload:${String(req.params.model)}`, +); diff --git a/src/routes/oidc.routes.ts b/src/routes/oidc.routes.ts index eea9f3a7..f3e44847 100644 --- a/src/routes/oidc.routes.ts +++ b/src/routes/oidc.routes.ts @@ -56,9 +56,9 @@ import { } from '../controllers/oidcEdge.js'; import { createRouter } from '../lib/createRouter.js'; import { - oidcEventLimiter, - oidcPayloadWriteLimiter, - oidcSignLimiter, + oidcEventLimiters, + oidcPayloadWriteLimiters, + oidcSignLimiters, requireOidcEdge, } from '../middleware/requireOidcEdge.js'; import { ErrorSchema, MessageSchema } from '../schemas/generic.responses.js'; @@ -91,7 +91,7 @@ oidcRouter.put( '/payloads/:model/:id', { ...edge, - middleware: [requireOidcEdge, oidcPayloadWriteLimiter], + middleware: [requireOidcEdge, ...oidcPayloadWriteLimiters], summary: 'Store a provider record', schemas: { params: OidcPayloadParamsSchema, @@ -182,7 +182,7 @@ oidcRouter.post( '/sign', { ...edge, - middleware: [requireOidcEdge, oidcSignLimiter], + middleware: [requireOidcEdge, ...oidcSignLimiters], summary: 'Sign a provider token the API would issue itself', schemas: { body: OidcSignRequestSchema, @@ -307,7 +307,7 @@ oidcRouter.post( '/events', { ...edge, - middleware: [requireOidcEdge, oidcEventLimiter], + middleware: [requireOidcEdge, ...oidcEventLimiters], summary: 'Record a provider audit event', schemas: { body: OidcEdgeEventSchema, diff --git a/tests/integration/oidc/oidcEdgeRateLimits.spec.ts b/tests/integration/oidc/oidcEdgeRateLimits.spec.ts new file mode 100644 index 00000000..9b8067d7 --- /dev/null +++ b/tests/integration/oidc/oidcEdgeRateLimits.spec.ts @@ -0,0 +1,133 @@ +import express, { Application, RequestHandler } from 'express'; +import request from 'supertest'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { getSystemConfig } from '../../../src/config/getSystemConfig.js'; +import { TOO_MANY_REQUESTS_BODY } from '../../../src/middleware/tooManyRequests.js'; +import { buildSystemConfig } from '../../factories/systemConfigFactory'; +import { + mintInternalServiceToken, + mintOidcEdgeServiceToken, +} from '../../factories/serviceTokenFactory'; + +type LimiterName = 'oidcSignLimiters' | 'oidcEventLimiters' | 'oidcPayloadWriteLimiters'; + +const PER_CLIENT = { + oidcSignLimiters: 600, + oidcEventLimiters: 600, + oidcPayloadWriteLimiters: 1200, +}; + +let edgeToken: string; + +/** The `/oidc/*` pipeline for one limiter set, with fresh counters for each test. */ +async function appWith(name: LimiterName): Promise { + vi.resetModules(); + const { applyTrustedClientContext } = + await import('../../../src/middleware/trustedClientContext.js'); + const guard = await import('../../../src/middleware/requireOidcEdge.js'); + const limiters = guard[name] as RequestHandler[]; + edgeToken = await mintOidcEdgeServiceToken(); + + const app = express(); + app.use(applyTrustedClientContext); + app.put('/oidc/payloads/:model/:id', guard.requireOidcEdge, ...limiters, (_req, res) => { + res.status(200).json({ ok: true }); + }); + return app; +} + +function call(app: Application, options: { clientIp?: string; token?: string; model?: string }) { + const req = request(app).put(`/oidc/payloads/${options.model ?? 'Interaction'}/abc`); + if (options.token) req.set('x-seamless-service-token', options.token); + if (options.clientIp) req.set('x-seamless-client-ip', options.clientIp); + return req; +} + +async function spend(app: Application, count: number, clientIp?: string) { + for (let i = 0; i < count; i += 1) { + const res = await call(app, { token: edgeToken, ...(clientIp ? { clientIp } : {}) }); + expect(res.status).toBe(200); + } +} + +beforeEach(() => { + vi.mocked(getSystemConfig).mockResolvedValue( + buildSystemConfig({ oidc_provider_enabled: true, oidc_issuer: 'https://login.example.com' }), + ); +}); + +describe.each(Object.keys(PER_CLIENT) as LimiterName[])('%s', (name) => { + it('refuses one end client past its share and leaves the rest alone', async () => { + const app = await appWith(name); + await spend(app, PER_CLIENT[name], '203.0.113.7'); + + const refused = await call(app, { token: edgeToken, clientIp: '203.0.113.7' }); + expect(refused.status).toBe(429); + expect(refused.body).toEqual(TOO_MANY_REQUESTS_BODY); + + const other = await call(app, { token: edgeToken, clientIp: '198.51.100.9' }); + expect(other.status).toBe(200); + }); +}); + +describe('per-client keys', () => { + it('falls back to the shared ceiling alone when the edge names no client', async () => { + const app = await appWith('oidcSignLimiters'); + await spend(app, PER_CLIENT.oidcSignLimiters + 1); + }); + + it('counts one IPv6 /56 as one client', async () => { + const app = await appWith('oidcSignLimiters'); + await spend(app, PER_CLIENT.oidcSignLimiters, '2001:db8:0:ff00::1'); + + const sameSubnet = await call(app, { token: edgeToken, clientIp: '2001:db8:0:ff42::9' }); + expect(sameSubnet.status).toBe(429); + }); + + it('keeps each model in its own bucket', async () => { + const app = await appWith('oidcPayloadWriteLimiters'); + await spend(app, PER_CLIENT.oidcPayloadWriteLimiters, '203.0.113.7'); + + const otherModel = await call(app, { + token: edgeToken, + clientIp: '203.0.113.7', + model: 'Session', + }); + expect(otherModel.status).toBe(200); + }); + + it('does not take the client address from a caller without the edge token', async () => { + const app = await appWith('oidcSignLimiters'); + + const anonymous = await call(app, { clientIp: '203.0.113.7' }); + expect(anonymous.status).toBe(401); + + const adapter = await call(app, { + token: await mintInternalServiceToken(), + clientIp: '203.0.113.7', + }); + expect(adapter.status).toBe(401); + }); + + it('ignores a forwarded address the API does not trust', async () => { + vi.resetModules(); + const { applyTrustedClientContext } = + await import('../../../src/middleware/trustedClientContext.js'); + const { oidcSignLimiters } = await import('../../../src/middleware/requireOidcEdge.js'); + edgeToken = await mintOidcEdgeServiceToken(); + + // The limiters alone, as if mounted without the guard: an address forwarded without a + // valid token never becomes a per-client key, so it can neither pick nor spend a bucket. + const app = express(); + app.use(applyTrustedClientContext); + app.put('/oidc/payloads/:model/:id', ...oidcSignLimiters, (_req, res) => { + res.status(200).json({ ok: true }); + }); + + for (let i = 0; i < PER_CLIENT.oidcSignLimiters; i += 1) { + expect((await call(app, { clientIp: '203.0.113.7', token: 'forged' })).status).toBe(200); + } + expect((await call(app, { clientIp: '203.0.113.7', token: edgeToken })).status).toBe(200); + }); +});