A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
test(api/auth): cover setup tokens, codes, recovery and IP limit
Hampus7574f302ecf1
diff --git a/fluxer_api/src/api/auth/tests/EmailCodeAttemptRace.test.ts b/fluxer_api/src/api/auth/tests/EmailCodeAttemptRace.test.tsnew file mode 100644index 000000000..c083e6035--- /dev/null+++ b/fluxer_api/src/api/auth/tests/EmailCodeAttemptRace.test.ts@@ -0,0 +1,262 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {+ ACCOUNT_CODE_FAILURES_DAILY_CAP,+ assertEmailSendAllowed,+ CODE_FAILURES_DAILY_CAP,+ enforceLookupHardLimits,+ recordAccountCodeFailure,+ recordAddressCodeFailure,+ requesterNetworkKey,+} from '@app/api/auth/AccountBudgets';+import {normalizeEmailKey} from '@app/api/auth/AccountCodes';+import {+ clearTestEmails,+ createEmailCodeSudoBody,+ createTestAccount,+ createUniqueEmail,+ findLastTestEmail,+ listTestEmails,+} from '@app/api/auth/tests/AuthTestUtils';+import {createUserID} from '@app/api/BrandedTypes';+import {getKVClient} from '@app/api/middleware/ServiceRegistry';+import {+ getInstanceConfigRepository,+ getRateLimitService,+ getUserRepository,+} from '@app/api/middleware/ServiceSingletons';+import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';+import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';+import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';+import {EmailCodeResendCooldownError} from '@fluxer/errors/src/domains/auth/EmailCodeResendCooldownError';+import {RateLimitError} from '@fluxer/errors/src/domains/core/RateLimitError';+import {MockKVProvider} from '@pkgs/kv_client/src/testing/MockKVProvider';+import type {IRateLimitService} from '@pkgs/rate_limit/src/IRateLimitService';+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';++const GUESSES = 40;+const MAX_ATTEMPTS = 5;++function wrongGuesses(code: string): Array<string> {+ return Array.from({length: GUESSES}, (_, index) =>+ ((Number(code) + index + 1) % 1_000_000).toString().padStart(6, '0'),+ );+}++function countChecked(results: Array<{json?: {code?: string} | null}>): number {+ return results.filter((result) => result.json?.code === APIErrorCodes.INVALID_SIGN_IN_CODE).length;+}++describe('Email code attempt cap under concurrency', () => {+ let harness: ApiTestHarness;+ beforeAll(async () => {+ harness = await createApiTestHarness();+ });+ beforeEach(async () => {+ await harness.reset();+ await getInstanceConfigRepository().updateAuthConfig({identifier_first: true});+ await clearTestEmails(harness);+ });+ afterAll(async () => {+ await harness?.shutdown();+ });++ async function startSignIn(email: string): Promise<{ticket: string; code: string}> {+ const {ticket} = await createBuilderWithoutAuth<{ticket: string}>(harness)+ .post('/auth/identify')+ .body({email})+ .execute();+ await createBuilderWithoutAuth(harness).post('/auth/email-code/send').body({ticket}).execute();+ const code = findLastTestEmail(await listTestEmails(harness, {recipient: email}), 'sign_in_code')!.metadata[+ 'code'+ ]!;+ return {ticket, code};+ }++ async function createPasswordlessAccount() {+ const account = await createTestAccount(harness);+ const user = await getUserRepository().findUniqueAssert(createUserID(BigInt(account.userId)));+ await getUserRepository().patchUpsert(user.id, {password_hash: null}, user.toRow());+ return account;+ }++ it('checks at most five sign-in guesses per code even when they arrive together', async () => {+ const account = await createPasswordlessAccount();+ const {ticket, code} = await startSignIn(account.email);+ const results = await Promise.all(+ wrongGuesses(code).map((guess) =>+ createBuilderWithoutAuth<{code?: string}>(harness)+ .post('/auth/email-code/verify')+ .body({ticket, code: guess})+ .executeRaw(),+ ),+ );+ expect(countChecked(results)).toBeLessThanOrEqual(MAX_ATTEMPTS);+ const last = await createBuilderWithoutAuth<{code?: string; token?: string}>(harness)+ .post('/auth/email-code/verify')+ .body({ticket, code})+ .executeRaw();+ expect(last.json?.token).toBeUndefined();+ expect(last.json?.code).toBe(APIErrorCodes.SIGN_IN_CODE_EXPIRED);+ });++ it('accepts a correct sign-in code exactly once', async () => {+ const account = await createPasswordlessAccount();+ const {ticket, code} = await startSignIn(account.email);+ const results = await Promise.all(+ Array.from({length: 4}, () =>+ createBuilderWithoutAuth<{code?: string; token?: string; ticket?: string}>(harness)+ .post('/auth/email-code/verify')+ .body({ticket, code})+ .executeRaw(),+ ),+ );+ expect(results.filter((result) => result.json?.token || result.json?.ticket).length).toBe(1);+ });++ it('checks at most five claim confirmation guesses even when they arrive together', async () => {+ const account = await createBuilderWithoutAuth<{token: string}>(harness)+ .post('/auth/register')+ .body({username: 'racer', consent: true, date_of_birth: '1995-05-05'})+ .execute();+ const email = createUniqueEmail('claim-race');+ await createBuilder(harness, account.token).post('/users/@me/claim').body({email}).execute();+ const code = findLastTestEmail(await listTestEmails(harness, {recipient: email}), 'email_verification_code')!+ .metadata['code']!;+ const results = await Promise.all(+ wrongGuesses(code).map((guess) =>+ createBuilder<{code?: string}>(harness, account.token)+ .post('/users/@me/email-verification/confirm')+ .body({code: guess})+ .executeRaw(),+ ),+ );+ expect(countChecked(results)).toBeLessThanOrEqual(MAX_ATTEMPTS);+ const last = await createBuilder<{code?: string; verified?: boolean}>(harness, account.token)+ .post('/users/@me/email-verification/confirm')+ .body({code})+ .executeRaw();+ expect(last.json?.code).toBe(APIErrorCodes.SIGN_IN_CODE_EXPIRED);+ });++ it('checks at most five sudo code guesses even when they arrive together', async () => {+ const account = await createTestAccount(harness);+ await createBuilder(harness, '')+ .post(`/test/users/${account.userId}/security-flags`)+ .body({email_verified: true})+ .execute();+ const user = await getUserRepository().findUniqueAssert(createUserID(BigInt(account.userId)));+ await getUserRepository().patchUpsert(user.id, {password_hash: null}, user.toRow());+ const sudo = await createEmailCodeSudoBody(harness, account);+ const results = await Promise.all(+ wrongGuesses(sudo.email_code).map((guess) =>+ createBuilder<{code?: string}>(harness, account.token)+ .post('/users/@me/disable')+ .body({...sudo, email_code: guess})+ .executeRaw(),+ ),+ );+ expect(countChecked(results)).toBeLessThanOrEqual(MAX_ATTEMPTS);+ const last = await createBuilder<{code?: string}>(harness, account.token)+ .post('/users/@me/disable')+ .body(sudo)+ .executeRaw();+ expect(last.response.status).toBe(400);+ expect(last.json?.code).toBe(APIErrorCodes.UNKNOWN_SIGN_IN_TICKET);+ });++ it('stops sudo codes once wrong sudo codes reach the account cap', async () => {+ const account = await createTestAccount(harness);+ await createBuilder(harness, '')+ .post(`/test/users/${account.userId}/security-flags`)+ .body({email_verified: true})+ .execute();+ const user = await getUserRepository().findUniqueAssert(createUserID(BigInt(account.userId)));+ await getUserRepository().patchUpsert(user.id, {password_hash: null}, user.toRow());+ const env = {kv: getKVClient(), rateLimit: getRateLimitService(), enforce: true};+ for (let failure = 1; failure < ACCOUNT_CODE_FAILURES_DAILY_CAP; failure++) {+ await recordAccountCodeFailure(env, account.userId);+ }+ const sudo = await createEmailCodeSudoBody(harness, account);+ await createBuilder(harness, account.token)+ .post('/users/@me/disable')+ .body({...sudo, email_code: wrongGuesses(sudo.email_code)[0]})+ .expect(400, APIErrorCodes.INVALID_SIGN_IN_CODE)+ .execute();+ await createBuilder(harness, account.token)+ .post('/users/@me/sudo/email-code')+ .header('x-fluxer-test-enable-rate-limits', 'true')+ .body(null)+ .expect(429, APIErrorCodes.EMAIL_CODE_RESEND_COOLDOWN)+ .execute();+ });+});++describe('Daily code failure caps', () => {+ const allowAll: IRateLimitService = {+ checkLimit: async () => ({allowed: true, limit: 0, remaining: 0, resetTime: new Date()}),+ } as unknown as IRateLimitService;++ async function failFrom(env: Parameters<typeof recordAddressCodeFailure>[0], emailKey: string, clientIp: string) {+ for (let failure = 0; failure < CODE_FAILURES_DAILY_CAP; failure++) {+ await assertEmailSendAllowed(env, {emailKey, requester: 'unknown', clientIp});+ await recordAddressCodeFailure(env, {emailKey, network: requesterNetworkKey(clientIp)});+ }+ }++ it('stops unknown requesters on the failing IPv4 /24 only', async () => {+ const env = {kv: new MockKVProvider(), rateLimit: allowAll, enforce: true};+ const emailKey = normalizeEmailKey('[email protected]');+ await failFrom(env, emailKey, '203.0.113.9');+ await expect(+ assertEmailSendAllowed(env, {emailKey, requester: 'unknown', clientIp: '203.0.113.77'}),+ ).rejects.toBeInstanceOf(EmailCodeResendCooldownError);+ await expect(+ assertEmailSendAllowed(env, {emailKey, requester: 'unknown', clientIp: '198.51.100.4'}),+ ).resolves.toBeUndefined();+ await expect(+ assertEmailSendAllowed(env, {emailKey, requester: 'known', clientIp: '203.0.113.9'}),+ ).resolves.toBeUndefined();+ });++ it('stops unknown requesters on the failing IPv6 /48 only', async () => {+ const env = {kv: new MockKVProvider(), rateLimit: allowAll, enforce: true};+ const emailKey = normalizeEmailKey('[email protected]');+ await failFrom(env, emailKey, '2001:db8:1:1::1');+ await expect(+ assertEmailSendAllowed(env, {emailKey, requester: 'unknown', clientIp: '2001:db8:1:ffff::2'}),+ ).rejects.toBeInstanceOf(EmailCodeResendCooldownError);+ await expect(+ assertEmailSendAllowed(env, {emailKey, requester: 'unknown', clientIp: '2001:db8:2::1'}),+ ).resolves.toBeUndefined();+ });++ it('stops every code to an account once its own wrong codes reach the account cap', async () => {+ const env = {kv: new MockKVProvider(), rateLimit: allowAll, enforce: true};+ const emailKey = normalizeEmailKey('[email protected]');+ const userId = '1234567890';+ for (let failure = 0; failure < ACCOUNT_CODE_FAILURES_DAILY_CAP; failure++) {+ await assertEmailSendAllowed(env, {emailKey, requester: 'known', clientIp: '203.0.113.9', userId});+ await recordAccountCodeFailure(env, userId);+ }+ for (const requester of ['known', 'unknown'] as const) {+ await expect(+ assertEmailSendAllowed(env, {emailKey, requester, clientIp: '198.51.100.4', userId}),+ ).rejects.toBeInstanceOf(EmailCodeResendCooldownError);+ }+ await expect(+ assertEmailSendAllowed(env, {emailKey, requester: 'unknown', clientIp: '198.51.100.4'}),+ ).resolves.toBeUndefined();+ });++ it('caps lookups at 30 per IP and 300 per subnet', async () => {+ const env = {kv: new MockKVProvider(), rateLimit: countingRateLimit(), enforce: true};+ for (let lookup = 0; lookup < 30; lookup++) await enforceLookupHardLimits(env, '203.0.113.1');+ await expect(enforceLookupHardLimits(env, '203.0.113.1')).rejects.toBeInstanceOf(RateLimitError);+ for (let host = 2; host <= 10; host++) {+ for (let lookup = 0; lookup < 30; lookup++) await enforceLookupHardLimits(env, `203.0.113.${host}`);+ }+ await expect(enforceLookupHardLimits(env, '203.0.113.11')).rejects.toBeInstanceOf(RateLimitError);+ await expect(enforceLookupHardLimits(env, '198.51.100.1')).resolves.toBeUndefined();+ });+});diff --git a/fluxer_api/src/api/auth/tests/LoginIpRateLimit.test.ts b/fluxer_api/src/api/auth/tests/LoginIpRateLimit.test.tsnew file mode 100644index 000000000..b00fc1ef7--- /dev/null+++ b/fluxer_api/src/api/auth/tests/LoginIpRateLimit.test.ts@@ -0,0 +1,58 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {createAuthHarness, createTestAccount} from '@app/api/auth/tests/AuthTestUtils';+import {getRateLimitService} from '@app/api/middleware/ServiceSingletons';+import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';+import {createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';+import {getSameIpDecisionKey} from '@fluxer/ip_utils/src/IpAddress';+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';++const CLIENT_IP = '127.0.0.1';+const IP_LIMIT = {+ identifier: `login:ip:${getSameIpDecisionKey(CLIENT_IP) ?? CLIENT_IP}`,+ maxAttempts: 10,+ windowMs: 30 * 60 * 1000,+};++describe('per-IP sign-in limit', () => {+ let harness: ApiTestHarness;++ beforeAll(async () => {+ harness = await createAuthHarness();+ });++ beforeEach(async () => {+ await harness.reset();+ await getRateLimitService().resetLimit(IP_LIMIT.identifier);+ });++ afterAll(async () => {+ await harness?.shutdown();+ });++ const signIn = (email: string, password: string) =>+ createBuilderWithoutAuth(harness)+ .post('/auth/login')+ .header('x-forwarded-for', CLIENT_IP)+ .body({email, password})+ .expect(200);++ it('does not spend the IP budget on correct passwords', async () => {+ for (let i = 0; i < 3; i++) {+ const account = await createTestAccount(harness);+ await signIn(account.email, account.password).execute();+ }+ expect((await getRateLimitService().peekLimit(IP_LIMIT)).remaining).toBe(IP_LIMIT.maxAttempts);+ });++ it('spends the IP budget on wrong passwords', async () => {+ const account = await createTestAccount(harness);+ await createBuilderWithoutAuth(harness)+ .post('/auth/login')+ .header('x-forwarded-for', CLIENT_IP)+ .body({email: account.email, password: 'WrongPassword123!'})+ .expect(400)+ .execute();+ expect((await getRateLimitService().peekLimit(IP_LIMIT)).remaining).toBe(IP_LIMIT.maxAttempts - 1);+ });+});diff --git a/fluxer_api/src/api/auth/tests/SetupTokenAccountPaths.test.ts b/fluxer_api/src/api/auth/tests/SetupTokenAccountPaths.test.tsnew file mode 100644index 000000000..db445d6fc--- /dev/null+++ b/fluxer_api/src/api/auth/tests/SetupTokenAccountPaths.test.ts@@ -0,0 +1,246 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {createHash, randomBytes} from 'node:crypto';+import {+ clearTestEmails,+ createUniqueEmail,+ createUniqueUsername,+ disableSso,+ enableSso,+ findLastTestEmail,+ listTestEmails,+} from '@app/api/auth/tests/AuthTestUtils';+import {createUserID} from '@app/api/BrandedTypes';+import {Config} from '@app/api/Config';+import {getInstanceConfigRepository, getUserRepository} from '@app/api/middleware/ServiceSingletons';+import {RateLimitConfigs} from '@app/api/RateLimitConfig';+import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';+import {HTTP_STATUS} from '@app/api/test/TestConstants';+import {createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';+import {AdminACLs} from '@fluxer/constants/src/AdminACLs';+import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';+import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';+import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it} from 'vitest';++const SETUP_TOKEN = 'setup-token-for-tests-0123456789-abcdefghijklmnopqrstuvwxyz';+const MARKETING_KEY = 'marketing-test-key-0123456789abcdefghijkl';+const VISITOR_IP = '192.0.2.44';++interface GateResponse {+ user_id?: string;+ token?: string;+ ticket?: string;+ purpose?: string;+ handoff_code?: string;+ code?: string;+ errors?: Array<{path: string; code: string}>;+}++describe('Setup token on every way to create an account', () => {+ let harness: ApiTestHarness;+ const originalSelfHosted = Config.instance.selfHosted;+ const originalSetupToken = Config.instance.setup.token;+ const originalTrustedCallers = Config.internal.trustedCallers;+ beforeAll(async () => {+ harness = await createApiTestHarness();+ });+ beforeEach(async () => {+ await harness.reset();+ await clearTestEmails(harness);+ const repository = getInstanceConfigRepository();+ await repository.updateCaptchaConfig({enabled: true});+ await repository.updateAuthConfig({identifier_first: true, instant_accounts: {enabled: true}});+ Config.internal.trustedCallers = [+ ...originalTrustedCallers,+ {+ name: 'marketing',+ key: MARKETING_KEY,+ buckets: [+ RateLimitConfigs.AUTH_REGISTER_HANDOFF.bucket,+ RateLimitConfigs.AUTH_REGISTER_HANDOFF_CHALLENGE.bucket,+ ],+ },+ ];+ });+ afterEach(() => {+ Config.instance.selfHosted = originalSelfHosted;+ Config.instance.setup.token = originalSetupToken;+ Config.internal.trustedCallers = originalTrustedCallers;+ });+ afterAll(async () => {+ await harness?.shutdown();+ });++ function openSetupTokenGate(): void {+ Config.instance.selfHosted = true;+ Config.instance.setup.token = SETUP_TOKEN;+ }++ async function post(+ path: string,+ body: Record<string, unknown>,+ headers: Record<string, string> = {},+ ): Promise<{status: number; json: GateResponse}> {+ const builder = createBuilderWithoutAuth<GateResponse>(harness).post(path).body(body);+ for (const [name, value] of Object.entries(headers)) builder.header(name, value);+ const {response, json} = await builder.executeRaw();+ return {status: response.status, json};+ }++ function expectSetupTokenRequired({status, json}: {status: number; json: GateResponse}): void {+ expect(status).toBe(HTTP_STATUS.BAD_REQUEST);+ expect((json.errors ?? []).map(({path, code}) => ({path, code}))).toEqual([+ {path: 'setup_token', code: ValidationErrorCodes.SETUP_TOKEN_REQUIRED},+ ]);+ }++ function handoffHeaders(): Record<string, string> {+ return {+ 'x-fluxer-internal-key': MARKETING_KEY,+ 'x-fluxer-client-ip': VISITOR_IP,+ 'x-forwarded-for': '10.9.9.9',+ };+ }++ function nonceWithHash(): {nonce: string; hash: string} {+ const nonce = randomBytes(32).toString('base64url');+ return {nonce, hash: createHash('sha256').update(nonce).digest('hex')};+ }++ async function identify(email: string): Promise<string> {+ const {status, json} = await post('/auth/identify', {email});+ expect(status).toBe(HTTP_STATUS.OK);+ return json.ticket!;+ }++ async function signUpCode(email: string): Promise<string> {+ const record = findLastTestEmail(await listTestEmails(harness, {recipient: email}), 'sign_up_code');+ expect(record).not.toBeNull();+ return record!.metadata['code']!;+ }++ function registerWithSetupToken(): Promise<{status: number; json: GateResponse}> {+ return post('/auth/register', {+ email: createUniqueEmail('setupadmin'),+ username: createUniqueUsername('setupadmin'),+ global_name: 'Setup Admin',+ date_of_birth: '2000-01-01',+ consent: true,+ setup_token: SETUP_TOKEN,+ });+ }++ async function registerAdmin(): Promise<string> {+ const {status, json} = await registerWithSetupToken();+ expect(status).toBe(HTTP_STATUS.OK);+ return json.user_id!;+ }++ async function completeSso(prefix: string): Promise<{status: number; json: GateResponse}> {+ const started = await post('/auth/sso/start', {});+ expect(started.status).toBe(HTTP_STATUS.OK);+ const state = (started.json as GateResponse & {state?: string}).state;+ return post('/auth/sso/complete', {code: `${prefix}-${Date.now()}@example.com`, state});+ }++ it('sends no sign-up code before the first admin exists', async () => {+ openSetupTokenGate();+ const email = createUniqueEmail('gatedcode');+ const ticket = await identify(email);+ expectSetupTokenRequired(await post('/auth/email-code/send', {ticket}));+ expect(await listTestEmails(harness, {recipient: email})).toEqual([]);+ });++ it('creates no account from a sign-up code that was sent before the gate applied', async () => {+ const email = createUniqueEmail('earlycode');+ const ticket = await identify(email);+ expect((await post('/auth/email-code/send', {ticket})).status).toBe(HTTP_STATUS.OK);+ const code = await signUpCode(email);+ openSetupTokenGate();+ expectSetupTokenRequired(await post('/auth/email-code/verify', {ticket, code, consent: true}));+ expect(await getUserRepository().findByEmail(email)).toBeNull();+ await expect(getInstanceConfigRepository().isAdminBootstrapped()).resolves.toBe(false);+ });++ it('creates no account without an email before the first admin exists', async () => {+ openSetupTokenGate();+ expectSetupTokenRequired(await post('/auth/register', {global_name: 'Newcomer', consent: true}));+ expect(await getUserRepository().findUsersByUsername('Newcomer')).toEqual([]);+ });++ it('starts no account from the website before the first admin exists', async () => {+ openSetupTokenGate();+ const {hash} = nonceWithHash();+ expectSetupTokenRequired(+ await post('/auth/register/handoff', {global_name: 'Newcomer', nonce_hash: hash}, handoffHeaders()),+ );+ });++ it('creates no account from a website handoff that was started before the gate applied', async () => {+ const {nonce, hash} = nonceWithHash();+ const started = await post('/auth/register/handoff', {global_name: 'Newcomer', nonce_hash: hash}, handoffHeaders());+ expect(started.status).toBe(HTTP_STATUS.OK);+ openSetupTokenGate();+ expectSetupTokenRequired(+ await post('/auth/register/handoff/redeem', {handoff_code: started.json.handoff_code, nonce, consent: true}),+ );+ expect(await getUserRepository().findUsersByUsername('Newcomer')).toEqual([]);+ });++ it('opens every way to create an account once the setup token holder is the admin', async () => {+ openSetupTokenGate();+ const adminId = await registerAdmin();+ const admin = await getUserRepository().findUniqueAssert(createUserID(BigInt(adminId)));+ expect([...admin.acls]).toEqual([AdminACLs.WILDCARD]);+ const email = createUniqueEmail('aftersetup');+ const ticket = await identify(email);+ const beforeFinish = await post('/auth/email-code/send', {ticket});+ expect(beforeFinish.status).toBe(HTTP_STATUS.FORBIDDEN);+ expect(beforeFinish.json.code).toBe(APIErrorCodes.REGISTRATION_CLOSED);+ expect((await post('/auth/register', {global_name: 'Early', consent: true})).json.code).toBe(+ APIErrorCodes.REGISTRATION_CLOSED,+ );+ await getInstanceConfigRepository().setAppPublicConfig({setup: {configured: true}});+ expect((await post('/auth/email-code/send', {ticket})).status).toBe(HTTP_STATUS.OK);+ const signedUp = await post('/auth/email-code/verify', {ticket, code: await signUpCode(email), consent: true});+ expect(signedUp.status).toBe(HTTP_STATUS.OK);+ const emailUser = await getUserRepository().findUniqueAssert(createUserID(BigInt(signedUp.json.user_id!)));+ expect([...emailUser.acls]).toEqual([]);+ const instant = await post('/auth/register', {global_name: 'Newcomer', consent: true});+ expect(instant.status).toBe(HTTP_STATUS.OK);+ const {nonce, hash} = nonceWithHash();+ const started = await post('/auth/register/handoff', {global_name: 'Visitor', nonce_hash: hash}, handoffHeaders());+ expect(started.status).toBe(HTTP_STATUS.OK);+ const redeemed = await post('/auth/register/handoff/redeem', {+ handoff_code: started.json.handoff_code,+ nonce,+ consent: true,+ });+ expect(redeemed.status).toBe(HTTP_STATUS.OK);+ });++ it('lets the setup token create only one account when two sign-ups race', async () => {+ openSetupTokenGate();+ const results = await Promise.all([registerWithSetupToken(), registerWithSetupToken()]);+ expect(results.map(({status}) => status).sort()).toEqual([HTTP_STATUS.OK, HTTP_STATUS.FORBIDDEN]);+ expect(results.find(({status}) => status === HTTP_STATUS.FORBIDDEN)?.json.code).toBe(+ APIErrorCodes.REGISTRATION_CLOSED,+ );+ });++ it('creates no SSO account until setup finishes', async () => {+ openSetupTokenGate();+ const admin = await registerWithSetupToken();+ expect(admin.status).toBe(HTTP_STATUS.OK);+ await enableSso(harness, admin.json.token!, {enforced: false});+ try {+ const beforeFinish = await completeSso('ssobeforesetup');+ expect(beforeFinish.status).toBe(HTTP_STATUS.FORBIDDEN);+ expect(beforeFinish.json.code).toBe(APIErrorCodes.REGISTRATION_CLOSED);+ await getInstanceConfigRepository().setAppPublicConfig({setup: {configured: true}});+ expect((await completeSso('ssoaftersetup')).status).toBe(HTTP_STATUS.OK);+ } finally {+ await disableSso(harness, admin.json.token!);+ }+ });+});diff --git a/fluxer_api/src/api/auth/tests/SquatterPasswordRecovery.test.ts b/fluxer_api/src/api/auth/tests/SquatterPasswordRecovery.test.tsnew file mode 100644index 000000000..eb9c1800d--- /dev/null+++ b/fluxer_api/src/api/auth/tests/SquatterPasswordRecovery.test.ts@@ -0,0 +1,192 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {+ clearTestEmails,+ createAuthHarness,+ createTotpSecret,+ createUniqueEmail,+ createUniqueUsername,+ findLastTestEmail,+ listTestEmails,+ registerUser,+ totpCodeNow,+} from '@app/api/auth/tests/AuthTestUtils';+import {createRegistrationResponse, createWebAuthnDevice} from '@app/api/auth/tests/WebAuthnTestUtils';+import {createUserID} from '@app/api/BrandedTypes';+import {getInstanceConfigRepository, getUserRepository} from '@app/api/middleware/ServiceSingletons';+import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';+import {HTTP_STATUS} from '@app/api/test/TestConstants';+import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';+import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';++const SQUATTER_IP = '192.0.2.61';+const SQUATTER_PASSWORD = 'a-strong-squatter-password-61';+const OWNER_PASSWORD = 'the-real-owner-password-62';++describe('An address someone else registered with a password', () => {+ let harness: ApiTestHarness;+ beforeAll(async () => {+ harness = await createAuthHarness();+ });+ beforeEach(async () => {+ await harness.reset();+ await clearTestEmails(harness);+ });+ afterAll(async () => {+ await harness?.shutdown();+ });++ async function squat(): Promise<{email: string; token: string; userId: string}> {+ const email = createUniqueEmail('squatted');+ const registered = await createBuilderWithoutAuth<{user_id: string; token: string}>(harness)+ .post('/auth/register')+ .header('x-forwarded-for', SQUATTER_IP)+ .body({+ email,+ username: createUniqueUsername('squatter'),+ password: SQUATTER_PASSWORD,+ date_of_birth: '1990-01-01',+ consent: true,+ })+ .execute();+ const me = await createBuilder<{verified: boolean}>(harness, registered.token).get('/users/@me').execute();+ expect(me.verified).toBe(false);+ return {email, token: registered.token, userId: registered.user_id};+ }++ async function expectNoFactor(token: string, path: string, body: Record<string, unknown>, method = 'post') {+ const builder = createBuilder<{code: string}>(harness, token);+ const request = method === 'put' ? builder.put(path) : builder.post(path);+ const {json} = await request.header('x-forwarded-for', SQUATTER_IP).body(body).expect(403).executeWithResponse();+ expect(json.code, path).toBe(APIErrorCodes.MFA_EMAIL_VERIFICATION_REQUIRED);+ }++ it('gives the squatter no way to add a second factor or a passkey on any route', async () => {+ const squatter = await squat();+ const secret = createTotpSecret();+ await expectNoFactor(squatter.token, '/users/@me/mfa/totp/enable', {+ secret,+ code: totpCodeNow(secret),+ password: SQUATTER_PASSWORD,+ });+ await expectNoFactor(squatter.token, '/users/@me/mfa/webauthn/credentials/registration-options', {+ password: SQUATTER_PASSWORD,+ });+ const device = createWebAuthnDevice();+ const challenge = Buffer.alloc(32, 7).toString('base64url');+ const response = createRegistrationResponse(+ device,+ {+ challenge,+ rp: {id: 'localhost', name: 'Fluxer'},+ user: {id: Buffer.from(squatter.userId).toString('base64url'), name: 'squatter', displayName: 'squatter'},+ } as Parameters<typeof createRegistrationResponse>[1],+ 'Squatter key',+ );+ await expectNoFactor(squatter.token, '/users/@me/mfa/webauthn/credentials', {+ response,+ challenge,+ name: 'Squatter key',+ password: SQUATTER_PASSWORD,+ });+ await expectNoFactor(+ squatter.token,+ '/users/@me/mfa/webauthn/two-factor',+ {enabled: true, password: SQUATTER_PASSWORD},+ 'put',+ );+ await expectNoFactor(squatter.token, '/users/@me/mfa/backup-codes', {+ regenerate: true,+ password: SQUATTER_PASSWORD,+ });+ await expectNoFactor(squatter.token, '/users/@me/mfa/backup-codes/challenge', {});+ const migration = await createBuilder(harness, squatter.token)+ .post('/users/@me/mfa/webauthn/migration/registration-options')+ .body({})+ .executeRaw();+ expect(migration.response.status).toBeGreaterThanOrEqual(400);+ const user = await getUserRepository().findUniqueAssert(createUserID(BigInt(squatter.userId)));+ expect(user.authenticatorTypes.size).toBe(0);+ expect(await getUserRepository().listWebAuthnCredentials(user.id)).toEqual([]);+ });++ it('lets the inbox owner take the account back with "Forgot your password?"', async () => {+ await getInstanceConfigRepository().updateAuthConfig({identifier_first: true});+ const squatter = await squat();+ const identify = await createBuilderWithoutAuth<{ticket: string; sign_in_method: string}>(harness)+ .post('/auth/identify')+ .body({email: squatter.email})+ .execute();+ expect(identify.sign_in_method).toBe('password');+ await createBuilderWithoutAuth(harness)+ .post('/auth/email-code/send')+ .body({ticket: identify.ticket})+ .expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.PASSWORD_SIGN_IN_REQUIRED)+ .execute();+ const grant = await createBuilder<{token: string}>(harness, '')+ .post('/test/oauth2/access-token')+ .body({user_id: squatter.userId, scopes: ['identify']})+ .execute();++ await clearTestEmails(harness);+ await createBuilderWithoutAuth(harness)+ .post('/auth/forgot')+ .body({email: squatter.email})+ .expect(HTTP_STATUS.NO_CONTENT)+ .execute();+ const resetMail = findLastTestEmail(await listTestEmails(harness, {recipient: squatter.email}), 'password_reset');+ expect(resetMail).not.toBeNull();+ const reset = await createBuilderWithoutAuth<{user_id: string; token: string}>(harness)+ .post('/auth/reset')+ .body({token: resetMail!.metadata['token'], password: OWNER_PASSWORD})+ .execute();+ expect(reset.user_id).toBe(squatter.userId);++ await createBuilder(harness, squatter.token).get('/users/@me').expect(HTTP_STATUS.UNAUTHORIZED).execute();+ await createBuilderWithoutAuth(harness)+ .post('/auth/login')+ .header('x-forwarded-for', SQUATTER_IP)+ .body({email: squatter.email, password: SQUATTER_PASSWORD})+ .expect(HTTP_STATUS.BAD_REQUEST)+ .execute();++ const user = await getUserRepository().findUniqueAssert(createUserID(BigInt(squatter.userId)));+ expect(user.emailVerified).toBe(false);+ expect((await getUserRepository().getAuthorizedIps(user.id)).map((entry) => entry.ip)).toContain(SQUATTER_IP);+ const oauth = await createBuilder(harness, `Bearer ${grant.token}`).get('/users/@me').executeRaw();+ expect(oauth.response.status).toBe(HTTP_STATUS.OK);++ await clearTestEmails(harness);+ await createBuilder(harness, reset.token).post('/users/@me/email-verification/send').body(null).execute();+ const code = findLastTestEmail(+ await listTestEmails(harness, {recipient: squatter.email}),+ 'email_verification_code',+ )!.metadata['code'];+ const confirmed = await createBuilder<{verified: boolean}>(harness, reset.token)+ .post('/users/@me/email-verification/confirm')+ .body({code})+ .execute();+ expect(confirmed.verified).toBe(true);+ });++ it('also takes back an address a squatter registered from an older client', async () => {+ const email = createUniqueEmail('old-client');+ const registered = await registerUser(harness, {+ email,+ username: createUniqueUsername('oldsquat'),+ password: SQUATTER_PASSWORD,+ date_of_birth: '1990-01-01',+ consent: true,+ });+ await createBuilderWithoutAuth(harness).post('/auth/forgot').body({email}).expect(HTTP_STATUS.NO_CONTENT).execute();+ const resetMail = findLastTestEmail(await listTestEmails(harness, {recipient: email}), 'password_reset');+ expect(resetMail).not.toBeNull();+ const reset = await createBuilderWithoutAuth<{user_id: string}>(harness)+ .post('/auth/reset')+ .body({token: resetMail!.metadata['token'], password: OWNER_PASSWORD})+ .execute();+ expect(reset.user_id).toBe(registered.user_id);+ await createBuilder(harness, registered.token).get('/users/@me').expect(HTTP_STATUS.UNAUTHORIZED).execute();+ });+});