Skip to content

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

TypeScript fluxerfluxerapp

feat(api/admin): add SSO identity admin routes

Hampusb38ff8776bad
diff --git a/fluxer_api/src/api/admin/AdminAuditActions.ts b/fluxer_api/src/api/admin/AdminAuditActions.ts
index a5724d0d0..10cf3342d 100644
--- a/fluxer_api/src/api/admin/AdminAuditActions.ts
+++ b/fluxer_api/src/api/admin/AdminAuditActions.ts
@@ -16,12 +16,21 @@ export const AdminAuditReadActions = {
GET_LIMIT_CONFIG: 'get_limit_config',
GET_MESSAGE: 'get_message',
GET_MESSAGE_SHRED_STATUS: 'get_message_shred_status',
+ GET_OPERATOR_PASS_RELEASE: 'get_operator_pass_release',
+ GET_OPERATOR_PASS_WAITLIST_STATS: 'get_operator_pass_waitlist_stats',
GET_REPORT: 'get_report',
GET_USER: 'get_user',
+ GET_USER_OPERATOR_PASS: 'get_user_operator_pass',
+ GET_OPERATOR_PASS_WALL_TIMELINE: 'get_operator_pass_wall_timeline',
+ GET_OPERATOR_PASS_WALL_AS_OF: 'get_operator_pass_wall_as_of',
+ GET_OPERATOR_PASS_WALL_STATE: 'get_operator_pass_wall_state',
+ GET_OPERATOR_PASS_WALL_AVATAR: 'get_operator_pass_wall_avatar',
GET_VOICE_REGION: 'get_voice_region',
GET_VOICE_SERVER: 'get_voice_server',
GET_VOICE_STATE_COUNTS: 'get_voice_state_counts',
LIST_ADMIN_ACLS: 'list_admin_acls',
+ LIST_OPERATOR_PASS_WAITLIST_FOLLOWUP_TEXTS: 'list_operator_pass_waitlist_followup_texts',
+ LIST_OPERATOR_PASS_WALL_REVIEW_QUEUE: 'list_operator_pass_wall_review_queue',
LIST_ADMIN_API_KEYS: 'list_admin_api_keys',
LIST_ARCHIVES: 'list_archives',
LIST_AUDIT_LOGS: 'list_audit_logs',
@@ -41,6 +50,7 @@ export const AdminAuditReadActions = {
LIST_GUILD_STICKERS: 'list_guild_stickers',
LIST_GUILD_THREADS: 'list_guild_threads',
LIST_NETWORK_BLOCK_CANDIDATES: 'list_network_block_candidates',
+ LIST_PAYMENT_DISPUTE_REVIEWS: 'list_payment_dispute_reviews',
LIST_PENDING_REGISTRATIONS: 'list_pending_registrations',
LIST_REPORT_NOTES: 'list_report_notes',
LIST_REPORT_REASONS: 'list_report_reasons',
@@ -50,10 +60,12 @@ export const AdminAuditReadActions = {
LIST_USER_GUILDS: 'list_user_guilds',
LIST_USER_RELATIONSHIPS: 'list_user_relationships',
LIST_USER_SESSIONS: 'list_user_sessions',
+ LIST_USER_SSO_IDENTITIES: 'list_user_sso_identities',
LIST_USER_STORE_PURCHASES: 'list_user_store_purchases',
LIST_VOICE_REGIONS: 'list_voice_regions',
LIST_VOICE_SERVERS: 'list_voice_servers',
LIST_WEBAUTHN_CREDENTIALS: 'list_webauthn_credentials',
+ LOOKUP_SSO_IDENTITY: 'lookup_sso_identity',
SEARCH_AUDIT_LOGS: 'search_audit_logs',
SEARCH_GUILDS: 'search_guilds',
SEARCH_MESSAGES: 'search_messages',
diff --git a/fluxer_api/src/api/admin/controllers/SsoIdentityAdminController.ts b/fluxer_api/src/api/admin/controllers/SsoIdentityAdminController.ts
new file mode 100644
index 000000000..81260b1fc
--- /dev/null
+++ b/fluxer_api/src/api/admin/controllers/SsoIdentityAdminController.ts
@@ -0,0 +1,220 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {AdminAuditReadActions} from '@app/api/admin/AdminAuditActions';
+import {recordAdminRead} from '@app/api/admin/AdminAuditRecorder';
+import {SsoIdentityLinkService, ssoProviderIdOf} from '@app/api/auth/services/SsoIdentityLinks';
+import {SsoIdentityRepository} from '@app/api/auth/services/SsoIdentityRepository';
+import {createUserID} from '@app/api/BrandedTypes';
+import type {UserSsoIdentityRow} from '@app/api/database/types/AuthTypes';
+import {requireAdminACL} from '@app/api/middleware/AdminMiddleware';
+import {RateLimitMiddleware} from '@app/api/middleware/RateLimitMiddleware';
+import {OpenAPI} from '@app/api/middleware/ResponseTypeMiddleware';
+import {getInstanceConfigRepository} from '@app/api/middleware/ServiceSingletons';
+import {RateLimitConfigs} from '@app/api/RateLimitConfig';
+import type {HonoApp} from '@app/api/types/HonoEnv';
+import {Validator} from '@app/api/Validator';
+import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
+import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';
+import {
+ AdminSsoIdentityLinkRequest,
+ AdminSsoIdentityLookupQuery,
+ AdminSsoIdentityLookupResponse,
+ AdminSsoIdentityMigrateRequest,
+ AdminSsoIdentityMigrateResponse,
+ type AdminSsoIdentityResponse,
+ AdminUserSsoIdentityListResponse,
+} from '@fluxer/schema/src/domains/admin/AdminSsoSchemas';
+import {UserIdParam} from '@fluxer/schema/src/domains/common/CommonParamSchemas';
+
+const ssoIdentityRepository = new SsoIdentityRepository();
+
+function mapSsoIdentity(row: UserSsoIdentityRow): AdminSsoIdentityResponse {
+ return {
+ provider_id: row.provider_id,
+ subject: row.subject,
+ user_id: row.user_id.toString(),
+ claimed_at: row.claimed_at.toISOString(),
+ };
+}
+
+async function currentProviderId(): Promise<string> {
+ return ssoProviderIdOf(await getInstanceConfigRepository().getSsoConfig());
+}
+
+export function SsoIdentityAdminController(app: HonoApp) {
+ app.get(
+ '/admin/users/:user_id/sso-identities',
+ RateLimitMiddleware(RateLimitConfigs.ADMIN_LOOKUP),
+ requireAdminACL(AdminACLs.USER_LOOKUP),
+ Validator('param', UserIdParam),
+ OpenAPI({
+ operationId: 'list_admin_user_sso_identities',
+ summary: 'List user SSO identities',
+ responseSchema: AdminUserSsoIdentityListResponse,
+ statusCode: 200,
+ security: 'adminApiKey',
+ tags: 'Admin',
+ description:
+ 'List the single sign-on provider subjects bound to a user, with the provider each belongs to and when it was bound. Requires USER_LOOKUP permission.',
+ }),
+ async (ctx) => {
+ const userId = createUserID(ctx.req.valid('param').user_id);
+ const user = await ctx.get('userRepository').findUnique(userId);
+ if (!user) {
+ throw new UnknownUserError();
+ }
+ const identities = await ssoIdentityRepository.listForUser(userId);
+ await recordAdminRead(ctx, {
+ targetType: 'user',
+ targetId: userId,
+ action: AdminAuditReadActions.LIST_USER_SSO_IDENTITIES,
+ metadata: {identity_count: identities.length},
+ });
+ return ctx.json({sso_identities: identities.map(mapSsoIdentity)});
+ },
+ );
+ app.get(
+ '/admin/sso-identities',
+ RateLimitMiddleware(RateLimitConfigs.ADMIN_LOOKUP),
+ requireAdminACL(AdminACLs.USER_LOOKUP),
+ Validator('query', AdminSsoIdentityLookupQuery),
+ OpenAPI({
+ operationId: 'lookup_admin_sso_identity',
+ summary: 'Look up an SSO identity',
+ responseSchema: AdminSsoIdentityLookupResponse,
+ statusCode: 200,
+ security: 'adminApiKey',
+ tags: 'Admin',
+ description:
+ 'Find the user a single sign-on provider subject is bound to. Returns null when no account holds the subject. Requires USER_LOOKUP permission.',
+ }),
+ async (ctx) => {
+ const {provider_id: providerId, subject} = ctx.req.valid('query');
+ const identity = await ssoIdentityRepository.findIdentity(providerId, subject);
+ await recordAdminRead(ctx, {
+ targetType: 'user',
+ targetId: identity?.user_id ?? 0n,
+ action: AdminAuditReadActions.LOOKUP_SSO_IDENTITY,
+ metadata: {provider_id: providerId, found: identity !== null},
+ });
+ return ctx.json({sso_identity: identity ? mapSsoIdentity(identity) : null});
+ },
+ );
+ app.put(
+ '/admin/users/:user_id/sso-identities',
+ RateLimitMiddleware(RateLimitConfigs.ADMIN_USER_MODIFY),
+ requireAdminACL(AdminACLs.USER_UPDATE_EMAIL),
+ Validator('param', UserIdParam),
+ Validator('json', AdminSsoIdentityLinkRequest),
+ OpenAPI({
+ operationId: 'link_admin_user_sso_identity',
+ summary: 'Bind an SSO subject to a user',
+ responseSchema: AdminUserSsoIdentityListResponse,
+ statusCode: 200,
+ security: 'adminApiKey',
+ tags: 'Admin',
+ description:
+ 'Bind a provider subject under the provider in use to the account, replacing every subject bound to it before. Use it when the provider started sending another subject for the same person. Refused with SSO_IDENTITY_LINKED_TO_ANOTHER_ACCOUNT when another account that is not deleted holds the subject. Creates audit log entry. Requires USER_UPDATE_EMAIL permission.',
+ }),
+ async (ctx) => {
+ const userId = createUserID(ctx.req.valid('param').user_id);
+ const user = await ctx.get('userRepository').findUnique(userId);
+ if (!user) {
+ throw new UnknownUserError();
+ }
+ const providerId = await currentProviderId();
+ const identities = await new SsoIdentityLinkService(ctx.get('userRepository')).link(
+ user,
+ providerId,
+ ctx.req.valid('json').subject,
+ );
+ await ctx.get('adminService').auditService.createAuditLog({
+ adminUserId: ctx.get('adminUserId'),
+ targetType: 'user',
+ targetId: userId,
+ action: 'link_sso_identity',
+ auditLogReason: ctx.get('auditLogReason'),
+ metadata: new Map([['provider_id', providerId]]),
+ });
+ return ctx.json({sso_identities: identities.map(mapSsoIdentity)});
+ },
+ );
+ app.delete(
+ '/admin/users/:user_id/sso-identities',
+ RateLimitMiddleware(RateLimitConfigs.ADMIN_USER_MODIFY),
+ requireAdminACL(AdminACLs.USER_UPDATE_EMAIL),
+ Validator('param', UserIdParam),
+ OpenAPI({
+ operationId: 'unlink_admin_user_sso_identities',
+ summary: 'Unbind the SSO subjects of a user',
+ responseSchema: AdminUserSsoIdentityListResponse,
+ statusCode: 200,
+ security: 'adminApiKey',
+ tags: 'Admin',
+ description:
+ 'Release every provider subject bound to the account. On an instance that stores email addresses, the next single sign-on with the same verified email binds the account again. A released subject of a deleted account can sign in to a new account. Creates audit log entry. Requires USER_UPDATE_EMAIL permission.',
+ }),
+ async (ctx) => {
+ const userId = createUserID(ctx.req.valid('param').user_id);
+ const user = await ctx.get('userRepository').findUnique(userId);
+ if (!user) {
+ throw new UnknownUserError();
+ }
+ const before = await ssoIdentityRepository.listForUser(userId);
+ const identities = await new SsoIdentityLinkService(ctx.get('userRepository')).unlink(
+ user,
+ await currentProviderId(),
+ );
+ await ctx.get('adminService').auditService.createAuditLog({
+ adminUserId: ctx.get('adminUserId'),
+ targetType: 'user',
+ targetId: userId,
+ action: 'unlink_sso_identities',
+ auditLogReason: ctx.get('auditLogReason'),
+ metadata: new Map([['identity_count', before.length.toString()]]),
+ });
+ return ctx.json({sso_identities: identities.map(mapSsoIdentity)});
+ },
+ );
+ app.post(
+ '/admin/sso-identities/migrate',
+ RateLimitMiddleware(RateLimitConfigs.ADMIN_USER_MODIFY),
+ requireAdminACL(AdminACLs.INSTANCE_CONFIG_UPDATE),
+ Validator('json', AdminSsoIdentityMigrateRequest),
+ OpenAPI({
+ operationId: 'migrate_admin_sso_identities',
+ summary: 'Move SSO subjects to the provider in use',
+ responseSchema: AdminSsoIdentityMigrateResponse,
+ statusCode: 200,
+ security: 'adminApiKey',
+ tags: 'Admin',
+ description:
+ 'Move every subject bound under from_provider_id to the provider in use, keeping each on its account. Use it after the issuer changed while the provider still sends the same subjects, so people keep their accounts. A subject that another account already holds under the provider in use is left where it was and counted in skipped_count. Reads every subject of the old provider, so run it once after the change. Creates audit log entry. Requires INSTANCE_CONFIG_UPDATE permission.',
+ }),
+ async (ctx) => {
+ const fromProviderId = ctx.req.valid('json').from_provider_id;
+ const toProviderId = await currentProviderId();
+ if (fromProviderId === toProviderId) {
+ throw InputValidationError.create('from_provider_id', 'This is the provider in use');
+ }
+ const {moved, skipped} = await new SsoIdentityLinkService(ctx.get('userRepository')).migrate(
+ fromProviderId,
+ toProviderId,
+ );
+ await ctx.get('adminService').auditService.createAuditLog({
+ adminUserId: ctx.get('adminUserId'),
+ targetType: 'instance_config',
+ targetId: 0n,
+ action: 'migrate_sso_identities',
+ auditLogReason: ctx.get('auditLogReason'),
+ metadata: new Map([
+ ['from_provider_id', fromProviderId],
+ ['to_provider_id', toProviderId],
+ ['moved_count', moved.toString()],
+ ['skipped_count', skipped.toString()],
+ ]),
+ });
+ return ctx.json({to_provider_id: toProviderId, moved_count: moved, skipped_count: skipped});
+ },
+ );
+}
diff --git a/fluxer_api/src/api/admin/tests/SsoIdentityAdmin.test.ts b/fluxer_api/src/api/admin/tests/SsoIdentityAdmin.test.ts
new file mode 100644
index 000000000..cf8c1576b
--- /dev/null
+++ b/fluxer_api/src/api/admin/tests/SsoIdentityAdmin.test.ts
@@ -0,0 +1,261 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+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} 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 {AccountIdentityModes} from '@fluxer/constants/src/AccountIdentityConstants';
+import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
+import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
+import type {
+ AdminSsoIdentityLookupResponse,
+ AdminSsoIdentityMigrateResponse,
+ AdminUserSsoIdentityListResponse,
+} from '@fluxer/schema/src/domains/admin/AdminSsoSchemas';
+import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it} from 'vitest';
+
+describe('SSO identity admin routes', () => {
+ let harness: ApiTestHarness;
+ let admin: TestAccount;
+ const originalSelfHosted = getConfig().instance.selfHosted;
+
+ beforeAll(async () => {
+ harness = await createAuthHarness();
+ });
+ beforeEach(async () => {
+ await harness.reset();
+ admin = await setUserACLs(harness, await createTestAccount(harness), [
+ AdminACLs.AUTHENTICATE,
+ AdminACLs.INSTANCE_CONFIG_UPDATE,
+ AdminACLs.INSTANCE_CONFIG_VIEW,
+ AdminACLs.USER_LOOKUP,
+ AdminACLs.USER_UPDATE_EMAIL,
+ ]);
+ await enableSso(harness, admin.token, {enforced: false});
+ });
+ afterEach(async () => {
+ await disableSso(harness, admin.token);
+ await createBuilder(harness, admin.token)
+ .patch('/admin/instance/config')
+ .body({sso: {issuer: null}})
+ .execute();
+ getConfig().instance.selfHosted = originalSelfHosted;
+ getInstanceConfigRepository().clearCacheForTesting();
+ });
+ afterAll(async () => {
+ await harness?.shutdown();
+ });
+
+ async function signInWithSso(sub: string, email: string | null = createUniqueEmail('sso-admin')): Promise<string> {
+ const login = await completeSso(sub, email).expect(200).execute();
+ return login.user_id;
+ }
+
+ function completeSso(sub: string, email: string | null) {
+ const claims = email === null ? {sub} : {sub, email};
+ return {
+ expect(status: number, code?: string) {
+ return {
+ async execute(): Promise<{user_id: string}> {
+ const start = await createBuilderWithoutAuth<{state: string}>(harness)
+ .post('/auth/sso/start')
+ .body({})
+ .execute();
+ return createBuilderWithoutAuth<{user_id: string}>(harness)
+ .post('/auth/sso/complete')
+ .body({code: JSON.stringify(claims), state: start.state})
+ .expect(status, code)
+ .execute();
+ },
+ };
+ },
+ };
+ }
+
+ async function setIssuer(issuer: string): Promise<void> {
+ await createBuilder(harness, admin.token).patch('/admin/instance/config').body({sso: {issuer}}).execute();
+ }
+
+ async function listIdentities(userId: string) {
+ const listed = await createBuilder<AdminUserSsoIdentityListResponse>(harness, admin.token)
+ .get(`/admin/users/${userId}/sso-identities`)
+ .execute();
+ return listed.sso_identities.map(({provider_id, subject}) => ({provider_id, subject}));
+ }
+
+ function migrate(fromProviderId: string) {
+ return createBuilder<AdminSsoIdentityMigrateResponse>(harness, admin.token)
+ .post('/admin/sso-identities/migrate')
+ .body({from_provider_id: fromProviderId});
+ }
+
+ function link(userId: string, subject: string) {
+ return createBuilder<AdminUserSsoIdentityListResponse>(harness, admin.token)
+ .put(`/admin/users/${userId}/sso-identities`)
+ .body({subject});
+ }
+
+ function unlink(userId: string) {
+ return createBuilder<AdminUserSsoIdentityListResponse>(harness, admin.token).delete(
+ `/admin/users/${userId}/sso-identities`,
+ );
+ }
+
+ async function useUsernameMode(): Promise<void> {
+ getConfig().instance.selfHosted = true;
+ await getInstanceConfigRepository().setAccountIdentityMode(AccountIdentityModes.USERNAME, 'setup');
+ await getInstanceConfigRepository().setAppPublicConfig({setup: {configured: true}});
+ }
+
+ it('maps a user to the provider subject and back', async () => {
+ const sub = `itest-admin-sso-${Date.now()}`;
+ const userId = await signInWithSso(sub);
+ const listed = await createBuilder<AdminUserSsoIdentityListResponse>(harness, admin.token)
+ .get(`/admin/users/${userId}/sso-identities`)
+ .execute();
+ expect(listed.sso_identities).toEqual([
+ {provider_id: 'test', subject: sub, user_id: userId, claimed_at: expect.any(String)},
+ ]);
+ const query = new URLSearchParams({provider_id: 'test', subject: sub});
+ const found = await createBuilder<AdminSsoIdentityLookupResponse>(harness, admin.token)
+ .get(`/admin/sso-identities?${query.toString()}`)
+ .execute();
+ expect(found.sso_identity?.user_id).toBe(userId);
+ });
+
+ it('returns an empty list for an account without SSO and null for an unknown subject', async () => {
+ const local = await createTestAccount(harness);
+ const listed = await createBuilder<AdminUserSsoIdentityListResponse>(harness, admin.token)
+ .get(`/admin/users/${local.userId}/sso-identities`)
+ .execute();
+ expect(listed.sso_identities).toEqual([]);
+ const query = new URLSearchParams({provider_id: 'test', subject: 'nobody'});
+ const missing = await createBuilder<AdminSsoIdentityLookupResponse>(harness, admin.token)
+ .get(`/admin/sso-identities?${query.toString()}`)
+ .execute();
+ expect(missing.sso_identity).toBeNull();
+ });
+
+ it('returns UNKNOWN_USER for an account that does not exist', async () => {
+ await createBuilder(harness, admin.token)
+ .get('/admin/users/123456789012345678/sso-identities')
+ .expect(404, 'UNKNOWN_USER')
+ .execute();
+ });
+
+ it('requires the user lookup permission', async () => {
+ const viewer = await setUserACLs(harness, await createTestAccount(harness), [AdminACLs.AUTHENTICATE]);
+ await createBuilder(harness, viewer.token)
+ .get(`/admin/users/${viewer.userId}/sso-identities`)
+ .expect(403)
+ .execute();
+ });
+
+ it('lists an identity bound before the per-account index existed once it signs in again', async () => {
+ const sub = `itest-admin-sso-legacy-${Date.now()}`;
+ const email = createUniqueEmail('sso-admin-legacy');
+ const userId = await signInWithSso(sub, email);
+ await deleteOneOrMany(
+ UserSsoIdentitiesByUser.deleteByPk({user_id: createUserID(BigInt(userId)), provider_id: 'test', subject: sub}),
+ );
+ expect(await listIdentities(userId)).toEqual([]);
+ expect(await signInWithSso(sub, email)).toBe(userId);
+ expect(await listIdentities(userId)).toEqual([{provider_id: 'test', subject: sub}]);
+ });
+
+ describe('after the issuer changes', () => {
+ it('refuses the old account until the subjects are moved, then signs it in', async () => {
+ await setIssuer('test-old');
+ const sub = `itest-admin-sso-move-${Date.now()}`;
+ const email = createUniqueEmail('sso-admin-move');
+ const userId = await signInWithSso(sub, email);
+ await setIssuer('test-new');
+ await completeSso(sub, email).expect(400, 'INVALID_FORM_BODY').execute();
+ const moved = await migrate('test-old').expect(200).execute();
+ expect(moved).toEqual({to_provider_id: 'test-new', moved_count: 1, skipped_count: 0});
+ expect(await signInWithSso(sub, email)).toBe(userId);
+ expect(await listIdentities(userId)).toEqual([{provider_id: 'test-new', subject: sub}]);
+ expect(await new SsoIdentityRepository().findUserId('test-old', sub)).toBeNull();
+ });
+
+ it('leaves a subject that another account already holds under the new issuer', async () => {
+ await setIssuer('test-old');
+ const sub = `itest-admin-sso-taken-${Date.now()}`;
+ const oldOwner = await signInWithSso(sub);
+ await setIssuer('test-new');
+ const newOwner = await signInWithSso(sub);
+ expect(newOwner).not.toBe(oldOwner);
+ const moved = await migrate('test-old').expect(200).execute();
+ expect(moved).toEqual({to_provider_id: 'test-new', moved_count: 0, skipped_count: 1});
+ expect((await new SsoIdentityRepository().findUserId('test-new', sub))?.toString()).toBe(newOwner);
+ expect(await listIdentities(oldOwner)).toEqual([{provider_id: 'test-old', subject: sub}]);
+ });
+
+ it('refuses to move subjects onto the issuer in use', async () => {
+ await migrate('test').expect(400, 'INVALID_FORM_BODY').execute();
+ });
+
+ it('binds a new subject to an account by hand on a username instance', async () => {
+ await useUsernameMode();
+ await enableSso(harness, admin.token, {enforced: false, allowed_domains: []});
+ const oldSub = `itest-admin-sso-old-${Date.now()}`;
+ const newSub = `itest-admin-sso-new-${Date.now()}`;
+ const userId = await signInWithSso(oldSub, null);
+ const linked = await link(userId, newSub).expect(200).execute();
+ expect(linked.sso_identities.map(({provider_id, subject}) => ({provider_id, subject}))).toEqual([
+ {provider_id: 'test', subject: newSub},
+ ]);
+ expect(await signInWithSso(newSub, null)).toBe(userId);
+ expect(await signInWithSso(oldSub, null)).not.toBe(userId);
+ });
+
+ it('refuses to bind a subject another account holds', async () => {
+ const taken = `itest-admin-sso-held-${Date.now()}`;
+ await signInWithSso(taken);
+ const other = await signInWithSso(`itest-admin-sso-other-${Date.now()}`);
+ const body = await link(other, taken).expect(400, 'INVALID_FORM_BODY').execute();
+ expect(body).toMatchObject({
+ errors: [{path: 'subject', code: ValidationErrorCodes.SSO_IDENTITY_LINKED_TO_ANOTHER_ACCOUNT}],
+ });
+ });
+
+ it('unbinds an account so the next sign-in binds it again by email', async () => {
+ const email = createUniqueEmail('sso-admin-unlink');
+ const userId = await signInWithSso(`itest-admin-sso-before-${Date.now()}`, email);
+ const unlinked = await unlink(userId).expect(200).execute();
+ expect(unlinked.sso_identities).toEqual([]);
+ const after = `itest-admin-sso-after-${Date.now()}`;
+ expect(await signInWithSso(after, email)).toBe(userId);
+ expect(await listIdentities(userId)).toEqual([{provider_id: 'test', subject: after}]);
+ });
+
+ it('requires the email update permission to bind or unbind', async () => {
+ const viewer = await setUserACLs(harness, await createTestAccount(harness), [
+ AdminACLs.AUTHENTICATE,
+ AdminACLs.USER_LOOKUP,
+ ]);
+ await createBuilder(harness, viewer.token)
+ .delete(`/admin/users/${viewer.userId}/sso-identities`)
+ .expect(403)
+ .execute();
+ await createBuilder(harness, viewer.token)
+ .post('/admin/sso-identities/migrate')
+ .body({from_provider_id: 'test-old'})
+ .expect(403)
+ .execute();
+ });
+ });
+});
diff --git a/fluxer_api/src/api/admin/tests/audit_coverage/SsoIdentityAdminAuditCases.ts b/fluxer_api/src/api/admin/tests/audit_coverage/SsoIdentityAdminAuditCases.ts
new file mode 100644
index 000000000..9a3c930ab
--- /dev/null
+++ b/fluxer_api/src/api/admin/tests/audit_coverage/SsoIdentityAdminAuditCases.ts
@@ -0,0 +1,113 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import type {AdminAuditCoverageCase} from '@app/api/admin/tests/audit_coverage/AdminAuditCoverage';
+import {SsoIdentityRepository} from '@app/api/auth/services/SsoIdentityRepository';
+import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';
+import {createUserID} from '@app/api/BrandedTypes';
+
+export const SsoIdentityAdminAuditCases: ReadonlyArray<AdminAuditCoverageCase> = [
+ {
+ method: 'GET',
+ route: '/admin/users/:user_id/sso-identities',
+ async prepare({harness}) {
+ const target = await createTestAccount(harness);
+ return {
+ request: {path: `/admin/users/${target.userId}/sso-identities`},
+ expected: {
+ action: 'list_user_sso_identities',
+ targetType: 'user',
+ targetId: target.userId,
+ metadata: {identity_count: '0'},
+ },
+ };
+ },
+ },
+ {
+ method: 'GET',
+ route: '/admin/sso-identities',
+ async prepare({harness}) {
+ const target = await createTestAccount(harness);
+ await new SsoIdentityRepository().tryClaimIdentity({
+ providerId: 'https://idp.example.com',
+ subject: 'audit-subject',
+ userId: createUserID(BigInt(target.userId)),
+ claimedAt: new Date(),
+ });
+ const query = new URLSearchParams({provider_id: 'https://idp.example.com', subject: 'audit-subject'});
+ return {
+ request: {path: `/admin/sso-identities?${query.toString()}`},
+ expected: {
+ action: 'lookup_sso_identity',
+ targetType: 'user',
+ targetId: target.userId,
+ metadata: {provider_id: 'https://idp.example.com', found: 'true'},
+ },
+ };
+ },
+ },
+ {
+ method: 'PUT',
+ route: '/admin/users/:user_id/sso-identities',
+ async prepare({harness}) {
+ const target = await createTestAccount(harness);
+ return {
+ request: {path: `/admin/users/${target.userId}/sso-identities`, body: {subject: 'audit-link-subject'}},
+ expected: {
+ action: 'link_sso_identity',
+ targetType: 'user',
+ targetId: target.userId,
+ metadata: {provider_id: 'sso'},
+ },
+ };
+ },
+ },
+ {
+ method: 'DELETE',
+ route: '/admin/users/:user_id/sso-identities',
+ async prepare({harness}) {
+ const target = await createTestAccount(harness);
+ await new SsoIdentityRepository().tryClaimIdentity({
+ providerId: 'https://idp.example.com',
+ subject: 'audit-unlink-subject',
+ userId: createUserID(BigInt(target.userId)),
+ claimedAt: new Date(),
+ });
+ return {
+ request: {path: `/admin/users/${target.userId}/sso-identities`},
+ expected: {
+ action: 'unlink_sso_identities',
+ targetType: 'user',
+ targetId: target.userId,
+ metadata: {identity_count: '1'},
+ },
+ };
+ },
+ },
+ {
+ method: 'POST',
+ route: '/admin/sso-identities/migrate',
+ async prepare({harness}) {
+ const target = await createTestAccount(harness);
+ await new SsoIdentityRepository().tryClaimIdentity({
+ providerId: 'https://old-idp.example.com',
+ subject: 'audit-migrate-subject',
+ userId: createUserID(BigInt(target.userId)),
+ claimedAt: new Date(),
+ });
+ return {
+ request: {path: '/admin/sso-identities/migrate', body: {from_provider_id: 'https://old-idp.example.com'}},
+ expected: {
+ action: 'migrate_sso_identities',
+ targetType: 'instance_config',
+ targetId: '0',
+ metadata: {
+ from_provider_id: 'https://old-idp.example.com',
+ to_provider_id: 'sso',
+ moved_count: '1',
+ skipped_count: '0',
+ },
+ },
+ };
+ },
+ },
+];
diff --git a/fluxer_api/src/api/admin/tests/audit_coverage/SsoIdentityAdminAuditCoverage.test.ts b/fluxer_api/src/api/admin/tests/audit_coverage/SsoIdentityAdminAuditCoverage.test.ts
new file mode 100644
index 000000000..5fb9eace5
--- /dev/null
+++ b/fluxer_api/src/api/admin/tests/audit_coverage/SsoIdentityAdminAuditCoverage.test.ts
@@ -0,0 +1,6 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {describeAdminAuditCoverage} from '@app/api/admin/tests/audit_coverage/AdminAuditCoverage';
+import {SsoIdentityAdminAuditCases} from '@app/api/admin/tests/audit_coverage/SsoIdentityAdminAuditCases';
+
+describeAdminAuditCoverage('SsoIdentityAdminController', SsoIdentityAdminAuditCases);