Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

fix(oidc): count only refused back-channel logouts toward the rate limit

Maurice218304179c3a
diff --git a/server/src/nest/common/rate-limit.service.ts b/server/src/nest/common/rate-limit.service.ts
index 4d3e41303..c0a82d53c 100644
--- a/server/src/nest/common/rate-limit.service.ts
+++ b/server/src/nest/common/rate-limit.service.ts
@@ -18,6 +18,14 @@ export class RateLimitService {
return this.store.hit(bucket, key, max, windowMs, now);
}
+ /**
+ * True when the key already used up `max` in this window, without counting
+ * the request; for a route that counts only the attempts it refuses.
+ */
+ exhausted(bucket: string, key: string, max: number, windowMs: number, now: number): Promise<boolean> {
+ return this.store.exhausted(bucket, key, max, windowMs, now);
+ }
+
/** Test helper: clear a bucket (mirrors the legacy exported maps used for resets). */
reset(bucket?: string): Promise<void> {
return this.store.reset(bucket);
diff --git a/server/src/nest/common/rate-limit.store.ts b/server/src/nest/common/rate-limit.store.ts
index e6669d81d..23ce6558a 100644
--- a/server/src/nest/common/rate-limit.store.ts
+++ b/server/src/nest/common/rate-limit.store.ts
@@ -15,6 +15,8 @@ export abstract class RateLimitStore {
* answers 429), true otherwise.
*/
abstract hit(bucket: string, key: string, max: number, windowMs: number, now: number): Promise<boolean>;
+ /** Whether `key` has already used `max` attempts in the current window, without counting one. */
+ abstract exhausted(bucket: string, key: string, max: number, windowMs: number, now: number): Promise<boolean>;
/** Clear one bucket, or every bucket. */
abstract reset(bucket?: string): Promise<void>;
}
@@ -45,6 +47,11 @@ export class InMemoryRateLimitStore extends RateLimitStore {
return Promise.resolve(this.count(bucket, key, max, windowMs, now));
}
+ exhausted(bucket: string, key: string, max: number, windowMs: number, now: number): Promise<boolean> {
+ const record = this.buckets.get(bucket)?.get(key);
+ return Promise.resolve(!!record && record.count >= max && now - record.first < windowMs);
+ }
+
reset(bucket?: string): Promise<void> {
if (bucket) this.buckets.get(bucket)?.clear();
else {
diff --git a/server/src/nest/oidc/oidc-backchannel.controller.ts b/server/src/nest/oidc/oidc-backchannel.controller.ts
index 86e9503b9..36587dad8 100644
--- a/server/src/nest/oidc/oidc-backchannel.controller.ts
+++ b/server/src/nest/oidc/oidc-backchannel.controller.ts
@@ -14,11 +14,11 @@ import {
import type { Request, Response } from 'express';
/**
- * Requests one address may send in a minute. An identity provider sends one
- * request per signed-out session, and an admin ending every session of a realm
- * sends a burst of them from one address, so the limit sits far above any real
- * logout traffic and only caps a flood of tokens that each cost a signature
- * check.
+ * Refused requests one address may send in a minute. An identity provider
+ * sends one request per signed-out session, and an admin ending every session
+ * of a realm sends a burst of them from one address, so only the requests that
+ * fail count: a validly signed logout is never throttled, and the limit caps a
+ * flood of tokens that each cost a signature check.
*/
export const BACKCHANNEL_LOGOUT_RATE_LIMIT = 600;
const RATE_WINDOW_MS = 60_000;
@@ -36,7 +36,7 @@ const RATE_WINDOW_MS = 60_000;
* `Cache-Control: no-store`: 200 when the token was valid (also when it named
* no account or session here), 400 `{"error":"invalid_request"}` for a missing
* or invalid token and while OIDC is not configured (the login answers 400 for
- * that too). A 429 past the flood limit. Never a 500 for a bad token.
+ * that too). A 429 once an address had too many refused. Never a 500 for a bad token.
*
* The body is form-encoded, which the global `urlencodedParser` reads for this
* path as for every other. It is checked against the shared contract with
@@ -58,27 +58,27 @@ export class OidcBackchannelController {
async logout(@Req() req: Request, @Res({ passthrough: true }) res: Response): Promise<OidcBackchannelLogoutResponse> {
res.set('Cache-Control', 'no-store');
res.set('Pragma', 'no-cache');
- if (
- !(await this.rl.check(
- 'oidc_backchannel',
- req.ip || 'unknown',
- BACKCHANNEL_LOGOUT_RATE_LIMIT,
- RATE_WINDOW_MS,
- Date.now(),
- ))
- ) {
+ const key = req.ip || 'unknown';
+ if (await this.rl.exhausted('oidc_backchannel', key, BACKCHANNEL_LOGOUT_RATE_LIMIT, RATE_WINDOW_MS, Date.now())) {
throw new DomainError(429, 'too_many_requests', {
details: { error_description: 'Too many requests. Please try again later.' },
});
}
- const body = oidcBackchannelLogoutRequestSchema.safeParse(req.body);
- if (!body.success) {
- throw new DomainError(400, 'invalid_request', {
- code: 'missing_logout_token',
- details: { error_description: 'The logout_token parameter is missing or malformed.' },
- });
+ try {
+ const body = oidcBackchannelLogoutRequestSchema.safeParse(req.body);
+ if (!body.success) {
+ throw new DomainError(400, 'invalid_request', {
+ code: 'missing_logout_token',
+ details: { error_description: 'The logout_token parameter is missing or malformed.' },
+ });
+ }
+ await this.backchannel.logout(body.data.logout_token, getClientIp(req) ?? null);
+ return {};
+ } catch (err) {
+ if (err instanceof DomainError && err.getStatus() === 400) {
+ await this.rl.check('oidc_backchannel', key, BACKCHANNEL_LOGOUT_RATE_LIMIT, RATE_WINDOW_MS, Date.now());
+ }
+ throw err;
}
- await this.backchannel.logout(body.data.logout_token, getClientIp(req) ?? null);
- return {};
}
}
diff --git a/server/tests/unit/nest/oidc-backchannel.controller.test.ts b/server/tests/unit/nest/oidc-backchannel.controller.test.ts
index 1cba3fba2..3148bac1b 100644
--- a/server/tests/unit/nest/oidc-backchannel.controller.test.ts
+++ b/server/tests/unit/nest/oidc-backchannel.controller.test.ts
@@ -22,8 +22,9 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
const logout = vi.fn();
const check = vi.fn();
+const exhausted = vi.fn();
const service = { logout } as unknown as OidcBackchannelService;
-const rl = { check } as unknown as RateLimitService;
+const rl = { check, exhausted } as unknown as RateLimitService;
const controller = () => new OidcBackchannelController(service, rl);
function makeRes() {
@@ -53,6 +54,7 @@ async function refused(call: Promise<unknown>): Promise<{ status: number; body:
beforeEach(() => {
vi.clearAllMocks();
check.mockResolvedValue(true);
+ exhausted.mockResolvedValue(false);
logout.mockResolvedValue(undefined);
});
@@ -104,23 +106,49 @@ describe('OidcBackchannelController POST /api/auth/oidc/backchannel-logout', ()
});
it('BCL-CTL-005: past the flood limit the answer is 429, before the body is read', async () => {
- check.mockResolvedValue(false);
+ exhausted.mockResolvedValue(true);
const res = makeRes();
expect(await refused(controller().logout(req({ logout_token: 'a.b.c' }), res))).toEqual({
status: 429,
body: { error: 'too_many_requests', error_description: 'Too many requests. Please try again later.' },
});
- expect(check).toHaveBeenCalledWith(
+ expect(exhausted).toHaveBeenCalledWith(
'oidc_backchannel',
'198.51.100.7',
BACKCHANNEL_LOGOUT_RATE_LIMIT,
60_000,
expect.any(Number),
);
+ expect(check).not.toHaveBeenCalled();
expect(logout).not.toHaveBeenCalled();
expect(res.headers['cache-control']).toBe('no-store');
});
+ it('BCL-CTL-007: only refused tokens count toward the limit, so a bulk logout of valid tokens is never throttled', async () => {
+ for (let i = 0; i < BACKCHANNEL_LOGOUT_RATE_LIMIT + 5; i++) {
+ await controller().logout(req({ logout_token: 'a.b.c' }), makeRes());
+ }
+ expect(check).not.toHaveBeenCalled();
+
+ expect((await refused(controller().logout(req({}), makeRes()))).status).toBe(400);
+ logout.mockRejectedValue(new DomainError(400, 'invalid_request'));
+ expect((await refused(controller().logout(req({ logout_token: 'x.y.z' }), makeRes()))).status).toBe(400);
+ expect(check).toHaveBeenCalledTimes(2);
+ expect(check).toHaveBeenLastCalledWith(
+ 'oidc_backchannel',
+ '198.51.100.7',
+ BACKCHANNEL_LOGOUT_RATE_LIMIT,
+ 60_000,
+ expect.any(Number),
+ );
+ });
+
+ it('BCL-CTL-008: a failure that is not a refused token is passed on without counting', async () => {
+ logout.mockRejectedValue(new Error('database down'));
+ await expect(controller().logout(req({ logout_token: 'a.b.c' }), makeRes())).rejects.toThrow('database down');
+ expect(check).not.toHaveBeenCalled();
+ });
+
it('BCL-CTL-006: the route is a public POST that answers 200 under the OIDC prefix', () => {
const handler = OidcBackchannelController.prototype.logout;
expect(Reflect.getMetadata(PATH_METADATA, OidcBackchannelController)).toBe('api/auth/oidc');
diff --git a/server/tests/unit/nest/rate-limit.service.test.ts b/server/tests/unit/nest/rate-limit.service.test.ts
index 2fdc68386..ddae1cbe4 100644
--- a/server/tests/unit/nest/rate-limit.service.test.ts
+++ b/server/tests/unit/nest/rate-limit.service.test.ts
@@ -25,6 +25,19 @@ describe('RateLimitService', () => {
expect(await s.check('login', '1.2.3.4', 5, WINDOW, now)).toBe(false);
});
+ it('exhausted answers whether the key is spent without counting an attempt', async () => {
+ const s = new RateLimitService();
+ const now = Date.now();
+ expect(await s.exhausted('logout', '1.2.3.4', 2, WINDOW, now)).toBe(false);
+ for (let i = 0; i < 5; i++) await s.exhausted('logout', '1.2.3.4', 2, WINDOW, now);
+ expect(bucketSize(s, 'logout')).toBe(0);
+ await s.check('logout', '1.2.3.4', 2, WINDOW, now);
+ expect(await s.exhausted('logout', '1.2.3.4', 2, WINDOW, now)).toBe(false);
+ await s.check('logout', '1.2.3.4', 2, WINDOW, now);
+ expect(await s.exhausted('logout', '1.2.3.4', 2, WINDOW, now)).toBe(true);
+ expect(await s.exhausted('logout', '1.2.3.4', 2, WINDOW, now + WINDOW)).toBe(false);
+ });
+
it('starts a fresh window once the old one elapsed', async () => {
const s = new RateLimitService();
const now = Date.now();