Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

test(api): delete restated auth flow and rate limit suites

Hampus7f883aa7abc2
diff --git a/fluxer_api/src/api/auth/tests/ConcurrentSessions.test.ts b/fluxer_api/src/api/auth/tests/ConcurrentSessions.test.ts
deleted file mode 100644
index aeb653d42..000000000
--- a/fluxer_api/src/api/auth/tests/ConcurrentSessions.test.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {createAuthHarness, createTestAccount, loginAccount} from '@app/api/auth/tests/AuthTestUtils';
-import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {createBuilder} from '@app/api/test/TestRequestBuilder';
-import type {AuthSessionResponse} from '@fluxer/schema/src/domains/auth/AuthSchemas';
-import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
-
-describe('Auth concurrent sessions', () => {
- let harness: ApiTestHarness;
- beforeAll(async () => {
- harness = await createAuthHarness();
- });
- beforeEach(async () => {
- await harness.reset();
- });
- afterAll(async () => {
- await harness?.shutdown();
- });
- it('logging out one session does not affect other sessions', async () => {
- const account = await createTestAccount(harness);
- const session1Token = account.token;
- const account2 = await loginAccount(harness, account);
- const session2Token = account2.token;
- const account3 = await loginAccount(harness, account);
- const session3Token = account3.token;
- const sessions = await createBuilder<Array<AuthSessionResponse>>(harness, session1Token)
- .get('/auth/sessions')
- .execute();
- expect(sessions.length).toBeGreaterThanOrEqual(3);
- await createBuilder(harness, session2Token).post('/auth/logout').expect(204).execute();
- await createBuilder(harness, session1Token).get('/users/@me').expect(200).execute();
- await createBuilder(harness, session3Token).get('/users/@me').expect(200).execute();
- await createBuilder(harness, session2Token).get('/users/@me').expect(401).execute();
- });
-});
diff --git a/fluxer_api/src/api/auth/tests/DesktopHandoffCodeNormalization.test.ts b/fluxer_api/src/api/auth/tests/DesktopHandoffCodeNormalization.test.ts
deleted file mode 100644
index 0d2c3839d..000000000
--- a/fluxer_api/src/api/auth/tests/DesktopHandoffCodeNormalization.test.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {createAuthHarness, createTestAccount, loginAccount} from '@app/api/auth/tests/AuthTestUtils';
-import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
-import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
-
-interface HandoffInitiateResponse {
- code: string;
- poll_secret: string;
-}
-
-interface HandoffInfoResponse {
- status: 'pending' | 'expired';
-}
-
-interface HandoffStatusResponse {
- status: 'pending' | 'completed' | 'expired';
- token?: string;
- user_id?: string;
-}
-
-function validateHandoffCodeFormat(code: string): boolean {
- return /^[A-Z0-9]{6}-[A-Z0-9]{6}$/.test(code);
-}
-
-describe('Auth desktop handoff code normalization', () => {
- let harness: ApiTestHarness;
- beforeAll(async () => {
- harness = await createAuthHarness();
- });
- beforeEach(async () => {
- await harness.reset();
- });
- afterAll(async () => {
- await harness?.shutdown();
- });
- it('accepts codes without dashes and is case-insensitive', async () => {
- const account = await createTestAccount(harness);
- const login = await loginAccount(harness, account);
- const initResp = await createBuilderWithoutAuth<HandoffInitiateResponse>(harness)
- .post('/auth/handoff/initiate')
- .body(null)
- .execute();
- expect(validateHandoffCodeFormat(initResp.code)).toBe(true);
- const codeWithoutDash = initResp.code.replace(/-/g, '');
- const status1 = await createBuilderWithoutAuth<HandoffStatusResponse>(harness)
- .get(`/auth/handoff/${codeWithoutDash}/status`)
- .execute();
- expect(status1.status).toBe('pending');
- const lowercaseCode = initResp.code.toLowerCase();
- await createBuilderWithoutAuth<HandoffInfoResponse>(harness).get(`/auth/handoff/${lowercaseCode}/info`).execute();
- await createBuilderWithoutAuth(harness)
- .post('/auth/handoff/complete')
- .header('Authorization', login.token)
- .body({
- code: lowercaseCode,
- user_id: login.userId,
- })
- .expect(204)
- .execute();
- const status2 = await createBuilderWithoutAuth<HandoffStatusResponse>(harness)
- .post(`/auth/handoff/${initResp.code}/status`)
- .body({poll_secret: initResp.poll_secret})
- .execute();
- expect(status2.status).toBe('completed');
- expect(status2.token).toBeTruthy();
- expect(status2.token).not.toBe(login.token);
- });
-});
diff --git a/fluxer_api/src/api/auth/tests/EmailVerificationFlow.test.ts b/fluxer_api/src/api/auth/tests/EmailVerificationFlow.test.ts
deleted file mode 100644
index 96648ca11..000000000
--- a/fluxer_api/src/api/auth/tests/EmailVerificationFlow.test.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- clearTestEmails,
- createAuthHarness,
- createTestAccount,
- findLastTestEmail,
- listTestEmails,
- loginAccount,
-} from '@app/api/auth/tests/AuthTestUtils';
-import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
-import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
-
-interface UserPrivateResponse {
- verified: boolean;
- email_bounced: boolean;
-}
-
-describe('Email verification flow', () => {
- let harness: ApiTestHarness;
- beforeAll(async () => {
- harness = await createAuthHarness();
- });
- beforeEach(async () => {
- await harness.reset();
- await clearTestEmails(harness);
- });
- afterAll(async () => {
- await harness?.shutdown();
- });
- it('allows resending verification email and verifying email', async () => {
- const account = await createTestAccount(harness, {skipEmailVerification: true});
- await createBuilderWithoutAuth(harness)
- .post(`/test/users/${account.userId}/security-flags`)
- .body({email_verified: false})
- .expect(200)
- .execute();
- await createBuilder(harness, account.token).post('/auth/verify/resend').body({}).expect(204).execute();
- const emails = await listTestEmails(harness, {recipient: account.email});
- const verificationEmail = findLastTestEmail(emails, 'email_verification');
- expect(verificationEmail?.metadata?.token).toBeDefined();
- const token = verificationEmail!.metadata!.token!;
- await createBuilderWithoutAuth(harness).post('/auth/verify').body({token}).expect(204).execute();
- const login = await loginAccount(harness, account);
- expect(login.token).toBeDefined();
- });
- it('clears email_bounced when verifying email', async () => {
- const account = await createTestAccount(harness);
- await createBuilderWithoutAuth(harness)
- .post(`/test/users/${account.userId}/security-flags`)
- .body({
- email_bounced: true,
- email_verified: false,
- })
- .expect(200)
- .execute();
- await createBuilder(harness, account.token).post('/auth/verify/resend').body({}).expect(204).execute();
- const emails = await listTestEmails(harness, {recipient: account.email});
- const verificationEmail = findLastTestEmail(emails, 'email_verification');
- expect(verificationEmail?.metadata?.token).toBeDefined();
- const token = verificationEmail!.metadata!.token!;
- await createBuilderWithoutAuth(harness).post('/auth/verify').body({token}).expect(204).execute();
- const me = await createBuilder<UserPrivateResponse>(harness, account.token).get('/users/@me').expect(200).execute();
- expect(me.verified).toBe(true);
- expect(me.email_bounced).toBe(false);
- });
-});
diff --git a/fluxer_api/src/api/auth/tests/IPAuthFlow.test.ts b/fluxer_api/src/api/auth/tests/IPAuthFlow.test.ts
deleted file mode 100644
index 3ac84da74..000000000
--- a/fluxer_api/src/api/auth/tests/IPAuthFlow.test.ts
+++ /dev/null
@@ -1,79 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- clearTestEmails,
- createAuthHarness,
- createUniqueEmail,
- createUniqueUsername,
- findLastTestEmail,
- listTestEmails,
- registerUser,
-} from '@app/api/auth/tests/AuthTestUtils';
-import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
-import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
-
-describe('Auth IP Authorization Flow', () => {
- let harness: ApiTestHarness;
- beforeAll(async () => {
- harness = await createAuthHarness();
- });
- beforeEach(async () => {
- await harness.reset();
- await clearTestEmails(harness);
- });
- afterAll(async () => {
- await harness?.shutdown();
- });
- it('validates the complete IP authorization flow', async () => {
- const email = createUniqueEmail('ip-auth-flow');
- const password = 'a-strong-password';
- const reg = await registerUser(harness, {
- email,
- username: createUniqueUsername('ipflow'),
- global_name: 'IP Auth Flow User',
- password,
- date_of_birth: '2000-01-01',
- consent: true,
- });
- await clearTestEmails(harness);
- const newIP = '10.20.30.40';
- const ipAuthResp = await createBuilderWithoutAuth<{
- code?: string;
- ticket?: string;
- ip_authorization_required?: boolean;
- email?: string;
- resend_available_in?: number;
- message?: string;
- }>(harness)
- .post('/auth/login')
- .body({email, password})
- .header('x-forwarded-for', newIP)
- .expect(403)
- .execute();
- expect(ipAuthResp.ip_authorization_required).toBe(true);
- expect(ipAuthResp.ticket).toBeTruthy();
- expect(ipAuthResp.email).toBe(email);
- const emails = await listTestEmails(harness, {recipient: email});
- const ipAuthEmail = findLastTestEmail(emails, 'ip_authorization');
- expect(ipAuthEmail).not.toBeNull();
- const authToken = ipAuthEmail?.metadata['token'];
- expect(authToken).toBeTruthy();
- await createBuilderWithoutAuth(harness)
- .post('/auth/authorize-ip')
- .body({token: authToken})
- .header('x-forwarded-for', newIP)
- .expect(204)
- .execute();
- const loginResp = await createBuilderWithoutAuth<{
- token?: string;
- user_id?: string;
- }>(harness)
- .post('/auth/login')
- .body({email, password})
- .header('x-forwarded-for', newIP)
- .execute();
- expect(loginResp.token).toBeTruthy();
- expect(loginResp.user_id).toBe(reg.user_id);
- });
-});
diff --git a/fluxer_api/src/api/auth/tests/LoginInviteInvalidCode.test.ts b/fluxer_api/src/api/auth/tests/LoginInviteInvalidCode.test.ts
deleted file mode 100644
index 37916e7d0..000000000
--- a/fluxer_api/src/api/auth/tests/LoginInviteInvalidCode.test.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {createAuthHarness, createTestAccount, loginUser} from '@app/api/auth/tests/AuthTestUtils';
-import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {createBuilder} from '@app/api/test/TestRequestBuilder';
-import type {GuildResponse} from '@fluxer/schema/src/domains/guild/GuildResponseSchemas';
-import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
-
-describe('Auth login with invalid invite code', () => {
- let harness: ApiTestHarness;
- beforeAll(async () => {
- harness = await createAuthHarness();
- });
- beforeEach(async () => {
- await harness.reset();
- });
- afterAll(async () => {
- await harness?.shutdown();
- });
- it('login with invalid invite code succeeds but does not add guilds', async () => {
- const member = await createTestAccount(harness);
- const login = await loginUser(harness, {
- email: member.email,
- password: member.password,
- invite_code: 'invalidcode123',
- });
- expect('mfa' in login).toBe(false);
- if (!('mfa' in login)) {
- const nonMfaLogin = login as {
- user_id: string;
- token: string;
- };
- expect(nonMfaLogin.token).toBeTruthy();
- }
- if (!('mfa' in login)) {
- const nonMfaLogin = login as {
- user_id: string;
- token: string;
- };
- const guilds = await createBuilder<Array<GuildResponse>>(harness, nonMfaLogin.token)
- .get('/users/@me/guilds')
- .execute();
- expect(guilds.length).toBe(0);
- }
- });
-});
diff --git a/fluxer_api/src/api/auth/tests/WebAuthnCredentialRegister.test.ts b/fluxer_api/src/api/auth/tests/WebAuthnCredentialRegister.test.ts
deleted file mode 100644
index c8e17e3ee..000000000
--- a/fluxer_api/src/api/auth/tests/WebAuthnCredentialRegister.test.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {createAuthHarness, createTestAccount} from '@app/api/auth/tests/AuthTestUtils';
-import {
- createRegistrationResponse,
- createTotpSecret,
- createWebAuthnDevice,
- generateTotpCode,
- type WebAuthnCredentialMetadata,
- type WebAuthnRegistrationOptions,
-} from '@app/api/auth/tests/WebAuthnTestUtils';
-import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {createBuilder} from '@app/api/test/TestRequestBuilder';
-import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
-
-describe('WebAuthn credential registration', () => {
- let harness: ApiTestHarness;
- beforeAll(async () => {
- harness = await createAuthHarness();
- });
- beforeEach(async () => {
- await harness.reset();
- });
- afterAll(async () => {
- await harness?.shutdown();
- });
- it('validates the WebAuthn credential registration flow', async () => {
- const account = await createTestAccount(harness);
- const device = createWebAuthnDevice();
- const secret = createTotpSecret();
- await createBuilder(harness, account.token)
- .post('/users/@me/mfa/totp/enable')
- .body({secret, code: generateTotpCode(secret), password: account.password})
- .execute();
- const regOptions = await createBuilder<WebAuthnRegistrationOptions>(harness, account.token)
- .post('/users/@me/mfa/webauthn/credentials/registration-options')
- .body({mfa_method: 'totp', mfa_code: generateTotpCode(secret)})
- .execute();
- expect(regOptions.challenge).toBeTruthy();
- expect(regOptions.rp.id).toBeTruthy();
- expect(regOptions.user.id).toBeTruthy();
- expect(regOptions.authenticatorSelection).toEqual({
- residentKey: 'preferred',
- requireResidentKey: false,
- userVerification: 'preferred',
- });
- if (regOptions.rp.id) {
- device.rpId = regOptions.rp.id;
- }
- const registrationResponse = createRegistrationResponse(device, regOptions, 'Test Passkey');
- await createBuilder(harness, account.token)
- .post('/users/@me/mfa/webauthn/credentials')
- .body({
- response: registrationResponse,
- challenge: regOptions.challenge,
- name: 'Test Passkey',
- })
- .expect(204)
- .execute();
- const credentials = await createBuilder<Array<WebAuthnCredentialMetadata>>(harness, account.token)
- .get('/users/@me/mfa/webauthn/credentials')
- .execute();
- expect(credentials).toHaveLength(1);
- expect(credentials[0].name).toBe('Test Passkey');
- expect(credentials[0].id).toBe(device.credentialId.toString('base64url'));
- });
-});
diff --git a/fluxer_api/src/api/auth/tests/WebAuthnPasswordlessLogin.test.ts b/fluxer_api/src/api/auth/tests/WebAuthnPasswordlessLogin.test.ts
deleted file mode 100644
index b8ee45faf..000000000
--- a/fluxer_api/src/api/auth/tests/WebAuthnPasswordlessLogin.test.ts
+++ /dev/null
@@ -1,92 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {createAuthHarness, createTestAccount} from '@app/api/auth/tests/AuthTestUtils';
-import {
- createAuthenticationResponse,
- createRegistrationResponse,
- createTotpSecret,
- createWebAuthnDevice,
- generateTotpCode,
- type WebAuthnAuthenticationOptions,
- type WebAuthnRegistrationOptions,
-} from '@app/api/auth/tests/WebAuthnTestUtils';
-import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
-import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
-
-describe('WebAuthn passwordless login', () => {
- let harness: ApiTestHarness;
- beforeAll(async () => {
- harness = await createAuthHarness();
- });
- beforeEach(async () => {
- await harness.reset();
- });
- afterAll(async () => {
- await harness?.shutdown();
- });
- it('validates passwordless login using WebAuthn with discoverable credentials', async () => {
- const account = await createTestAccount(harness);
- const device = createWebAuthnDevice();
- const secret = createTotpSecret();
- await createBuilder(harness, account.token)
- .post('/users/@me/mfa/totp/enable')
- .body({secret, code: generateTotpCode(secret), password: account.password})
- .execute();
- const regOptions = await createBuilder<WebAuthnRegistrationOptions>(harness, account.token)
- .post('/users/@me/mfa/webauthn/credentials/registration-options')
- .body({mfa_method: 'totp', mfa_code: generateTotpCode(secret)})
- .execute();
- if (regOptions.rp.id) {
- device.rpId = regOptions.rp.id;
- }
- const registrationResponse = createRegistrationResponse(device, regOptions, 'Passwordless Passkey');
- await createBuilder(harness, account.token)
- .post('/users/@me/mfa/webauthn/credentials')
- .body({
- response: registrationResponse,
- challenge: regOptions.challenge,
- name: 'Passwordless Passkey',
- mfa_method: 'totp',
- mfa_code: generateTotpCode(secret),
- })
- .expect(204)
- .execute();
- await createBuilder(harness, account.token)
- .post('/users/@me/mfa/totp/disable')
- .body({
- code: generateTotpCode(secret),
- mfa_method: 'totp',
- mfa_code: generateTotpCode(secret),
- })
- .expect(204)
- .execute();
- const discoverableOptions = await createBuilderWithoutAuth<WebAuthnAuthenticationOptions>(harness)
- .post('/auth/webauthn/authentication-options')
- .body(null)
- .execute();
- expect(discoverableOptions.challenge).toBeTruthy();
- expect(discoverableOptions.rpId).toBeTruthy();
- expect(discoverableOptions.userVerification).toBe('required');
- if (discoverableOptions.rpId) {
- device.rpId = discoverableOptions.rpId;
- }
- const discoverableAssertion = createAuthenticationResponse(device, discoverableOptions);
- const passkeyLogin = await createBuilderWithoutAuth<{
- token: string;
- }>(harness)
- .post('/auth/webauthn/authenticate')
- .body({
- response: discoverableAssertion,
- challenge: discoverableOptions.challenge,
- })
- .execute();
- expect(passkeyLogin.token).toBeTruthy();
- const userInfo = await createBuilder<{
- id: string;
- }>(harness, passkeyLogin.token)
- .get('/users/@me')
- .execute();
- expect(userInfo.id).toBe(account.userId);
- });
-});
diff --git a/fluxer_api/src/api/middleware/tests/PublicRouteRateLimits.test.ts b/fluxer_api/src/api/middleware/tests/PublicRouteRateLimits.test.ts
deleted file mode 100644
index a69882d3d..000000000
--- a/fluxer_api/src/api/middleware/tests/PublicRouteRateLimits.test.ts
+++ /dev/null
@@ -1,153 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {createHash} from 'node:crypto';
-import {BlueskyOAuthController} from '@app/api/bluesky/BlueskyOAuthController';
-import type {IBlueskyOAuthService} from '@app/api/bluesky/IBlueskyOAuthService';
-import {RateLimitMiddleware} from '@app/api/middleware/RateLimitMiddleware';
-import {ConnectionRateLimitConfigs} from '@app/api/rate_limit_configs/ConnectionRateLimitConfig';
-import type {HonoApp, HonoEnv} from '@app/api/types/HonoEnv';
-import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
-import type {
- BucketConfig,
- IRateLimitService,
- RateLimitConfig,
- RateLimitResult,
-} from '@pkgs/rate_limit/src/IRateLimitService';
-import {Hono} from 'hono';
-import {describe, expect, test} from 'vitest';
-
-const CLIENT_IP = '203.0.113.10';
-const HTTP_TOO_MANY_REQUESTS = 429;
-const RATE_LIMIT_MIDDLEWARE_SOURCE = String(RateLimitMiddleware(ConnectionRateLimitConfigs.CONNECTION_LIST));
-
-interface BucketCheck {
- bucket: string;
- limit: number;
- windowMs: number;
-}
-
-function allowedResult(limit: number): RateLimitResult {
- return {
- allowed: true,
- limit,
- remaining: limit - 1,
- resetTime: new Date(Date.now() + 60000),
- resetAfterDecimal: 60,
- };
-}
-
-class RecordingRateLimitService implements IRateLimitService {
- readonly bucketChecks: Array<BucketCheck> = [];
- readonly globalIdentifiers: Array<string> = [];
- denyBuckets = false;
-
- async checkLimit(config: RateLimitConfig): Promise<RateLimitResult> {
- return allowedResult(config.maxAttempts);
- }
-
- async peekLimit(config: RateLimitConfig): Promise<RateLimitResult> {
- return allowedResult(config.maxAttempts);
- }
-
- async checkBucketLimit(bucket: string, config: BucketConfig): Promise<RateLimitResult> {
- this.bucketChecks.push({bucket, limit: config.limit, windowMs: config.windowMs});
- return {...allowedResult(config.limit), allowed: !this.denyBuckets, remaining: this.denyBuckets ? 0 : 1};
- }
-
- async checkGlobalLimit(identifier: string, limit: number): Promise<RateLimitResult> {
- this.globalIdentifiers.push(identifier);
- return allowedResult(limit);
- }
-
- async resetLimit(_identifier: string): Promise<void> {}
-
- async clearLimitsByIdentifierPrefix(_identifierPrefix: string): Promise<number> {
- return 0;
- }
-}
-
-const blueskyOAuthService = {
- clientMetadata: {client_id: 'https://fluxer.test/v1/connections/bluesky/client-metadata.json'},
- jwks: {keys: []},
-} as unknown as IBlueskyOAuthService;
-
-interface Harness {
- app: HonoApp;
- service: RecordingRateLimitService;
-}
-
-function buildHarness(register: (app: HonoApp) => void): Harness {
- const service = new RecordingRateLimitService();
- const app = new Hono<HonoEnv>();
- app.use('*', async (ctx, next) => {
- ctx.set('rateLimitService', service);
- ctx.set('blueskyOAuthService', blueskyOAuthService);
- await next();
- });
- register(app);
- return {app, service};
-}
-
-async function callRoute(harness: Harness, path: string): Promise<Response> {
- return await harness.app.request(`http://localhost${path}`, {
- headers: {
- 'x-forwarded-for': CLIENT_IP,
- 'x-fluxer-test-enable-rate-limits': 'true',
- },
- });
-}
-
-function routesWithoutRateLimit(register: (app: HonoApp) => void): Array<string> {
- const app = new Hono<HonoEnv>();
- register(app);
- const registered = new Set<string>();
- const throttled = new Set<string>();
- for (const route of app.routes) {
- const shape = `${route.method} ${route.path}`;
- registered.add(shape);
- if (String(route.handler) === RATE_LIMIT_MIDDLEWARE_SOURCE) {
- throttled.add(shape);
- }
- }
- return [...registered].filter((shape) => !throttled.has(shape)).sort();
-}
-
-function bucketHash(bucket: string): string {
- return createHash('sha256').update(bucket).digest('hex').slice(0, 16);
-}
-
-describe('public route rate limits', () => {
- test('every Bluesky OAuth route declares a rate limit bucket', () => {
- expect(routesWithoutRateLimit(BlueskyOAuthController)).toEqual([]);
- });
-
- test('the Bluesky client documents share one bucket keyed by client IP', async () => {
- const harness = buildHarness(BlueskyOAuthController);
-
- const metadata = await callRoute(harness, '/connections/bluesky/client-metadata.json');
- const jwks = await callRoute(harness, '/connections/bluesky/jwks.json');
-
- expect(metadata.status).toBe(200);
- expect(jwks.status).toBe(200);
- expect(harness.service.bucketChecks).toEqual([
- {bucket: `ip:${CLIENT_IP}:connection:bluesky:client_document`, limit: 60, windowMs: 60000},
- {bucket: `ip:${CLIENT_IP}:connection:bluesky:client_document`, limit: 60, windowMs: 60000},
- ]);
- expect(harness.service.globalIdentifiers).toEqual([`ip:${CLIENT_IP}`, `ip:${CLIENT_IP}`]);
- });
-
- test('a denied bucket answers a Bluesky client document with 429 and the bucket hash', async () => {
- const harness = buildHarness(BlueskyOAuthController);
- harness.service.denyBuckets = true;
-
- const response = await callRoute(harness, '/connections/bluesky/client-metadata.json');
- const body = (await response.json()) as {code?: string};
-
- expect(response.status).toBe(HTTP_TOO_MANY_REQUESTS);
- expect(body.code).toBe(APIErrorCodes.RATE_LIMITED);
- expect(response.headers.get('X-RateLimit-Bucket')).toBe(
- bucketHash(ConnectionRateLimitConfigs.BLUESKY_CLIENT_DOCUMENT.bucket),
- );
- expect(response.headers.get('X-RateLimit-Scope')).toBe('user');
- });
-});