A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
test(api/sso): cover self-hosted SSO, enforcement and roles
Hampus48723ad30879
diff --git a/fluxer_api/src/api/auth/services/SsoIdentityRepository.test.ts b/fluxer_api/src/api/auth/services/SsoIdentityRepository.test.tsnew file mode 100644index 000000000..ebb49ebbb--- /dev/null+++ b/fluxer_api/src/api/auth/services/SsoIdentityRepository.test.ts@@ -0,0 +1,48 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {SsoIdentityRepository} from '@app/api/auth/services/SsoIdentityRepository';+import {createUserID} from '@app/api/BrandedTypes';+import {setCassandraQueryExecutorForTesting} from '@app/api/database/CassandraQueryExecution';+import {InMemoryCassandraQueryExecutor} from '@app/api/test/InMemoryCassandraQueryExecutor';+import {afterEach, beforeEach, describe, expect, it} from 'vitest';++const ALICE = createUserID(1810000000000000001n);+const BOB = createUserID(1810000000000000002n);++describe('SsoIdentityRepository', () => {+ const repository = new SsoIdentityRepository();++ beforeEach(async () => {+ setCassandraQueryExecutorForTesting(new InMemoryCassandraQueryExecutor());+ const claimedAt = new Date('2026-10-01T00:00:00Z');+ await repository.tryClaimIdentity({providerId: 'https://idp.one', subject: 'alice', userId: ALICE, claimedAt});+ await repository.tryClaimIdentity({providerId: 'https://idp.one', subject: 'bob', userId: BOB, claimedAt});+ await repository.tryClaimIdentity({providerId: 'https://idp.two', subject: 'alice-2', userId: ALICE, claimedAt});+ });++ afterEach(() => {+ setCassandraQueryExecutorForTesting(new InMemoryCassandraQueryExecutor());+ });++ it('releases the identities of one account and leaves the others', async () => {+ expect(await repository.releaseIdentitiesForUser(ALICE)).toBe(2);+ expect(await repository.findUserId('https://idp.one', 'alice')).toBeNull();+ expect(await repository.findUserId('https://idp.two', 'alice-2')).toBeNull();+ expect(await repository.findUserId('https://idp.one', 'bob')).toBe(BOB);+ expect(await repository.listForUser(ALICE)).toEqual([]);+ expect((await repository.listForUser(BOB)).map(({subject}) => subject)).toEqual(['bob']);+ });++ it('skips an index entry whose identity now belongs to another account', async () => {+ await repository.releaseIdentity('https://idp.one', 'alice');+ await repository.tryClaimIdentity({+ providerId: 'https://idp.one',+ subject: 'alice',+ userId: BOB,+ claimedAt: new Date(),+ });+ expect((await repository.listForUser(ALICE)).map(({subject}) => subject)).toEqual(['alice-2']);+ expect(await repository.releaseIdentitiesForUser(ALICE)).toBe(1);+ expect(await repository.findUserId('https://idp.one', 'alice')).toBe(BOB);+ });+});diff --git a/fluxer_api/src/api/auth/tests/SsoEnforcedCredentials.test.ts b/fluxer_api/src/api/auth/tests/SsoEnforcedCredentials.test.tsnew file mode 100644index 000000000..19e82d39b--- /dev/null+++ b/fluxer_api/src/api/auth/tests/SsoEnforcedCredentials.test.ts@@ -0,0 +1,163 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {+ createAuthHarness,+ createTestAccount,+ createUniqueEmail,+ disableSso,+ enableSso,+ setUserACLs,+ type TestAccount,+} from '@app/api/auth/tests/AuthTestUtils';+import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';+import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';+import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it} from 'vitest';++interface SsoStartResponse {+ state: string;+}++interface SsoCompleteResponse {+ token: string;+ user_id: string;+}++interface ErrorBody {+ code: string;+ message: string;+}++const CREDENTIAL_ROUTES: ReadonlyArray<{method: 'post' | 'patch'; path: string; body: Record<string, unknown>}> = [+ {method: 'post', path: '/users/@me/email-change/start', body: {}},+ {method: 'post', path: '/users/@me/email-change/resend-original', body: {ticket: 'ticket'}},+ {method: 'post', path: '/users/@me/email-change/verify-original', body: {ticket: 'ticket', code: 'code'}},+ {+ method: 'post',+ path: '/users/@me/email-change/request-new',+ body: {ticket: 'ticket', new_email: '[email protected]', original_proof: 'proof'},+ },+ {method: 'post', path: '/users/@me/email-change/resend-new', body: {ticket: 'ticket'}},+ {+ method: 'post',+ path: '/users/@me/email-change/verify-new',+ body: {ticket: 'ticket', code: 'code', original_proof: 'proof'},+ },+ {method: 'post', path: '/users/@me/email-change/apply', body: {email_token: 'token'}},+ {method: 'post', path: '/users/@me/email-change/bounced/request-new', body: {new_email: '[email protected]'}},+ {method: 'post', path: '/users/@me/email-change/bounced/resend-new', body: {ticket: 'ticket'}},+ {method: 'post', path: '/users/@me/email-change/bounced/verify-new', body: {ticket: 'ticket', code: 'code'}},+ {method: 'post', path: '/users/@me/password-change/start', body: {}},+ {method: 'post', path: '/users/@me/password-change/resend', body: {ticket: 'ticket'}},+ {method: 'post', path: '/users/@me/password-change/verify', body: {ticket: 'ticket', code: 'code'}},+ {+ method: 'post',+ path: '/users/@me/password-change/complete',+ body: {ticket: 'ticket', verification_proof: 'proof', new_password: 'a-new-password-123'},+ },+ {method: 'patch', path: '/users/@me', body: {new_password: 'a-new-password-123'}},+ {method: 'patch', path: '/users/@me', body: {email_token: 'token'}},+];++describe('Credentials of SSO accounts while SSO is enforced', () => {+ let harness: ApiTestHarness;+ let admin: TestAccount;++ beforeAll(async () => {+ harness = await createAuthHarness();+ });+ beforeEach(async () => {+ await harness.reset();+ admin = await setUserACLs(harness, await createTestAccount(harness), [+ 'admin:authenticate',+ 'instance:config:update',+ 'instance:config:view',+ ]);+ });+ afterEach(async () => {+ await disableSso(harness, admin.token);+ });+ afterAll(async () => {+ await harness?.shutdown();+ });++ async function signInWithSso(): Promise<SsoCompleteResponse> {+ const start = await createBuilderWithoutAuth<SsoStartResponse>(harness).post('/auth/sso/start').body({}).execute();+ const login = await createBuilderWithoutAuth<SsoCompleteResponse>(harness)+ .post('/auth/sso/complete')+ .body({code: createUniqueEmail('sso-credentials'), state: start.state})+ .execute();+ await createBuilder(harness, login.token)+ .put('/users/@me/date-of-birth')+ .body({date_of_birth: '1990-01-01'})+ .execute();+ return login;+ }++ for (const route of CREDENTIAL_ROUTES) {+ it(`refuses ${route.method.toUpperCase()} ${route.path} ${Object.keys(route.body).join(',')}`, async () => {+ await enableSso(harness, admin.token);+ const login = await signInWithSso();+ await createBuilder(harness, login.token)+ [route.method](route.path)+ .body(route.body)+ .expect(403, 'SSO_REQUIRED')+ .execute();+ });+ }++ it('says the SSO provider manages the credentials of an SSO account', async () => {+ await enableSso(harness, admin.token);+ const login = await signInWithSso();+ const {json} = await createBuilder<ErrorBody>(harness, login.token)+ .post('/users/@me/password-change/start')+ .body({})+ .expect(403, 'SSO_REQUIRED')+ .executeWithResponse();+ expect(json.message).toBe(+ 'This instance requires single sign-on, so your SSO provider manages your email and password.',+ );+ });++ it('points a password sign-in at the SSO button while SSO is enforced', async () => {+ const local = await createTestAccount(harness);+ await enableSso(harness, admin.token);+ const {json} = await createBuilderWithoutAuth<ErrorBody>(harness)+ .post('/auth/login')+ .body({email: local.email, password: local.password})+ .expect(403, 'SSO_REQUIRED')+ .executeWithResponse();+ expect(json.message).toBe(+ 'This instance requires single sign-on. Sign in with the SSO button on the sign-in page.',+ );+ });++ it('still lets an SSO account edit its profile while SSO is enforced', async () => {+ await enableSso(harness, admin.token);+ const login = await signInWithSso();+ const updated = await createBuilder<{global_name: string | null}>(harness, login.token)+ .patch('/users/@me')+ .body({global_name: 'Renamed'})+ .execute();+ expect(updated.global_name).toBe('Renamed');+ });++ it('lets an SSO account start an email change when SSO is optional', async () => {+ await enableSso(harness, admin.token, {enforced: false});+ const login = await signInWithSso();+ const started = await createBuilder<{ticket: string}>(harness, login.token)+ .post('/users/@me/email-change/start')+ .body({})+ .execute();+ expect(started.ticket).toBeTruthy();+ });++ it('leaves accounts without an SSO link alone while SSO is enforced', async () => {+ const local = await createTestAccount(harness);+ await enableSso(harness, admin.token);+ const started = await createBuilder<{ticket: string}>(harness, local.token)+ .post('/users/@me/email-change/start')+ .body({})+ .execute();+ expect(started.ticket).toBeTruthy();+ });+});diff --git a/fluxer_api/src/api/auth/tests/SsoEnforcement.test.ts b/fluxer_api/src/api/auth/tests/SsoEnforcement.test.tsnew file mode 100644index 000000000..517532298--- /dev/null+++ b/fluxer_api/src/api/auth/tests/SsoEnforcement.test.ts@@ -0,0 +1,86 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {+ clearTestEmails,+ createUniqueEmail,+ disableSso,+ enableSso,+ type TestAccount,+} from '@app/api/auth/tests/AuthTestUtils';+import {close, createStaff, suspend} from '@app/api/enforcement/tests/EnforcementTestUtils';+import {ipBanCache} from '@app/api/middleware/IpBanMiddleware';+import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';+import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';+import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it} from 'vitest';++interface SsoCompleteBody {+ token?: string;+ user_id?: string;+ code?: string;+}++describe('SSO after enforcement ends', () => {+ let harness: ApiTestHarness;+ let staff: TestAccount;++ beforeAll(async () => {+ harness = await createApiTestHarness();+ });+ beforeEach(async () => {+ await harness.reset();+ ipBanCache.resetCaches();+ await clearTestEmails(harness);+ staff = await createStaff(harness);+ await enableSso(harness, staff.token);+ });+ afterEach(async () => {+ await disableSso(harness, staff.token);+ });+ afterAll(async () => {+ await harness?.shutdown();+ });++ function subject(label: string): string {+ return `itest-${label}-${Date.now()}-${Math.random().toString(36).slice(2)}`;+ }++ async function ssoSignIn(claims: Record<string, unknown>) {+ const {state} = await createBuilderWithoutAuth<{state: string}>(harness).post('/auth/sso/start').body({}).execute();+ return createBuilderWithoutAuth<SsoCompleteBody>(harness)+ .post('/auth/sso/complete')+ .body({code: JSON.stringify(claims), state})+ .executeRaw();+ }++ async function endDecision(decisionId: string): Promise<void> {+ await createBuilder(harness, staff.token)+ .post(`/admin/enforcement-decisions/${decisionId}/end`)+ .body({outcome: 'reversed'})+ .expect(200)+ .execute();+ }++ it('signs the same account in again after a closure is reversed', async () => {+ const claims = {sub: subject('closed'), email: createUniqueEmail('sso-closed')};+ const first = await ssoSignIn(claims);+ expect(first.response.status).toBe(200);+ const decisionId = await close(harness, staff, first.json.user_id!);+ const refused = await ssoSignIn(claims);+ expect(refused.response.status).toBe(403);+ await endDecision(decisionId);+ const again = await ssoSignIn(claims);+ expect(again.response.status).toBe(200);+ expect(again.json.user_id).toBe(first.json.user_id);+ });++ it('signs the same account in again after a suspension is lifted', async () => {+ const claims = {sub: subject('suspended'), email: createUniqueEmail('sso-suspended')};+ const first = await ssoSignIn(claims);+ const decisionId = await suspend(harness, staff, first.json.user_id!);+ expect((await ssoSignIn(claims)).response.status).toBe(403);+ await endDecision(decisionId);+ const again = await ssoSignIn(claims);+ expect(again.response.status).toBe(200);+ expect(again.json.user_id).toBe(first.json.user_id);+ });+});diff --git a/fluxer_api/src/api/auth/tests/SsoGroupRoles.test.ts b/fluxer_api/src/api/auth/tests/SsoGroupRoles.test.tsnew file mode 100644index 000000000..142d9c454--- /dev/null+++ b/fluxer_api/src/api/auth/tests/SsoGroupRoles.test.ts@@ -0,0 +1,138 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {+ createAuthHarness,+ createTestAccount,+ createUniqueEmail,+ disableSso,+ enableSso,+ setUserACLs,+ type TestAccount,+} from '@app/api/auth/tests/AuthTestUtils';+import {addMemberRole, createGuild, createRole, getMember} from '@app/api/guild/tests/GuildTestUtils';+import {getInstanceConfigRepository} from '@app/api/middleware/ServiceSingletons';+import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';+import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';+import {AdminACLs} from '@fluxer/constants/src/AdminACLs';+import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it} from 'vitest';++describe('SSO groups to community roles', () => {+ let harness: ApiTestHarness;+ let admin: TestAccount;+ let owner: TestAccount;+ let guildId: string;+ let staffRole: string;+ let devRole: string;+ let handRole: string;+ let foreignRole: string;++ beforeAll(async () => {+ harness = await createAuthHarness();+ });+ beforeEach(async () => {+ await harness.reset();+ await getInstanceConfigRepository().setAppPublicConfig({setup: {configured: true}});+ admin = await setUserACLs(harness, await createTestAccount(harness), [+ AdminACLs.AUTHENTICATE,+ AdminACLs.INSTANCE_CONFIG_UPDATE,+ AdminACLs.INSTANCE_CONFIG_VIEW,+ ]);+ owner = await createTestAccount(harness);+ const guild = await createGuild(harness, owner.token, 'Company');+ guildId = guild.id;+ staffRole = (await createRole(harness, owner.token, guildId, {name: 'Staff'})).id;+ devRole = (await createRole(harness, owner.token, guildId, {name: 'Developers'})).id;+ handRole = (await createRole(harness, owner.token, guildId, {name: 'Given by hand'})).id;+ const other = await createGuild(harness, owner.token, 'Elsewhere');+ foreignRole = (await createRole(harness, owner.token, other.id, {name: 'Foreign'})).id;+ await createBuilder(harness, admin.token)+ .patch('/admin/instance/config')+ .body({policy: {single_community_enabled: true, single_community_guild_id: guildId}})+ .execute();+ });+ afterEach(async () => {+ await disableSso(harness, admin.token);+ getInstanceConfigRepository().clearCacheForTesting();+ });+ afterAll(async () => {+ await harness?.shutdown();+ });++ function subject(label: string): string {+ return `itest-${label}-${Date.now()}-${Math.random().toString(36).slice(2)}`;+ }++ async function enableWithMappings(extra: Record<string, unknown> = {}): Promise<void> {+ await enableSso(harness, admin.token, {+ enforced: false,+ allowed_domains: [],+ group_role_mappings: [+ {group: 'staff', role_id: staffRole},+ {group: '/engineering/devs', role_id: devRole},+ ],+ ...extra,+ });+ }++ async function signIn(claims: Record<string, unknown>): Promise<string> {+ const {state} = await createBuilderWithoutAuth<{state: string}>(harness).post('/auth/sso/start').body({}).execute();+ const login = await createBuilderWithoutAuth<{user_id: string}>(harness)+ .post('/auth/sso/complete')+ .body({code: JSON.stringify(claims), state})+ .expect(200)+ .execute();+ return login.user_id;+ }++ async function rolesOf(userId: string): Promise<Array<string>> {+ const member = await getMember(harness, owner.token, guildId, userId);+ return [...member.roles].sort();+ }++ it('gives a new account the roles of its groups', async () => {+ await enableWithMappings();+ const userId = await signIn({sub: subject('new'), email: createUniqueEmail('sso-groups'), groups: ['staff']});+ expect(await rolesOf(userId)).toEqual([staffRole]);+ });++ it('follows the groups on every sign-in and leaves roles it does not manage', async () => {+ await enableWithMappings();+ const claims = {sub: subject('change'), email: createUniqueEmail('sso-groups-change')};+ const userId = await signIn({...claims, groups: ['staff']});+ await addMemberRole(harness, owner.token, guildId, userId, handRole);+ await signIn({...claims, groups: ['/engineering/devs', 'unmapped']});+ expect(await rolesOf(userId)).toEqual([devRole, handRole].sort());+ await signIn({...claims, groups: []});+ expect(await rolesOf(userId)).toEqual([handRole]);+ });++ it('leaves the roles alone when the provider sends no groups claim', async () => {+ await enableWithMappings();+ const claims = {sub: subject('absent'), email: createUniqueEmail('sso-groups-absent')};+ const userId = await signIn({...claims, groups: ['staff']});+ await signIn(claims);+ expect(await rolesOf(userId)).toEqual([staffRole]);+ });++ it('reads the groups from the claim the admin names', async () => {+ await enableWithMappings({groups_claim: 'roles'});+ const userId = await signIn({+ sub: subject('claim'),+ email: createUniqueEmail('sso-groups-claim'),+ groups: ['staff'],+ roles: ['/engineering/devs'],+ });+ expect(await rolesOf(userId)).toEqual([devRole]);+ });++ it.each([+ ['a role of another community', () => foreignRole],+ ['the everyone role', () => guildId],+ ])('refuses %s', async (_label, roleId) => {+ await createBuilder(harness, admin.token)+ .patch('/admin/instance/config')+ .body({sso: {group_role_mappings: [{group: 'staff', role_id: roleId()}]}})+ .expect(400, 'INVALID_FORM_BODY')+ .execute();+ });+});diff --git a/fluxer_api/src/api/auth/tests/SsoSelfHosting.test.ts b/fluxer_api/src/api/auth/tests/SsoSelfHosting.test.tsnew file mode 100644index 000000000..91e9e2ba9--- /dev/null+++ b/fluxer_api/src/api/auth/tests/SsoSelfHosting.test.ts@@ -0,0 +1,353 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {AdminRepository} from '@app/api/admin/AdminRepository';+import {SsoIdentityRepository} from '@app/api/auth/services/SsoIdentityRepository';+import {+ createAuthHarness,+ createTestAccount,+ createUniqueEmail,+ disableSso,+ enableSso,+ setUserACLs,+ type TestAccount,+} from '@app/api/auth/tests/AuthTestUtils';+import {createUserID} from '@app/api/BrandedTypes';+import {getConfig} from '@app/api/Config';+import {deleteOneOrMany} from '@app/api/database/CassandraQueryExecution';+import {getInstanceConfigRepository, getUserRepository} from '@app/api/middleware/ServiceSingletons';+import {UserSsoIdentitiesByUser} from '@app/api/Tables';+import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';+import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';+import {triggerDeletionWorker} from '@app/api/user/tests/UserTestUtils';+import {AccountIdentityModes} from '@fluxer/constants/src/AccountIdentityConstants';+import {AdminACLs} from '@fluxer/constants/src/AdminACLs';+import {DeletionReasons} from '@fluxer/constants/src/Core';+import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';+import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it} from 'vitest';++interface SsoStartResponse {+ state: string;+}++interface SsoCompleteResponse {+ token: string;+ user_id: string;+}++interface ValidationErrorBody {+ code: string;+ message?: string;+ errors?: Array<{path: string; code: string}>;+}++interface CurrentUser {+ id: string;+ username: string;+ global_name: string | null;+ email: string | null;+}++const ISSUER = 'test';++describe('SSO on self-hosted instances', () => {+ let harness: ApiTestHarness;+ let admin: TestAccount;+ const config = getConfig();+ let originalSelfHosted: boolean;++ beforeAll(async () => {+ harness = await createAuthHarness();+ });+ beforeEach(async () => {+ await harness.reset();+ originalSelfHosted = config.instance.selfHosted;+ admin = await setUserACLs(harness, await createTestAccount(harness), [+ 'admin:authenticate',+ 'instance:config:update',+ 'instance:config:view',+ ]);+ });+ afterEach(async () => {+ await disableSso(harness, admin.token);+ config.instance.selfHosted = originalSelfHosted;+ getInstanceConfigRepository().clearCacheForTesting();+ });+ afterAll(async () => {+ await harness?.shutdown();+ });++ async function useUsernameMode(): Promise<void> {+ config.instance.selfHosted = true;+ await getInstanceConfigRepository().setAccountIdentityMode(AccountIdentityModes.USERNAME, 'setup');+ await getInstanceConfigRepository().setAppPublicConfig({setup: {configured: true}});+ }++ async function startState(): Promise<string> {+ const start = await createBuilderWithoutAuth<SsoStartResponse>(harness).post('/auth/sso/start').body({}).execute();+ return start.state;+ }++ async function completeSso(claims: Record<string, unknown>): Promise<SsoCompleteResponse> {+ const state = await startState();+ return createBuilderWithoutAuth<SsoCompleteResponse>(harness)+ .post('/auth/sso/complete')+ .body({code: JSON.stringify(claims), state})+ .execute();+ }++ async function completeSsoFailure(claims: Record<string, unknown>, status: number): Promise<ValidationErrorBody> {+ const state = await startState();+ const {json} = await createBuilderWithoutAuth<ValidationErrorBody>(harness)+ .post('/auth/sso/complete')+ .body({code: JSON.stringify(claims), state})+ .expect(status)+ .executeWithResponse();+ return json;+ }++ async function currentUser(token: string): Promise<CurrentUser> {+ return createBuilder<CurrentUser>(harness, token).get('/users/@me').execute();+ }++ function subject(label: string): string {+ return `itest-${label}-${Date.now()}-${Math.random().toString(36).slice(2)}`;+ }++ describe('registration modes', () => {+ it('provisions an SSO user while registration is closed', async () => {+ await enableSso(harness, admin.token);+ await getInstanceConfigRepository().setRegistrationConfig({mode: 'closed'});+ const login = await completeSso({email: createUniqueEmail('sso-closed'), sub: subject('closed')});+ expect(login.token).toBeTruthy();+ const me = await currentUser(login.token);+ expect(me.id).toBe(login.user_id);+ });++ it('still requires an existing account when auto-provisioning is off and registration is closed', async () => {+ await enableSso(harness, admin.token, {auto_provision: false});+ await getInstanceConfigRepository().setRegistrationConfig({mode: 'closed'});+ const body = await completeSsoFailure(+ {email: createUniqueEmail('sso-closed-noprov'), sub: subject('closed-noprov')},+ 403,+ );+ expect(body.code).toBe('SSO_REQUIRED');+ expect(body.message).toBe(+ "This instance only lets existing accounts sign in with SSO, and there's no account for you yet. Ask an admin of this instance for access.",+ );+ });++ it('keeps approval mode in force for SSO users', async () => {+ await enableSso(harness, admin.token);+ await getInstanceConfigRepository().setRegistrationConfig({mode: 'approval'});+ const body = await completeSsoFailure({email: createUniqueEmail('sso-approval'), sub: subject('approval')}, 403);+ expect(body.code).toBe('REGISTRATION_PENDING_APPROVAL');+ });+ });++ describe('email claims', () => {+ it('names an unverified provider email on email instances', async () => {+ await enableSso(harness, admin.token);+ const body = await completeSsoFailure(+ {email: createUniqueEmail('sso-unverified'), sub: subject('unverified'), email_verified: false},+ 400,+ );+ expect(body.errors).toEqual([+ {path: 'email_verified', code: ValidationErrorCodes.SSO_EMAIL_NOT_VERIFIED, message: expect.any(String)},+ ]);+ });++ it('requires an email on email instances', async () => {+ await enableSso(harness, admin.token, {allowed_domains: []});+ const body = await completeSsoFailure({sub: subject('no-email'), preferred_username: 'noemail'}, 400);+ expect(body.errors?.map(({path, code}) => ({path, code}))).toEqual([+ {path: 'email', code: ValidationErrorCodes.SSO_PROVIDER_DID_NOT_RETURN_EMAIL},+ ]);+ });++ it('provisions without an email on username instances', async () => {+ await useUsernameMode();+ await enableSso(harness, admin.token, {allowed_domains: []});+ const login = await completeSso({sub: subject('username-no-email'), preferred_username: 'nomail'});+ const me = await currentUser(login.token);+ expect(me.username).toBe('nomail');+ expect(me.email).toBeNull();+ });++ it('accepts an unverified email on username instances without a domain list', async () => {+ await useUsernameMode();+ await enableSso(harness, admin.token, {allowed_domains: []});+ const sub = subject('username-unverified');+ const first = await completeSso({+ sub,+ email: createUniqueEmail('sso-username-unverified'),+ email_verified: false,+ preferred_username: 'unverified',+ });+ const second = await completeSso({sub, preferred_username: 'unverified'});+ expect(second.user_id).toBe(first.user_id);+ });++ it('still needs a verified email on username instances with a domain list', async () => {+ await useUsernameMode();+ await enableSso(harness, admin.token, {allowed_domains: ['example.com']});+ const missing = await completeSsoFailure({sub: subject('username-domain-missing')}, 400);+ expect(missing.errors?.map(({code}) => code)).toEqual([ValidationErrorCodes.SSO_PROVIDER_DID_NOT_RETURN_EMAIL]);+ const unverified = await completeSsoFailure(+ {sub: subject('username-domain-unverified'), email: createUniqueEmail('sso-domain'), email_verified: false},+ 400,+ );+ expect(unverified.errors?.map(({code}) => code)).toEqual([ValidationErrorCodes.SSO_EMAIL_NOT_VERIFIED]);+ });+ });++ describe('deleted accounts', () => {+ async function deleteAccount(userId: string, reasonCode: number): Promise<void> {+ const users = getUserRepository();+ const user = await users.findUnique(createUserID(BigInt(userId)));+ if (!user) throw new Error('user missing');+ await users.updateDeletionSchedule(user, {+ pending_deletion_at: new Date(Date.now() - 1000),+ deletion_reason_code: reasonCode,+ });+ await createBuilderWithoutAuth(harness)+ .post(`/test/users/${userId}/set-pending-deletion`)+ .body({+ pending_deletion_at: new Date(Date.now() - 1000).toISOString(),+ set_self_deleted_flag: reasonCode === DeletionReasons.USER_REQUESTED,+ })+ .execute();+ await triggerDeletionWorker(harness);+ const deleted = await users.findUnique(createUserID(BigInt(userId)));+ expect(deleted?.pendingDeletionAt ?? null).toBeNull();+ }++ it('provisions a new account for the same subject after the person deletes theirs', async () => {+ await enableSso(harness, admin.token);+ const sub = subject('deleted-self');+ const email = createUniqueEmail('sso-deleted-self');+ const first = await completeSso({sub, email});+ await deleteAccount(first.user_id, DeletionReasons.USER_REQUESTED);+ expect(await new SsoIdentityRepository().findUserId(ISSUER, sub)).toBeNull();+ const second = await completeSso({sub, email});+ expect(second.user_id).not.toBe(first.user_id);+ });++ it('releases a mapping left pointing at an account deleted before the release existed', async () => {+ await enableSso(harness, admin.token);+ const sub = subject('deleted-stale');+ const email = createUniqueEmail('sso-deleted-stale');+ const first = await completeSso({sub, email});+ await deleteAccount(first.user_id, DeletionReasons.USER_REQUESTED);+ await new SsoIdentityRepository().tryClaimIdentity({+ providerId: ISSUER,+ subject: sub,+ userId: createUserID(BigInt(first.user_id)),+ claimedAt: new Date(),+ });+ const second = await completeSso({sub, email});+ expect(second.user_id).not.toBe(first.user_id);+ });++ it('keeps refusing a subject whose account was closed by enforcement while its email is banned', async () => {+ await enableSso(harness, admin.token);+ const sub = subject('deleted-enforced');+ const email = createUniqueEmail('sso-deleted-enforced');+ const first = await completeSso({sub, email});+ await deleteAccount(first.user_id, DeletionReasons.SPAM);+ await new AdminRepository().banEmail(email);+ expect((await new SsoIdentityRepository().findUserId(ISSUER, sub))?.toString()).toBe(first.user_id);+ const body = await completeSsoFailure({sub, email}, 403);+ expect(body.code).toBe('ACCOUNT_SUSPENDED_PERMANENTLY');+ });++ it('lets the subject back in to a new account once the email ban is lifted', async () => {+ await enableSso(harness, admin.token);+ const sub = subject('deleted-unbanned');+ const email = createUniqueEmail('sso-deleted-unbanned');+ const first = await completeSso({sub, email});+ await deleteAccount(first.user_id, DeletionReasons.SPAM);+ const bans = new AdminRepository();+ await bans.banEmail(email);+ await completeSsoFailure({sub, email}, 403);+ await bans.unbanEmail(email);+ const second = await completeSso({sub, email});+ expect(second.user_id).not.toBe(first.user_id);+ expect((await new SsoIdentityRepository().findUserId(ISSUER, sub))?.toString()).toBe(second.user_id);+ });++ it.each([+ ['bound now', false],+ ['bound before the per-account index', true],+ ])('lets a subject %s back in on a username instance once an admin releases it', async (_label, legacy) => {+ const staff = await setUserACLs(harness, await createTestAccount(harness), [+ 'admin:authenticate',+ AdminACLs.USER_UPDATE_EMAIL,+ ]);+ await useUsernameMode();+ await enableSso(harness, admin.token, {allowed_domains: []});+ const sub = subject('deleted-username');+ const first = await completeSso({sub, preferred_username: 'removed'});+ await deleteAccount(first.user_id, DeletionReasons.SPAM);+ expect((await completeSsoFailure({sub}, 403)).code).toBe('ACCOUNT_SUSPENDED_PERMANENTLY');+ if (legacy) {+ await deleteOneOrMany(+ UserSsoIdentitiesByUser.deleteByPk({+ user_id: createUserID(BigInt(first.user_id)),+ provider_id: ISSUER,+ subject: sub,+ }),+ );+ }+ await createBuilder(harness, staff.token)+ .delete(`/admin/users/${first.user_id}/sso-identities`)+ .expect(200)+ .execute();+ const second = await completeSso({sub});+ expect(second.user_id).not.toBe(first.user_id);+ });+ });++ describe('email while SSO is required', () => {+ it('takes a changed provider email on sign-in', async () => {+ await enableSso(harness, admin.token);+ const sub = subject('email-sync');+ const first = await completeSso({sub, email: createUniqueEmail('sso-email-before')});+ const changed = createUniqueEmail('sso-email-after');+ const second = await completeSso({sub, email: changed});+ expect(second.user_id).toBe(first.user_id);+ expect((await currentUser(second.token)).email).toBe(changed);+ });++ it('keeps the account email when SSO is optional', async () => {+ await enableSso(harness, admin.token, {enforced: false});+ const sub = subject('email-optional');+ const original = createUniqueEmail('sso-email-optional');+ await completeSso({sub, email: original});+ const second = await completeSso({sub, email: createUniqueEmail('sso-email-optional-after')});+ expect((await currentUser(second.token)).email).toBe(original);+ });++ it('keeps the account email when another account holds the provider email', async () => {+ const other = await createTestAccount(harness);+ await enableSso(harness, admin.token);+ const sub = subject('email-taken');+ const original = createUniqueEmail('sso-email-taken');+ await completeSso({sub, email: original});+ const second = await completeSso({sub, email: other.email});+ expect(second.user_id).not.toBe(other.userId);+ expect((await currentUser(second.token)).email).toBe(original);+ });++ it('reports the instance mode before the SSO lock on username instances', async () => {+ await useUsernameMode();+ await enableSso(harness, admin.token, {allowed_domains: []});+ const login = await completeSso({sub: subject('username-lock'), preferred_username: 'locked'});+ const {json} = await createBuilder<ValidationErrorBody>(harness, login.token)+ .post('/users/@me/email-change/start')+ .body({})+ .expect(400)+ .executeWithResponse();+ expect(json.code).toBe('EMAIL_UNAVAILABLE_ON_INSTANCE');+ });+ });+});