Skip to content

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

TypeScript fluxerfluxerapp

test(api): trim admin, auth and OAuth cases, fold ACL checks

Hampus096cc5bd0154
diff --git a/fluxer_api/src/api/admin/tests/AdminApiKeyAuthentication.test.ts b/fluxer_api/src/api/admin/tests/AdminApiKeyAuthentication.test.ts
index 713944e7d..3d8abaff1 100644
--- a/fluxer_api/src/api/admin/tests/AdminApiKeyAuthentication.test.ts
+++ b/fluxer_api/src/api/admin/tests/AdminApiKeyAuthentication.test.ts
@@ -47,55 +47,6 @@ describe('Admin API Key Authentication', () => {
.expect(HTTP_STATUS.UNAUTHORIZED)
.execute();
});
- test('wrong prefix is rejected', async () => {
- const admin = await createTestAccount(harness);
- await setUserACLs(harness, admin, [
- 'admin:authenticate',
- 'admin_api_key:manage',
- 'audit_log:view',
- 'user:lookup',
- 'guild:lookup',
- ]);
- const apiKey = await createAdminApiKeyWithDefaultACLs(harness, admin, 'Prefix Test Key');
- await createBuilder(harness, `Bearer ${apiKey.key}`)
- .get(`/admin/users/${admin.userId}`)
- .expect(HTTP_STATUS.UNAUTHORIZED)
- .execute();
- });
- test('missing prefix is rejected', async () => {
- const admin = await createTestAccount(harness);
- await setUserACLs(harness, admin, [
- 'admin:authenticate',
- 'admin_api_key:manage',
- 'audit_log:view',
- 'user:lookup',
- 'guild:lookup',
- ]);
- const apiKey = await createAdminApiKeyWithDefaultACLs(harness, admin, 'No Prefix Test Key');
- await createBuilder(harness, apiKey.key)
- .get(`/admin/users/${admin.userId}`)
- .expect(HTTP_STATUS.UNAUTHORIZED)
- .execute();
- });
- test('case sensitive prefix', async () => {
- const admin = await createTestAccount(harness);
- await setUserACLs(harness, admin, [
- 'admin:authenticate',
- 'admin_api_key:manage',
- 'audit_log:view',
- 'user:lookup',
- 'guild:lookup',
- ]);
- const apiKey = await createAdminApiKeyWithDefaultACLs(harness, admin, 'Case Test Key');
- await createBuilder(harness, `admin ${apiKey.key}`)
- .get(`/admin/users/${admin.userId}`)
- .expect(HTTP_STATUS.UNAUTHORIZED)
- .execute();
- });
- test('empty key is rejected', async () => {
- await createTestAccount(harness);
- await createBuilder(harness, 'Admin ').get('/admin/users/123456789').expect(HTTP_STATUS.UNAUTHORIZED).execute();
- });
test('cannot authenticate to user endpoints', async () => {
const admin = await createTestAccount(harness);
await setUserACLs(harness, admin, [
diff --git a/fluxer_api/src/api/admin/tests/AdminApiKeyAuthorization.test.ts b/fluxer_api/src/api/admin/tests/AdminApiKeyAuthorization.test.ts
index 29cfe835f..8fc39aa2d 100644
--- a/fluxer_api/src/api/admin/tests/AdminApiKeyAuthorization.test.ts
+++ b/fluxer_api/src/api/admin/tests/AdminApiKeyAuthorization.test.ts
@@ -41,21 +41,4 @@ describe('Admin API Key Authorization', () => {
.expect(HTTP_STATUS.FORBIDDEN)
.execute();
});
- test('GET /admin/api-keys fails without admin_api_key:manage', async () => {
- const admin = await createTestAccount(harness);
- await setUserACLs(harness, admin, ['admin:authenticate', 'admin_api_key:manage']);
- const apiKey = await createAdminApiKey(harness, admin, 'List Test No ACL', [], null);
- await createBuilder(harness, apiKey.token).get('/admin/api-keys').expect(HTTP_STATUS.FORBIDDEN).execute();
- });
- test('DELETE /admin/api-keys/:key_id fails without admin_api_key:manage', async () => {
- const admin = await createTestAccount(harness);
- await setUserACLs(harness, admin, ['admin:authenticate', 'admin_api_key:manage']);
- const keyToDelete = await createAdminApiKey(harness, admin, 'To Delete 2', [], null);
- const deleterKey = await createAdminApiKey(harness, admin, 'Deleter No ACL', [], null);
- await createBuilder(harness, deleterKey.token)
- .delete(`/admin/api-keys/${keyToDelete.keyId}`)
- .body(null)
- .expect(HTTP_STATUS.FORBIDDEN)
- .execute();
- });
});
diff --git a/fluxer_api/src/api/admin/tests/AdminApiKeyLifecycle.test.ts b/fluxer_api/src/api/admin/tests/AdminApiKeyLifecycle.test.ts
index d424db7d8..7dc921f1b 100644
--- a/fluxer_api/src/api/admin/tests/AdminApiKeyLifecycle.test.ts
+++ b/fluxer_api/src/api/admin/tests/AdminApiKeyLifecycle.test.ts
@@ -19,19 +19,6 @@ describe('Admin API Key Lifecycle', () => {
afterEach(async () => {
await harness?.shutdown();
});
- test('expiration validation - zero days rejected', async () => {
- const admin = await createTestAccount(harness);
- await setUserACLs(harness, admin, ['admin:authenticate', 'admin_api_key:manage', 'audit_log:view']);
- await createBuilder(harness, `${admin.token}`)
- .post('/admin/api-keys')
- .body({
- name: 'Test Key',
- expires_in_days: 0,
- acls: ['audit_log:view'],
- })
- .expect(HTTP_STATUS.BAD_REQUEST)
- .executeWithResponse();
- });
test('list does not include secret key', async () => {
const admin = await createTestAccount(harness);
await setUserACLs(harness, admin, [
diff --git a/fluxer_api/src/api/admin/tests/AdminApiKeyRevocation.test.ts b/fluxer_api/src/api/admin/tests/AdminApiKeyRevocation.test.ts
index 10bce540c..6c30635d9 100644
--- a/fluxer_api/src/api/admin/tests/AdminApiKeyRevocation.test.ts
+++ b/fluxer_api/src/api/admin/tests/AdminApiKeyRevocation.test.ts
@@ -17,25 +17,6 @@ describe('Admin API Key Revocation', () => {
beforeEach(async () => {
harness = await createApiTestHarness();
});
- test('revocation requires admin_api_key:manage ACL', async () => {
- const admin1 = await createTestAccount(harness);
- const admin2 = await createTestAccount(harness);
- await setUserACLs(harness, admin1, [
- 'admin:authenticate',
- 'admin_api_key:manage',
- 'audit_log:view',
- 'user:lookup',
- 'guild:lookup',
- ]);
- await setUserACLs(harness, admin2, ['admin:authenticate']);
- const apiKey = await createAdminApiKeyWithDefaultACLs(harness, admin1, 'Admin1 Key');
- await createBuilder(harness, `${admin2.token}`)
- .delete(`/admin/api-keys/${apiKey.keyId}`)
- .body(null)
- .expect(HTTP_STATUS.FORBIDDEN)
- .execute();
- expect(await hasAdminAPIKeyId(harness, admin1.token, apiKey.keyId)).toBe(true);
- });
test('cannot revoke other users keys', async () => {
const admin1 = await createTestAccount(harness);
const admin2 = await createTestAccount(harness);
diff --git a/fluxer_api/src/api/admin/tests/AdminBlocklistUrlDomain.test.ts b/fluxer_api/src/api/admin/tests/AdminBlocklistUrlDomain.test.ts
index 791bb6192..4422607c2 100644
--- a/fluxer_api/src/api/admin/tests/AdminBlocklistUrlDomain.test.ts
+++ b/fluxer_api/src/api/admin/tests/AdminBlocklistUrlDomain.test.ts
@@ -3,7 +3,6 @@
import {createTestAccount, setUserACLs, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';
import {createChannel, createGuild} from '@app/api/channel/tests/ChannelTestUtils';
import {ensureSessionStarted} from '@app/api/message/tests/MessageTestUtils';
-import {getAdminRepository} from '@app/api/middleware/ServiceSingletons';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
@@ -73,21 +72,6 @@ describe('Admin url-domain blocklist patterns', () => {
expect(await check('docs.onrender.com')).toBe(false);
});
- it('records whether the entry is a pattern in the audit log', async () => {
- await add('*shop*.onrender.com', false);
- await add('shop.example.com');
- const logs = (await getAdminRepository().listAllAuditLogsPaginated(1000)).filter(
- (log) => log.action === 'ban_url_domain',
- );
- const metadata = logs.map((log) => Object.fromEntries(log.metadata));
- expect(metadata).toEqual(
- expect.arrayContaining([
- {domain: '*shop*.onrender.com', match_subdomains: 'false', pattern: 'true'},
- {domain: 'shop.example.com', match_subdomains: 'true', pattern: 'false'},
- ]),
- );
- });
-
it('rejects patterns that are too broad or malformed', async () => {
for (const domain of ['*', '*.com', '*shop*.co.uk', '*.onrender.com', '*ab*.onrender.com', 'shop.*.example.com']) {
const json = await createBuilder<ValidationErrorResponse>(harness, admin.token)
@@ -100,27 +84,12 @@ describe('Admin url-domain blocklist patterns', () => {
expect(await list()).toEqual([]);
});
- it('validates the value on update', async () => {
- const json = await createBuilder<ValidationErrorResponse>(harness, admin.token)
- .patch(`/admin/blocklists/url-domain/entries/${encodeURIComponent('*.com')}`)
- .body({})
- .expect(400, 'INVALID_FORM_BODY')
- .execute();
- expect(json.errors?.[0]?.path).toBe('domain');
- });
-
it('stores internationalized domains in ASCII form', async () => {
await add('Bücher.Example.');
expect((await list()).map((entry) => entry.value)).toEqual(['xn--bcher-kva.example']);
expect(await check('www.bücher.example')).toBe(true);
});
- it('accepts an add for a domain that is already blocked', async () => {
- await add('shop.example.com');
- await add('shop.example.com', false);
- expect(await list()).toMatchObject([{value: 'shop.example.com', match_subdomains: false}]);
- });
-
it('removes a pattern through any spelling that canonicalizes to it', async () => {
await add('*shop*.onrender.com');
await createBuilder(harness, admin.token)
diff --git a/fluxer_api/src/api/admin/tests/AdminEndpointsAuthorization.test.ts b/fluxer_api/src/api/admin/tests/AdminEndpointsAuthorization.test.ts
index 65f538d10..af48eec90 100644
--- a/fluxer_api/src/api/admin/tests/AdminEndpointsAuthorization.test.ts
+++ b/fluxer_api/src/api/admin/tests/AdminEndpointsAuthorization.test.ts
@@ -50,6 +50,21 @@ const adminEndpoints: Array<AdminEndpointCase> = [
{method: 'GET', path: '/admin/guilds'},
{method: 'GET', path: '/admin/users'},
{method: 'GET', path: '/admin/messages?channel_id=1'},
+ {method: 'GET', path: '/admin/users/1'},
+ {method: 'GET', path: '/admin/guilds/1'},
+ {method: 'GET', path: '/admin/guilds/1/members'},
+ {method: 'DELETE', path: '/admin/guilds/1/members/2'},
+ {method: 'PUT', path: '/admin/guilds/1/bans/2'},
+ {method: 'DELETE', path: '/admin/guilds/1/bans/2'},
+ {method: 'GET', path: '/admin/audit-logs?limit=10'},
+ {method: 'GET', path: '/admin/api-keys'},
+ {method: 'GET', path: '/admin/api-keys/1'},
+ {method: 'DELETE', path: '/admin/api-keys/1'},
+ {method: 'PUT', path: '/admin/jobs/1/cancellation'},
+ {method: 'GET', path: '/admin/gateway/stats'},
+ {method: 'GET', path: '/admin/gateway/memory-stats'},
+ {method: 'GET', path: '/admin/gateway/voice-state-counts'},
+ {method: 'POST', path: '/admin/gateway/reloads'},
];
describe('Admin Endpoints Authorization', () => {
@@ -67,34 +82,10 @@ describe('Admin Endpoints Authorization', () => {
test('admin endpoints require proper ACLs', async () => {
const admin = await createTestAccount(harness);
await setUserACLs(harness, admin, ['admin:authenticate']);
- for (const endpoint of adminEndpoints.slice(0, 10)) {
+ for (const endpoint of adminEndpoints) {
await withMethod(createBuilder(harness, `${admin.token}`), endpoint.method, endpoint.path, endpoint.body)
.expect(HTTP_STATUS.FORBIDDEN)
.execute();
}
});
- test('user lookup endpoint requires user:lookup ACL', async () => {
- const admin = await createTestAccount(harness);
- await setUserACLs(harness, admin, ['admin:authenticate', 'admin_api_key:manage', 'audit_log:view']);
- await createBuilder(harness, `${admin.token}`)
- .get(`/admin/users/${admin.userId}`)
- .expect(HTTP_STATUS.FORBIDDEN)
- .execute();
- });
- test('guild lookup endpoint requires guild:lookup ACL', async () => {
- const admin = await createTestAccount(harness);
- await setUserACLs(harness, admin, ['admin:authenticate', 'admin_api_key:manage', 'audit_log:view']);
- await createBuilder(harness, `${admin.token}`)
- .get('/admin/guilds/123456789')
- .expect(HTTP_STATUS.FORBIDDEN)
- .execute();
- });
- test('audit logs endpoint requires audit_log:view ACL', async () => {
- const admin = await createTestAccount(harness);
- await setUserACLs(harness, admin, ['admin:authenticate', 'admin_api_key:manage', 'user:lookup']);
- await createBuilder(harness, `${admin.token}`)
- .get('/admin/audit-logs?limit=10')
- .expect(HTTP_STATUS.FORBIDDEN)
- .execute();
- });
});
diff --git a/fluxer_api/src/api/admin/tests/AdminGuildRoutes.test.ts b/fluxer_api/src/api/admin/tests/AdminGuildRoutes.test.ts
index 10bb9045c..7c127240b 100644
--- a/fluxer_api/src/api/admin/tests/AdminGuildRoutes.test.ts
+++ b/fluxer_api/src/api/admin/tests/AdminGuildRoutes.test.ts
@@ -22,13 +22,4 @@ describe('Admin guild routes', () => {
.expect(HTTP_STATUS.FORBIDDEN, 'MISSING_ACL')
.execute();
});
- test('GET /admin/guilds/{guild_id}/members requires guild:list:members', async () => {
- const admin = await createTestAccount(harness);
- await setUserACLs(harness, admin, ['admin:authenticate', 'guild:lookup']);
- const guild = await createGuild(harness, admin.token, `Member ACL Guild ${Date.now()}`);
- await createBuilder(harness, `${admin.token}`)
- .get(`/admin/guilds/${guild.id}/members`)
- .expect(HTTP_STATUS.FORBIDDEN, 'MISSING_ACL')
- .execute();
- });
});
diff --git a/fluxer_api/src/api/admin/tests/AdminGuildSystemModeration.test.ts b/fluxer_api/src/api/admin/tests/AdminGuildSystemModeration.test.ts
index 0108d838c..ca9d866f3 100644
--- a/fluxer_api/src/api/admin/tests/AdminGuildSystemModeration.test.ts
+++ b/fluxer_api/src/api/admin/tests/AdminGuildSystemModeration.test.ts
@@ -4,7 +4,6 @@ import {createTestAccount, setUserACLs, type TestAccount} from '@app/api/auth/te
import {setupTestGuildWithMembers} from '@app/api/guild/tests/GuildTestUtils';
import {getAdminRepository} from '@app/api/middleware/ServiceSingletons';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {NoopGatewayService} from '@app/api/test/NoopGatewayService';
import {HTTP_STATUS} from '@app/api/test/TestConstants';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
@@ -53,14 +52,6 @@ async function latestAdminAuditLog(action: string, targetId: string) {
return logs.find((log) => log.action === action && log.targetId.toString() === targetId);
}
-function captureGuildDispatches() {
- const events: Array<{event: string; data: unknown}> = [];
- vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild').mockImplementation(async (params) => {
- events.push({event: params.event, data: params.data});
- });
- return events;
-}
-
describe('Admin guild moderation as the system user', () => {
let harness: ApiTestHarness;
@@ -69,7 +60,6 @@ describe('Admin guild moderation as the system user', () => {
});
afterEach(async () => {
- vi.restoreAllMocks();
await harness?.shutdown();
});
@@ -77,7 +67,6 @@ describe('Admin guild moderation as the system user', () => {
const {owner, members, guild} = await setupTestGuildWithMembers(harness, 1);
const target = members[0]!;
const staff = await createStaff(harness, [AdminACLs.GUILD_KICK_MEMBER]);
- const dispatches = captureGuildDispatches();
await createBuilder(harness, staff.token)
.delete(`/admin/guilds/${guild.id}/members/${target.userId}`)
@@ -97,13 +86,6 @@ describe('Admin guild moderation as the system user', () => {
expect(auditLog.users.map((user) => user.id)).toContain(SYSTEM_USER_ID);
expect(JSON.stringify(auditLog)).not.toContain(staff.userId);
- expect(dispatches.map((dispatch) => dispatch.event)).toContain('GUILD_MEMBER_REMOVE');
- expect(dispatches.find((dispatch) => dispatch.event === 'GUILD_AUDIT_LOG_ENTRY_CREATE')?.data).toMatchObject({
- user_id: SYSTEM_USER_ID,
- });
- expect(JSON.stringify(dispatches)).not.toContain(staff.userId);
- expect(JSON.stringify(dispatches)).not.toContain(STAFF_REASON);
-
const adminLog = await latestAdminAuditLog('kick_member', target.userId);
expect(adminLog?.adminUserId.toString()).toBe(staff.userId);
expect(adminLog?.auditLogReason).toBe(STAFF_REASON);
@@ -118,7 +100,6 @@ describe('Admin guild moderation as the system user', () => {
const {owner, members, guild} = await setupTestGuildWithMembers(harness, 1);
const target = members[0]!;
const staff = await createStaff(harness, [AdminACLs.GUILD_BAN_MEMBER]);
- const dispatches = captureGuildDispatches();
await createBuilder(harness, staff.token)
.put(`/admin/guilds/${guild.id}/bans/${target.userId}`)
@@ -137,12 +118,6 @@ describe('Admin guild moderation as the system user', () => {
expect(entry?.reason).toBe('Underage member');
expect(JSON.stringify(auditLog)).not.toContain(staff.userId);
- expect(dispatches.map((dispatch) => dispatch.event)).toEqual(
- expect.arrayContaining(['GUILD_BAN_ADD', 'GUILD_MEMBER_REMOVE', 'GUILD_AUDIT_LOG_ENTRY_CREATE']),
- );
- expect(JSON.stringify(dispatches)).not.toContain(staff.userId);
- expect(JSON.stringify(dispatches)).not.toContain(STAFF_REASON);
-
const adminLog = await latestAdminAuditLog('ban_member', target.userId);
expect(adminLog?.adminUserId.toString()).toBe(staff.userId);
expect(adminLog?.auditLogReason).toBe(STAFF_REASON);
@@ -150,59 +125,6 @@ describe('Admin guild moderation as the system user', () => {
expect(adminLog?.metadata.get('reason')).toBe('Underage member');
});
- test('ban without a reason stores no reason', async () => {
- const {owner, members, guild} = await setupTestGuildWithMembers(harness, 1);
- const target = members[0]!;
- const staff = await createStaff(harness, [AdminACLs.GUILD_BAN_MEMBER]);
-
- await createBuilder(harness, staff.token)
- .put(`/admin/guilds/${guild.id}/bans/${target.userId}`)
- .header('X-Audit-Log-Reason', STAFF_REASON)
- .body({})
- .expect(HTTP_STATUS.NO_CONTENT)
- .execute();
-
- const bans = await listBans(harness, owner, guild.id);
- expect(bans[0]).toMatchObject({moderator_id: SYSTEM_USER_ID, reason: null});
- const auditLog = await listGuildAuditLog(harness, owner, guild.id, AuditLogActionType.MEMBER_BAN_ADD);
- expect(auditLog.audit_log_entries[0]?.reason).toBeUndefined();
- });
-
- test('unban removes the ban as the system user', async () => {
- const {owner, members, guild} = await setupTestGuildWithMembers(harness, 1);
- const target = members[0]!;
- const staff = await createStaff(harness, [AdminACLs.GUILD_BAN_MEMBER]);
- await createBuilder(harness, staff.token)
- .put(`/admin/guilds/${guild.id}/bans/${target.userId}`)
- .body({})
- .expect(HTTP_STATUS.NO_CONTENT)
- .execute();
- const dispatches = captureGuildDispatches();
-
- await createBuilder(harness, staff.token)
- .delete(`/admin/guilds/${guild.id}/bans/${target.userId}`)
- .header('X-Audit-Log-Reason', STAFF_REASON)
- .expect(HTTP_STATUS.NO_CONTENT)
- .execute();
-
- expect(await listBans(harness, owner, guild.id)).toEqual([]);
- const auditLog = await listGuildAuditLog(harness, owner, guild.id, AuditLogActionType.MEMBER_BAN_REMOVE);
- expect(auditLog.audit_log_entries[0]).toMatchObject({user_id: SYSTEM_USER_ID, target_id: target.userId});
- expect(auditLog.audit_log_entries[0]?.reason).toBeUndefined();
- expect(dispatches.map((dispatch) => dispatch.event)).toContain('GUILD_BAN_REMOVE');
- expect(JSON.stringify(dispatches)).not.toContain(staff.userId);
-
- const adminLog = await latestAdminAuditLog('unban_member', target.userId);
- expect(adminLog?.adminUserId.toString()).toBe(staff.userId);
- expect(adminLog?.auditLogReason).toBe(STAFF_REASON);
- expect(adminLog?.metadata.get('acl')).toBe(AdminACLs.GUILD_BAN_MEMBER);
-
- await createBuilder(harness, staff.token)
- .delete(`/admin/guilds/${guild.id}/bans/${target.userId}`)
- .expect(HTTP_STATUS.BAD_REQUEST)
- .execute();
- });
-
test('kicking or banning the guild owner is refused', async () => {
const {owner, guild} = await setupTestGuildWithMembers(harness, 0);
const staff = await createStaff(harness, [AdminACLs.GUILD_KICK_MEMBER, AdminACLs.GUILD_BAN_MEMBER]);
@@ -225,51 +147,4 @@ describe('Admin guild moderation as the system user', () => {
expect(await latestAdminAuditLog('kick_member', owner.userId)).toBeUndefined();
expect(await latestAdminAuditLog('ban_member', owner.userId)).toBeUndefined();
});
-
- test('unknown guilds are reported as unknown', async () => {
- const target = await createTestAccount(harness);
- const staff = await createStaff(harness, [AdminACLs.GUILD_KICK_MEMBER, AdminACLs.GUILD_BAN_MEMBER]);
- const missingGuildId = '900000000000000001';
-
- await createBuilder(harness, staff.token)
- .delete(`/admin/guilds/${missingGuildId}/members/${target.userId}`)
- .expect(HTTP_STATUS.NOT_FOUND, 'UNKNOWN_GUILD')
- .execute();
- await createBuilder(harness, staff.token)
- .put(`/admin/guilds/${missingGuildId}/bans/${target.userId}`)
- .body({})
- .expect(HTTP_STATUS.NOT_FOUND, 'UNKNOWN_GUILD')
- .execute();
- await createBuilder(harness, staff.token)
- .delete(`/admin/guilds/${missingGuildId}/bans/${target.userId}`)
- .expect(HTTP_STATUS.NOT_FOUND, 'UNKNOWN_GUILD')
- .execute();
- });
-
- test('each route still requires its Admin ACL', async () => {
- const {owner, members, guild} = await setupTestGuildWithMembers(harness, 1);
- const target = members[0]!;
- const kicker = await createStaff(harness, [AdminACLs.GUILD_KICK_MEMBER]);
- const banner = await createStaff(harness, [AdminACLs.GUILD_BAN_MEMBER]);
-
- await createBuilder(harness, banner.token)
- .delete(`/admin/guilds/${guild.id}/members/${target.userId}`)
- .expect(HTTP_STATUS.FORBIDDEN, 'MISSING_ACL')
- .execute();
- await createBuilder(harness, kicker.token)
- .put(`/admin/guilds/${guild.id}/bans/${target.userId}`)
- .body({})
- .expect(HTTP_STATUS.FORBIDDEN, 'MISSING_ACL')
- .execute();
- await createBuilder(harness, kicker.token)
- .delete(`/admin/guilds/${guild.id}/bans/${target.userId}`)
- .expect(HTTP_STATUS.FORBIDDEN, 'MISSING_ACL')
- .execute();
-
- expect(await listBans(harness, owner, guild.id)).toEqual([]);
- await createBuilder(harness, owner.token)
- .get(`/guilds/${guild.id}/members/${target.userId}`)
- .expect(HTTP_STATUS.OK)
- .execute();
- });
});
diff --git a/fluxer_api/src/api/admin/tests/AdminJobsAndBulkJobs.test.ts b/fluxer_api/src/api/admin/tests/AdminJobsAndBulkJobs.test.ts
index 0638a29b8..c851e4e4c 100644
--- a/fluxer_api/src/api/admin/tests/AdminJobsAndBulkJobs.test.ts
+++ b/fluxer_api/src/api/admin/tests/AdminJobsAndBulkJobs.test.ts
@@ -11,15 +11,6 @@ describe('Admin jobs and bulk jobs', () => {
beforeEach(async () => {
harness = await createApiTestHarness();
});
- test('job cancellation requires jobs:cancel rather than jobs:view', async () => {
- const admin = await createTestAccount(harness);
- const updated = await setUserACLs(harness, admin, ['admin:authenticate', 'jobs:view']);
- await createBuilder(harness, `${updated.token}`)
- .put('/admin/jobs/123456789012345678/cancellation')
- .body({})
- .expect(HTTP_STATUS.FORBIDDEN)
- .execute();
- });
test('holding one bulk ACL does not authorise another task', async () => {
const admin = await createTestAccount(harness);
const updated = await setUserACLs(harness, admin, ['admin:authenticate', 'bulk:update:user_flags']);
diff --git a/fluxer_api/src/api/admin/tests/AdminReportNotes.test.ts b/fluxer_api/src/api/admin/tests/AdminReportNotes.test.ts
index 2e2519248..9ef960a79 100644
--- a/fluxer_api/src/api/admin/tests/AdminReportNotes.test.ts
+++ b/fluxer_api/src/api/admin/tests/AdminReportNotes.test.ts
@@ -69,28 +69,6 @@ describe('report notes', () => {
return logs.filter((log) => log.action === action);
}
- test('adds notes, lists them oldest first and returns them with the report', async () => {
- const reportId = await seedReport();
-
- const first = await addNote(admin, reportId, ' Reporter sent more context by email ')
- .expect(HTTP_STATUS.OK)
- .execute();
- const second = await addNote(admin, reportId, 'Waiting on the guild owner').expect(HTTP_STATUS.OK).execute();
-
- expect(first).toEqual({
- note_id: expect.any(String),
- author_id: admin.userId,
- body: 'Reporter sent more context by email',
- created_at: expect.any(String),
- });
- expect(await listNotes(admin, reportId).expect(HTTP_STATUS.OK).execute()).toEqual({notes: [first, second]});
- const detail = await createBuilder<{notes?: Array<ReportNoteResponse>}>(harness, admin.token)
- .get(`/admin/reports/${reportId}`)
- .expect(HTTP_STATUS.OK)
- .execute();
- expect(detail.notes).toEqual([first, second]);
- });
-
test('records the note in the audit log without its body', async () => {
const reportId = await seedReport();
@@ -108,42 +86,6 @@ describe('report notes', () => {
});
});
- test.each([
- ['empty', ''],
- ['blank', ' '],
- ['too long', 'x'.repeat(2001)],
- ['not a string', 42],
- ])('refuses a %s body and stores nothing', async (_, body) => {
- const reportId = await seedReport();
-
- const response = await addNote(admin, reportId, body)
- .expect(HTTP_STATUS.BAD_REQUEST, 'INVALID_FORM_BODY')
- .execute();
-
- expect(response.errors?.[0]?.path).toBe('body');
- expect(await repository.listNotes(reportId)).toEqual([]);
- expect(await auditEntries('annotate_report')).toEqual([]);
- });
-
- test('accepts a body of 2000 characters', async () => {
- const reportId = await seedReport();
-
- const note = await addNote(admin, reportId, 'x'.repeat(2000)).expect(HTTP_STATUS.OK).execute();
-
- expect(note.body).toHaveLength(2000);
- });
-
- test('an unknown report gives UNKNOWN_REPORT and stores nothing', async () => {
- sequence += 1n;
- const missing = createReportID(sequence);
-
- await addNote(admin, missing, 'Note').expect(HTTP_STATUS.NOT_FOUND, 'UNKNOWN_REPORT').execute();
- await listNotes(admin, missing).expect(HTTP_STATUS.NOT_FOUND, 'UNKNOWN_REPORT').execute();
-
- expect(await repository.listNotes(missing)).toEqual([]);
- expect(await auditEntries('annotate_report')).toEqual([]);
- });
-
test('adding a note needs REPORT_RESOLVE', async () => {
const reportId = await seedReport();
const viewer = await setUserACLs(harness, await createTestAccount(harness), [
diff --git a/fluxer_api/src/api/admin/tests/AdminSearchEndpoints.test.ts b/fluxer_api/src/api/admin/tests/AdminSearchEndpoints.test.ts
index 49ba2dba7..efb9e4f3c 100644
--- a/fluxer_api/src/api/admin/tests/AdminSearchEndpoints.test.ts
+++ b/fluxer_api/src/api/admin/tests/AdminSearchEndpoints.test.ts
@@ -35,45 +35,3 @@ describe('Admin Search Endpoints', () => {
});
});
});
-
-describe('Admin Search Endpoints without a search backend', () => {
- let harness: ApiTestHarness;
- beforeEach(async () => {
- harness = await createApiTestHarness({search: 'disabled'});
- });
- afterEach(async () => {
- await harness.shutdown();
- });
- test('GET /admin/guilds answers 403 FEATURE_TEMPORARILY_DISABLED', async () => {
- const admin = await createTestAccount(harness);
- await setUserACLs(harness, admin, ['admin:authenticate', 'guild:lookup']);
- await createBuilder(harness, `${admin.token}`)
- .get('/admin/guilds?q=test&limit=10&offset=0')
- .expect(HTTP_STATUS.FORBIDDEN, 'FEATURE_TEMPORARILY_DISABLED')
- .execute();
- });
- test('GET /admin/users with q answers 403 FEATURE_TEMPORARILY_DISABLED', async () => {
- const admin = await createTestAccount(harness);
- await setUserACLs(harness, admin, ['admin:authenticate', 'user:lookup']);
- await createBuilder(harness, `${admin.token}`)
- .get('/admin/users?q=test&limit=10&offset=0')
- .expect(HTTP_STATUS.FORBIDDEN, 'FEATURE_TEMPORARILY_DISABLED')
- .execute();
- });
- test('GET /admin/reports answers 403 FEATURE_TEMPORARILY_DISABLED on the status branch', async () => {
- const admin = await createTestAccount(harness);
- await setUserACLs(harness, admin, ['admin:authenticate', 'report:view']);
- await createBuilder(harness, `${admin.token}`)
- .get('/admin/reports?status=pending&limit=10&offset=0')
- .expect(HTTP_STATUS.FORBIDDEN, 'FEATURE_TEMPORARILY_DISABLED')
- .execute();
- });
- test('GET /admin/reports answers 403 FEATURE_TEMPORARILY_DISABLED on the search branch', async () => {
- const admin = await createTestAccount(harness);
- await setUserACLs(harness, admin, ['admin:authenticate', 'report:view']);
- await createBuilder(harness, `${admin.token}`)
- .get('/admin/reports?q=example&limit=10&offset=0')
- .expect(HTTP_STATUS.FORBIDDEN, 'FEATURE_TEMPORARILY_DISABLED')
- .execute();
- });
-});
diff --git a/fluxer_api/src/api/admin/tests/AdminSyntheticUserServiceGuards.test.ts b/fluxer_api/src/api/admin/tests/AdminSyntheticUserServiceGuards.test.ts
index 0b4998e9d..fb95473a4 100644
--- a/fluxer_api/src/api/admin/tests/AdminSyntheticUserServiceGuards.test.ts
+++ b/fluxer_api/src/api/admin/tests/AdminSyntheticUserServiceGuards.test.ts
@@ -1,11 +1,9 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import {createGuildID, createUserID, type UserID} from '@app/api/BrandedTypes';
+import {createUserID, type UserID} from '@app/api/BrandedTypes';
import type {ChannelRepository} from '@app/api/channel/ChannelRepository';
import type {CrosspostWorkerService} from '@app/api/channel/services/message/CrosspostPropagation';
import {UserMessageDeletionService} from '@app/api/channel/services/message/UserMessageDeletionService';
-import type {GuildRepository} from '@app/api/guild/repositories/GuildRepository';
-import {GuildMemberOperationsService} from '@app/api/guild/services/member/GuildMemberOperationsService';
import type {IPurgeQueue} from '@app/api/infrastructure/CachePurgeQueue';
import type {IGatewayService} from '@app/api/infrastructure/IGatewayService';
import type {IStorageService} from '@app/api/infrastructure/IStorageService';
@@ -18,8 +16,6 @@ const SYNTHETIC_USER_IDS: Array<[string, UserID]> = [
['1', createUserID(DELETED_USER_ID)],
];
-const GUILD_ID = createGuildID(7000n);
-
function unusableDependency(): object {
return new Proxy(
{},
@@ -42,49 +38,10 @@ function createMessageDeletionService(): UserMessageDeletionService {
});
}
-function createGuildMemberOperationsService(): GuildMemberOperationsService {
- const guildRepository = {
- async findUnique() {
- return {id: GUILD_ID, features: new Set(), memberCount: 0};
- },
- async getMember() {
- return null;
- },
- } as unknown as GuildRepository;
- const unusable = unusableDependency();
- return new GuildMemberOperationsService(
- guildRepository,
- unusable as never,
- unusable as never,
- unusable as never,
- unusable as never,
- unusable as never,
- unusable as never,
- unusable as never,
- unusable as never,
- unusable as never,
- unusable as never,
- );
-}
-
describe('service level guards for synthetic accounts', () => {
test.each(SYNTHETIC_USER_IDS)('deleteUserMessagesBulk refuses user %s', async (_label, userId) => {
await expect(createMessageDeletionService().deleteUserMessagesBulk(userId)).rejects.toBeInstanceOf(
UnknownUserError,
);
});
- test.each(SYNTHETIC_USER_IDS)('addUserToGuild refuses user %s', async (_label, userId) => {
- await expect(
- createGuildMemberOperationsService().addUserToGuild(
- {
- userId,
- guildId: GUILD_ID,
- skipBanCheck: true,
- skipGuildLimitCheck: true,
- requestCache: new Map(),
- } as never,
- unusableDependency() as never,
- ),
- ).rejects.toBeInstanceOf(UnknownUserError);
- });
});
diff --git a/fluxer_api/src/api/admin/tests/AdminUserChangeLogAndFlags.test.ts b/fluxer_api/src/api/admin/tests/AdminUserChangeLogAndFlags.test.ts
index 5e9177d75..420eacbeb 100644
--- a/fluxer_api/src/api/admin/tests/AdminUserChangeLogAndFlags.test.ts
+++ b/fluxer_api/src/api/admin/tests/AdminUserChangeLogAndFlags.test.ts
@@ -2,7 +2,6 @@
import {createTestAccount, setUserACLs} from '@app/api/auth/tests/AuthTestUtils';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {NoopWorkerService} from '@app/api/test/NoopWorkerService';
import {HTTP_STATUS} from '@app/api/test/TestConstants';
import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
@@ -52,37 +51,6 @@ describe('Admin User Change Log and Flags', () => {
.execute();
});
});
- describe('PATCH /admin/users/{user_id}/email', () => {
- test('queues a Stripe customer email sync for users with a Stripe customer', async () => {
- const admin = await createTestAccount(harness);
- await setUserACLs(harness, admin, [AdminACLs.AUTHENTICATE, AdminACLs.WILDCARD]);
- const target = await createTestAccount(harness);
- await createBuilderWithoutAuth(harness)
- .post(`/test/users/${target.userId}/premium`)
- .body({stripe_customer_id: 'cus_admin_email_sync'})
- .expect(HTTP_STATUS.OK)
- .execute();
- const addJob = vi.spyOn(NoopWorkerService.prototype, 'addJob');
- await createBuilder(harness, `${admin.token}`)
- .patch(`/admin/users/${target.userId}/email`)
- .body({email: `admin-changed-${Date.now()}@example.com`})
- .expect(HTTP_STATUS.OK)
- .execute();
- expect(addJob).toHaveBeenCalledWith('syncStripeCustomerEmail', {userId: target.userId});
- });
- test('does not queue a Stripe customer email sync for users without a Stripe customer', async () => {
- const admin = await createTestAccount(harness);
- await setUserACLs(harness, admin, [AdminACLs.AUTHENTICATE, AdminACLs.WILDCARD]);
- const target = await createTestAccount(harness);
- const addJob = vi.spyOn(NoopWorkerService.prototype, 'addJob');
- await createBuilder(harness, `${admin.token}`)
- .patch(`/admin/users/${target.userId}/email`)
- .body({email: `admin-changed-${Date.now()}@example.com`})
- .expect(HTTP_STATUS.OK)
- .execute();
- expect(addJob).not.toHaveBeenCalledWith('syncStripeCustomerEmail', expect.anything());
- });
- });
describe('PUT /admin/users/{user_id}/email-verification', () => {
test('verifying email clears email_bounced', async () => {
const admin = await createTestAccount(harness);
diff --git a/fluxer_api/src/api/admin/tests/DiscoveryAdminOperations.test.ts b/fluxer_api/src/api/admin/tests/DiscoveryAdminOperations.test.ts
index 0cdf89f78..e2f740005 100644
--- a/fluxer_api/src/api/admin/tests/DiscoveryAdminOperations.test.ts
+++ b/fluxer_api/src/api/admin/tests/DiscoveryAdminOperations.test.ts
@@ -3,12 +3,11 @@
import {createTestAccount, setUserACLs, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';
import {createGuildID} from '@app/api/BrandedTypes';
import {GuildDiscoveryRepository} from '@app/api/guild/repositories/GuildDiscoveryRepository';
-import {createGuild, getGuild} from '@app/api/guild/tests/GuildTestUtils';
+import {createGuild} from '@app/api/guild/tests/GuildTestUtils';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
import {HTTP_STATUS, TEST_IDS} from '@app/api/test/TestConstants';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
import {DiscoveryApplicationStatus, DiscoveryCategories} from '@fluxer/constants/src/DiscoveryConstants';
-import {GuildFeatures} from '@fluxer/constants/src/GuildConstants';
import type {
DiscoveryAdminListedGuildResponse,
DiscoveryApplicationResponse,
@@ -82,26 +81,6 @@ describe('Discovery Admin Operations', () => {
afterEach(async () => {
await harness?.shutdown();
});
- describe('remove', () => {
- test('should remove an approved guild from discovery', async () => {
- const {owner, guild} = await createGuildWithApplication(harness, 'Remove Test Guild');
- const admin = await createAdminWithACLs(harness, ['discovery:review', 'discovery:remove', 'discovery:review']);
- await createBuilder(harness, `${admin.token}`)
- .patch(`/admin/discovery/applications/${guild.id}`)
- .body({status: 'approved'})
- .expect(HTTP_STATUS.OK)
- .execute();
- expect((await getGuild(harness, owner.token, guild.id)).features).toContain(GuildFeatures.DISCOVERABLE);
- const result = await createBuilder<DiscoveryApplicationResponse>(harness, `${admin.token}`)
- .delete(`/admin/discovery/listings/${guild.id}`)
- .body({reason: 'Violated community guidelines'})
- .expect(HTTP_STATUS.OK)
- .execute();
- expect(result.status).toBe('removed');
- const guildData = await getGuild(harness, owner.token, guild.id);
- expect(guildData.features).not.toContain(GuildFeatures.DISCOVERABLE);
- });
- });
describe('list listed guilds', () => {
test('returns every approved listing when there are more than a thousand', async () => {
await seedApprovedListings(1001);
diff --git a/fluxer_api/src/api/admin/tests/InstanceConfigBilling.test.ts b/fluxer_api/src/api/admin/tests/InstanceConfigBilling.test.ts
index 648d01445..9b1c6e229 100644
--- a/fluxer_api/src/api/admin/tests/InstanceConfigBilling.test.ts
+++ b/fluxer_api/src/api/admin/tests/InstanceConfigBilling.test.ts
@@ -3,16 +3,18 @@
import type {TestAccount} from '@app/api/auth/tests/AuthTestUtils';
import {createTestAccount, setUserACLs} from '@app/api/auth/tests/AuthTestUtils';
import {getConfig} from '@app/api/Config';
+import {executeQuery} from '@app/api/database/CassandraQueryExecution';
import {getCachedInstancePremiumMode, setCachedInstancePremiumMode} from '@app/api/limits/InstancePremiumModeCache';
import {getAdminRepository, getInstanceConfigRepository} from '@app/api/middleware/ServiceSingletons';
import {getStoredBillingConfig, setStoredBillingConfig} from '@app/api/stripe/BillingConfigCache';
+import {InstanceConfiguration} from '@app/api/Tables';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
import {HTTP_STATUS} from '@app/api/test/TestConstants';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
import type {InstanceConfigResponse} from '@fluxer/schema/src/domains/admin/AdminSchemas';
-import {afterAll, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
const OPERATOR_SECRET_KEY = 'sk_test_operator_secret_value';
const OPERATOR_WEBHOOK_SECRET = 'whsec_operator_secret_value';
@@ -37,24 +39,28 @@ function restoreGlobalState(state: GlobalState): void {
setStoredBillingConfig(state.storedBilling);
}
-function useInstanceHarness(selfHosted: boolean) {
- const context: {harness: ApiTestHarness} = {harness: undefined as unknown as ApiTestHarness};
+function useInstanceHarness({selfHosted}: {selfHosted: boolean}) {
+ let harness: ApiTestHarness;
let original: GlobalState;
beforeAll(async () => {
original = captureGlobalState();
getConfig().instance.selfHosted = selfHosted;
- context.harness = await createApiTestHarness();
+ harness = await createApiTestHarness();
});
beforeEach(async () => {
- await context.harness.reset();
+ await harness.reset();
setStoredBillingConfig(null);
setCachedInstancePremiumMode('everyone');
});
afterAll(async () => {
- await context.harness.shutdown();
+ await harness.shutdown();
restoreGlobalState(original);
});
- return context;
+ return {
+ get harness(): ApiTestHarness {
+ return harness;
+ },
+ };
}
async function createAdmin(harness: ApiTestHarness): Promise<TestAccount> {
@@ -87,7 +93,7 @@ const OPERATOR_BILLING = {
};
describe('instance config billing on a self-hosted instance', () => {
- const context = useInstanceHarness(true);
+ const context = useInstanceHarness({selfHosted: true});
it('rejects enabling billing while the premium mode is everyone', async () => {
const admin = await createAdmin(context.harness);
@@ -225,16 +231,20 @@ describe('instance config billing on a self-hosted instance', () => {
it('re-checks the stored premium mode right before the billing write', async () => {
const admin = await createAdmin(context.harness);
+ await patchConfig(context.harness, admin, {policy: {premium_mode: 'mirror'}}).execute();
const repository = getInstanceConfigRepository();
- const stored = await repository.getInstancePolicyConfig();
- const spy = vi.spyOn(repository, 'getInstancePolicyConfig').mockResolvedValue({...stored, premium_mode: 'mirror'});
- try {
- await patchConfig(context.harness, admin, {billing: {enabled: true}})
- .expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.INVALID_FORM_BODY)
- .execute();
- } finally {
- spy.mockRestore();
- }
+ await executeQuery(
+ InstanceConfiguration.upsertAll({
+ key: 'instance_policy_config',
+ value: JSON.stringify({premium_mode: 'everyone'}),
+ updated_at: new Date(),
+ }),
+ );
+ expect((await repository.getInstancePolicyConfig()).premium_mode).toBe('mirror');
+ expect((await repository.readStoredInstancePolicyConfig()).premium_mode).toBe('everyone');
+ await patchConfig(context.harness, admin, {billing: {enabled: true}})
+ .expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.INVALID_FORM_BODY)
+ .execute();
const current = await createBuilder<InstanceConfigResponse>(context.harness, admin.token)
.get('/admin/instance/config')
.execute();
@@ -267,36 +277,10 @@ describe('instance config billing on a self-hosted instance', () => {
expect(serialized).not.toContain(OPERATOR_SECRET_KEY);
expect(serialized).not.toContain(OPERATOR_WEBHOOK_SECRET);
});
-
- it('stores the premium name and info URL and resets the name to the self-hosted default', async () => {
- const admin = await createAdmin(context.harness);
- const initial = await createBuilder<InstanceConfigResponse>(context.harness, admin.token)
- .get('/admin/instance/config')
- .execute();
- expect(initial.app_public.branding).toMatchObject({premium_product_name: 'Premium', premium_info_url: null});
- const named = await patchConfig(context.harness, admin, {
- app_public: {branding: {premium_product_name: 'Gold', premium_info_url: 'https://example.com/gold'}},
- }).execute();
- expect(named.app_public.branding).toMatchObject({
- premium_product_name: 'Gold',
- premium_info_url: 'https://example.com/gold',
- });
- const renamedProduct = await patchConfig(context.harness, admin, {
- app_public: {branding: {product_name: 'Example Chat'}},
- }).execute();
- expect(renamedProduct.app_public.branding.premium_product_name).toBe('Gold');
- const reset = await patchConfig(context.harness, admin, {
- app_public: {branding: {product_name: 'Example Chat', premium_product_name: null, premium_info_url: null}},
- }).execute();
- expect(reset.app_public.branding).toMatchObject({premium_product_name: 'Premium', premium_info_url: null});
- await patchConfig(context.harness, admin, {app_public: {branding: {premium_info_url: 'javascript:alert(1)'}}})
- .expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.INVALID_FORM_BODY)
- .execute();
- });
});
describe('instance config billing on a hosted instance', () => {
- const context = useInstanceHarness(false);
+ const context = useInstanceHarness({selfHosted: false});
it('keeps the Plutonium default and env billing', async () => {
const admin = await createAdmin(context.harness);
@@ -332,17 +316,4 @@ describe('instance config billing on a hosted instance', () => {
expect(current.app_public.branding).toMatchObject({premium_product_name: 'Plutonium', premium_info_url: null});
expect(getStoredBillingConfig()?.prices ?? null).toBeNull();
});
-
- it('rejects a theme colour that is not hex', async () => {
- const admin = await createAdmin(context.harness);
- for (const theme_color of ['rgb(123, 44, 228)', 'rebeccapurple', '#12345']) {
- await patchConfig(context.harness, admin, {app_public: {branding: {theme_color}}})
- .expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.INVALID_FORM_BODY)
- .execute();
- }
- const cleared = await patchConfig(context.harness, admin, {
- app_public: {branding: {theme_color: null}},
- }).execute();
- expect(cleared.app_public.branding.theme_color).toBeNull();
- });
});
diff --git a/fluxer_api/src/api/admin/tests/InstanceConfigSmtpTest.test.ts b/fluxer_api/src/api/admin/tests/InstanceConfigSmtpTest.test.ts
index bdb2a7919..f14d56441 100644
--- a/fluxer_api/src/api/admin/tests/InstanceConfigSmtpTest.test.ts
+++ b/fluxer_api/src/api/admin/tests/InstanceConfigSmtpTest.test.ts
@@ -2,7 +2,6 @@
import type {TestAccount} from '@app/api/auth/tests/AuthTestUtils';
import {createTestAccount, setUserACLs} from '@app/api/auth/tests/AuthTestUtils';
-import {getConfig} from '@app/api/Config';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
@@ -16,8 +15,6 @@ import {afterAll, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest'
describe('instance SMTP settings', () => {
let harness: ApiTestHarness;
let admin: TestAccount;
- const verify = vi.fn();
- const createTransport = vi.spyOn(nodemailer, 'createTransport');
beforeAll(async () => {
harness = await createApiTestHarness();
@@ -25,10 +22,6 @@ describe('instance SMTP settings', () => {
beforeEach(async () => {
await harness.reset();
- createTransport.mockReset();
- createTransport.mockReturnValue({verify} as unknown as Transporter);
- verify.mockReset();
- verify.mockResolvedValue(true);
admin = await setUserACLs(harness, await createTestAccount(harness), [
AdminACLs.AUTHENTICATE,
AdminACLs.INSTANCE_CONFIG_VIEW,
@@ -38,7 +31,6 @@ describe('instance SMTP settings', () => {
afterAll(async () => {
await harness.shutdown();
- createTransport.mockRestore();
});
async function patchSmtp(smtp: Record<string, unknown>) {
@@ -56,29 +48,6 @@ describe('instance SMTP settings', () => {
.execute();
}
- it('fills a draft for the saved host with the saved password', async () => {
- await patchSmtp({
- host: 'smtp.example.com',
- port: 465,
- username: 'mailer',
- password: 'saved-password',
- tls_mode: 'implicit',
- });
- await expect(runSmtpTest({host: 'SMTP.example.com', port: 2525, tls_mode: null})).resolves.toEqual({
- ok: true,
- error: null,
- });
- expect(createTransport).toHaveBeenCalledWith(
- expect.objectContaining({
- host: 'SMTP.example.com',
- port: 2525,
- secure: false,
- ignoreTLS: true,
- auth: {user: 'mailer', pass: 'saved-password'},
- }),
- );
- });
-
it.each([{host: 'draft.example.com'}, {username: 'someone-else'}, {host: 'draft.example.com', password: null}])(
'keeps the saved password away from the draft %j',
async (draft) => {
@@ -87,48 +56,6 @@ describe('instance SMTP settings', () => {
ok: false,
error: 'Enter the SMTP password to test a different host or username',
});
- expect(createTransport).not.toHaveBeenCalled();
},
);
-
- it('picks the TLS mode from the port until one is saved', async () => {
- const original = getConfig().email.smtp;
- getConfig().email.smtp = original ? {...original, tlsMode: null} : original;
- try {
- expect(await patchSmtp({host: 'smtp.example.com', port: 587})).toMatchObject({
- tls_mode: null,
- effective_tls_mode: 'starttls',
- });
- expect(await patchSmtp({port: 465})).toMatchObject({tls_mode: null, effective_tls_mode: 'implicit'});
- expect(await patchSmtp({tls_mode: 'none'})).toMatchObject({tls_mode: 'none', effective_tls_mode: 'none'});
- } finally {
- getConfig().email.smtp = original;
- }
- });
-
- it('reads the legacy secure flag and lets the mode replace it', async () => {
- expect(await patchSmtp({host: 'smtp.example.com', port: 587, secure: true})).toMatchObject({
- tls_mode: 'implicit',
- });
- expect(await patchSmtp({secure: false})).toMatchObject({tls_mode: 'opportunistic'});
- expect(await patchSmtp({tls_mode: 'starttls'})).toMatchObject({tls_mode: 'starttls'});
- });
-
- it('clears every saved field so the environment applies again', async () => {
- await patchSmtp({
- host: 'smtp.example.com',
- port: 465,
- username: 'mailer',
- password: 'saved-password',
- tls_mode: 'implicit',
- });
- const environment = getConfig().email.smtp;
- expect(await patchSmtp({host: null, port: null, username: null, password: null, tls_mode: null})).toMatchObject({
- host: environment?.host,
- port: environment?.port,
- username: environment?.username,
- tls_mode: null,
- effective_tls_mode: 'none',
- });
- });
});
diff --git a/fluxer_api/src/api/admin/tests/LimitConfigRemovedKeys.test.ts b/fluxer_api/src/api/admin/tests/LimitConfigRemovedKeys.test.ts
index b9c19772d..a8c27679b 100644
--- a/fluxer_api/src/api/admin/tests/LimitConfigRemovedKeys.test.ts
+++ b/fluxer_api/src/api/admin/tests/LimitConfigRemovedKeys.test.ts
@@ -5,11 +5,8 @@ import {createTestAccount, setUserACLs} from '@app/api/auth/tests/AuthTestUtils'
import {getConfig} from '@app/api/Config';
import {getInstanceConfigRepository, getLimitConfigService} from '@app/api/middleware/ServiceSingletons';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {HTTP_STATUS} from '@app/api/test/TestConstants';
import {createBuilder} 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 type {LimitRule} from '@fluxer/limits/src/LimitTypes';
import type {LimitConfigGetResponse} from '@fluxer/schema/src/domains/admin/AdminSchemas';
import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
@@ -113,30 +110,4 @@ describe.each([true, false])('limit config with a key from an older release (sel
})
.execute();
});
-
- it('names the unknown key in the validation error', async () => {
- const admin = await createAdmin();
- const {limit_config: config} = await createBuilder<LimitConfigResponse>(harness, admin.token)
- .get('/admin/limit-config')
- .execute();
- const response = await createBuilder<{errors: Array<{path: string; code: string}>}>(harness, admin.token)
- .put('/admin/limit-config')
- .body({
- limit_config: {
- traitDefinitions: [...config.traitDefinitions, 'vip'],
- rules: [
- ...config.rules.map(({modifiedFields: _modifiedFields, ...rule}) => rule),
- {id: 'vip', filters: {traits: ['vip']}, limits: {max_bio_length: 200, [REMOVED_KEY]: 5}},
- ],
- },
- })
- .expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.INVALID_FORM_BODY)
- .execute();
- expect(response.errors).toEqual([
- expect.objectContaining({
- path: `limit_config.rules.${config.rules.length}.limits.${REMOVED_KEY}`,
- code: ValidationErrorCodes.INVALID_FORMAT,
- }),
- ]);
- });
});
diff --git a/fluxer_api/src/api/admin/tests/PushRelayConsentAdmin.test.ts b/fluxer_api/src/api/admin/tests/PushRelayConsentAdmin.test.ts
index 803865129..c9b156b93 100644
--- a/fluxer_api/src/api/admin/tests/PushRelayConsentAdmin.test.ts
+++ b/fluxer_api/src/api/admin/tests/PushRelayConsentAdmin.test.ts
@@ -3,7 +3,6 @@
import type {TestAccount} from '@app/api/auth/tests/AuthTestUtils';
import {createTestAccount, setUserACLs} from '@app/api/auth/tests/AuthTestUtils';
import {setCassandraQueryExecutorForTesting} from '@app/api/database/CassandraQueryExecution';
-import {NatsConfigPublisher} from '@app/api/instance/NatsConfigPublisher';
import {InstanceConfigWriteRaceExecutor} from '@app/api/instance/tests/InstanceConfigWriteRaceExecutor';
import {getInstanceConfigRepository} from '@app/api/middleware/ServiceSingletons';
import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';
@@ -49,11 +48,6 @@ describe('push relay supplemental notice consent', () => {
beforeEach(async () => {
await harness.reset();
- vi.spyOn(NatsConfigPublisher.prototype, 'publish').mockResolvedValue(undefined);
- });
-
- afterEach(() => {
- vi.restoreAllMocks();
});
afterAll(async () => {
@@ -67,9 +61,6 @@ describe('push relay supplemental notice consent', () => {
AdminACLs.INSTANCE_CONFIG_UPDATE,
]);
- const patchConfig = (admin: TestAccount, body: Record<string, unknown>) =>
- createBuilder<InstanceConfigResponse>(harness, admin.token).patch('/admin/instance/config').body(body);
-
const readConfig = (admin: TestAccount) =>
createBuilder<InstanceConfigResponse>(harness, admin.token).get('/admin/instance/config');
@@ -88,12 +79,6 @@ describe('push relay supplemental notice consent', () => {
getInstanceConfigRepository().clearCacheForTesting();
}
- async function readStoredRow(): Promise<unknown> {
- const raw = await executor.readDirectly(PUSH_RELAY_CONFIG_KEY);
- if (raw === null) throw new Error('push relay config was never stored');
- return JSON.parse(raw);
- }
-
it('reads back as unaccepted before an operator agrees', async () => {
const admin = await createAdmin();
@@ -106,19 +91,6 @@ describe('push relay supplemental notice consent', () => {
});
});
- it('keeps the consent of a stored push service delivery row', async () => {
- const admin = await createAdmin();
- await storeRow(PROD_ROW);
-
- const config = await readConfig(admin).execute();
-
- expect(config.push_relay).toEqual({
- relay_consent_accepted: true,
- relay_consent_accepted_at: ACCEPTED_AT,
- relay_consent_accepted_by: ACCEPTED_BY,
- });
- });
-
it('reads a stored row without consent fields as unaccepted', async () => {
const admin = await createAdmin();
await storeRow({enabled: true, config_version: 3, rollout_basis_points: 10000});
@@ -129,151 +101,6 @@ describe('push relay supplemental notice consent', () => {
expect(await readRpcConfig()).toMatchObject({config_version: 3, relay_consent_accepted: false});
});
- it('stamps the acting admin and the acceptance time when consent is given', async () => {
- const admin = await createAdmin();
-
- const updated = await patchConfig(admin, {push_relay: {relay_consent_accepted: true}}).execute();
-
- expect(updated.push_relay.relay_consent_accepted).toBe(true);
- expect(updated.push_relay.relay_consent_accepted_by).toBe(admin.userId);
- expect(Date.parse(updated.push_relay.relay_consent_accepted_at ?? '')).not.toBeNaN();
- });
-
- it('keeps the stamp untouched when consent is re-sent unchanged', async () => {
- const admin = await createAdmin();
- const accepted = await patchConfig(admin, {push_relay: {relay_consent_accepted: true}}).execute();
-
- const resent = await patchConfig(admin, {push_relay: {relay_consent_accepted: true}}).execute();
-
- expect(resent.push_relay).toEqual(accepted.push_relay);
- });
-
- it('clears the stamp when an operator withdraws consent', async () => {
- const admin = await createAdmin();
- await patchConfig(admin, {push_relay: {relay_consent_accepted: true}}).execute();
-
- const withdrawn = await patchConfig(admin, {push_relay: {relay_consent_accepted: false}}).execute();
-
- expect(withdrawn.push_relay).toEqual({
- relay_consent_accepted: false,
- relay_consent_accepted_at: null,
- relay_consent_accepted_by: null,
- });
- });
-
- it('ignores an acceptance stamp supplied by the caller', async () => {
- const admin = await createAdmin();
-
- const updated = await patchConfig(admin, {
- push_relay: {
- relay_consent_accepted: true,
- relay_consent_accepted_at: '2020-01-01T00:00:00.000Z',
- relay_consent_accepted_by: '1500000000000000009',
- },
- }).execute();
-
- expect(updated.push_relay.relay_consent_accepted_at).not.toBe('2020-01-01T00:00:00.000Z');
- expect(updated.push_relay.relay_consent_accepted_by).toBe(admin.userId);
- });
-
- it('writes the full legacy document and bumps the stored config version', async () => {
- const admin = await createAdmin();
- await storeRow({
- ...PROD_ROW,
- relay_consent_accepted: false,
- relay_consent_accepted_at: null,
- relay_consent_accepted_by: null,
- });
-
- const updated = await patchConfig(admin, {push_relay: {relay_consent_accepted: true}}).execute();
-
- expect(await readStoredRow()).toEqual({
- enabled: true,
- config_version: 42,
- rollout_basis_points: 10000,
- rollout_salt: 'push-service-delivery-v1',
- included_user_ids: [],
- excluded_user_ids: [],
- relay_consent_accepted: true,
- relay_consent_accepted_at: updated.push_relay.relay_consent_accepted_at,
- relay_consent_accepted_by: admin.userId,
- });
-
- await patchConfig(admin, {push_relay: {relay_consent_accepted: false}}).execute();
-
- expect(await readStoredRow()).toMatchObject({
- enabled: true,
- config_version: 43,
- rollout_basis_points: 10000,
- relay_consent_accepted: false,
- relay_consent_accepted_at: null,
- relay_consent_accepted_by: null,
- });
- });
-
- it('rewrites a partially enrolled stored row as full enrolment', async () => {
- const admin = await createAdmin();
- await storeRow({
- ...PROD_ROW,
- enabled: false,
- rollout_basis_points: 250,
- rollout_salt: 'custom-salt',
- included_user_ids: ['1500000000000000003'],
- excluded_user_ids: ['1500000000000000004'],
- });
-
- await patchConfig(admin, {push_relay: {relay_consent_accepted: false}}).execute();
-
- expect(await readStoredRow()).toMatchObject({
- enabled: true,
- config_version: 42,
- rollout_basis_points: 10000,
- rollout_salt: 'push-service-delivery-v1',
- included_user_ids: [],
- excluded_user_ids: [],
- });
- });
-
- it('publishes the legacy delivery document with the consent', async () => {
- const admin = await createAdmin();
- const publish = vi.mocked(NatsConfigPublisher.prototype.publish);
-
- const updated = await patchConfig(admin, {push_relay: {relay_consent_accepted: true}}).execute();
-
- expect(publish).toHaveBeenCalledTimes(1);
- expect(publish).toHaveBeenCalledWith('config.push.delivery', 'push_service_delivery_config', {
- enabled: true,
- config_version: 1,
- rollout_basis_points: 10000,
- rollout_salt: 'push-service-delivery-v1',
- included_user_ids: [],
- excluded_user_ids: [],
- relay_consent_accepted: true,
- relay_consent_accepted_at: updated.push_relay.relay_consent_accepted_at,
- relay_consent_accepted_by: admin.userId,
- });
- });
-
- it('does not write or publish for an empty push relay patch', async () => {
- const admin = await createAdmin();
- const publish = vi.mocked(NatsConfigPublisher.prototype.publish);
-
- await patchConfig(admin, {push_relay: {}}).execute();
-
- expect(publish).not.toHaveBeenCalled();
- expect(await executor.readDirectly(PUSH_RELAY_CONFIG_KEY)).toBeNull();
- });
-
- it('ignores the retired push_service_delivery section', async () => {
- const admin = await createAdmin();
- const publish = vi.mocked(NatsConfigPublisher.prototype.publish);
-
- const updated = await patchConfig(admin, {push_service_delivery: {relay_consent_accepted: true}}).execute();
-
- expect(updated.push_relay.relay_consent_accepted).toBe(false);
- expect(publish).not.toHaveBeenCalled();
- });
-
it('answers the legacy delivery RPC with full enrolment and the stored consent', async () => {
await storeRow(PROD_ROW);
@@ -293,18 +120,4 @@ describe('push relay supplemental notice consent', () => {
relay_consent_accepted_by: null,
});
});
-
- it('answers the legacy delivery RPC with consent given through the admin API', async () => {
- const admin = await createAdmin();
- const updated = await patchConfig(admin, {push_relay: {relay_consent_accepted: true}}).execute();
-
- expect(await readRpcConfig()).toMatchObject({
- enabled: true,
- config_version: 1,
- rollout_basis_points: 10000,
- relay_consent_accepted: true,
- relay_consent_accepted_at: updated.push_relay.relay_consent_accepted_at,
- relay_consent_accepted_by: admin.userId,
- });
- });
});
diff --git a/fluxer_api/src/api/admin/tests/VoiceAdminController.test.ts b/fluxer_api/src/api/admin/tests/VoiceAdminController.test.ts
index 7357a70bc..fadedcc74 100644
--- a/fluxer_api/src/api/admin/tests/VoiceAdminController.test.ts
+++ b/fluxer_api/src/api/admin/tests/VoiceAdminController.test.ts
@@ -133,135 +133,4 @@ describe('VoiceAdminController', () => {
expect(persisted?.apiKey).toBe(fixture.initialApiKey);
expect(persisted?.apiSecret).toBe(fixture.initialApiSecret);
});
- test('stores, keeps, and clears a voice server soft connection limit', async () => {
- const admin = await createAdminWithAcls(harness, [
- AdminACLs.VOICE_REGION_CREATE,
- AdminACLs.VOICE_SERVER_CREATE,
- AdminACLs.VOICE_SERVER_LIST,
- AdminACLs.VOICE_SERVER_UPDATE,
- ]);
- const regionId = 'voice-region-soft-limit';
- const serverId = 'voice-server-soft-limit';
- await createBuilder<CreateVoiceRegionResponse>(harness, `${admin.token}`)
- .post('/admin/voice/regions')
- .body({
- id: regionId,
- name: `Region ${regionId}`,
- emoji: ':earth_americas:',
- latitude: 1,
- longitude: 2,
- })
- .expect(HTTP_STATUS.OK)
- .execute();
- const created = await createBuilder<CreateVoiceServerResponse>(harness, `${admin.token}`)
- .post(`/admin/voice/regions/${regionId}/servers`)
- .body({
- server_id: serverId,
- endpoint: 'https://voice-soft-limit.example.com/socket',
- api_key: 'soft-limit-api-key',
- api_secret: 'soft-limit-api-secret',
- soft_connection_limit: 250,
- })
- .expect(HTTP_STATUS.OK)
- .execute();
- expect(created.server.soft_connection_limit).toBe(250);
- expect((await voiceRepository.getServer(regionId, serverId))?.softConnectionLimit).toBe(250);
- await createBuilder<UpdateVoiceServerResponse>(harness, `${admin.token}`)
- .patch(`/admin/voice/regions/${regionId}/servers/${serverId}`)
- .body({endpoint: 'https://voice-soft-limit-2.example.com/socket'})
- .expect(HTTP_STATUS.OK)
- .execute();
- expect((await voiceRepository.getServer(regionId, serverId))?.softConnectionLimit).toBe(250);
- const cleared = await createBuilder<UpdateVoiceServerResponse>(harness, `${admin.token}`)
- .patch(`/admin/voice/regions/${regionId}/servers/${serverId}`)
- .body({soft_connection_limit: null})
- .expect(HTTP_STATUS.OK)
- .execute();
- expect(cleared.server.soft_connection_limit).toBeNull();
- expect((await voiceRepository.getServer(regionId, serverId))?.softConnectionLimit).toBeNull();
- });
- test('clears voice server restriction lists when empty arrays are supplied', async () => {
- const admin = await createAdminWithAcls(harness, [
- AdminACLs.VOICE_REGION_CREATE,
- AdminACLs.VOICE_SERVER_CREATE,
- AdminACLs.VOICE_SERVER_UPDATE,
- ]);
- const regionId = 'voice-region-clear-restrictions';
- const serverId = 'voice-server-clear-restrictions';
- await createBuilder<CreateVoiceRegionResponse>(harness, `${admin.token}`)
- .post('/admin/voice/regions')
- .body({
- id: regionId,
- name: `Region ${regionId}`,
- emoji: ':earth_americas:',
- latitude: 1,
- longitude: 2,
- })
- .expect(HTTP_STATUS.OK)
- .execute();
- await createBuilder<CreateVoiceServerResponse>(harness, `${admin.token}`)
- .post(`/admin/voice/regions/${regionId}/servers`)
- .body({
- server_id: serverId,
- endpoint: 'https://voice-clear.example.com/socket',
- api_key: 'clear-api-key',
- api_secret: 'clear-api-secret',
- required_guild_features: ['VIP_VOICE'],
- allowed_guild_ids: [1234567890123456789n.toString()],
- })
- .expect(HTTP_STATUS.OK)
- .execute();
- const stored = await voiceRepository.getServer(regionId, serverId);
- expect(Array.from(stored?.restrictions.requiredGuildFeatures ?? [])).toEqual(['VIP_VOICE']);
- expect(stored?.restrictions.allowedGuildIds.size).toBe(1);
- const cleared = await createBuilder<UpdateVoiceServerResponse>(harness, `${admin.token}`)
- .patch(`/admin/voice/regions/${regionId}/servers/${serverId}`)
- .body({required_guild_features: [], allowed_guild_ids: []})
- .expect(HTTP_STATUS.OK)
- .execute();
- expect(cleared.server.required_guild_features).toEqual([]);
- expect(cleared.server.allowed_guild_ids).toEqual([]);
- const persisted = await voiceRepository.getServer(regionId, serverId);
- expect(persisted?.restrictions.requiredGuildFeatures.size).toBe(0);
- expect(persisted?.restrictions.allowedGuildIds.size).toBe(0);
- });
- test('leaves voice server restriction lists unchanged when they are omitted', async () => {
- const admin = await createAdminWithAcls(harness, [
- AdminACLs.VOICE_REGION_CREATE,
- AdminACLs.VOICE_SERVER_CREATE,
- AdminACLs.VOICE_SERVER_UPDATE,
- ]);
- const regionId = 'voice-region-keep-restrictions';
- const serverId = 'voice-server-keep-restrictions';
- await createBuilder<CreateVoiceRegionResponse>(harness, `${admin.token}`)
- .post('/admin/voice/regions')
- .body({
- id: regionId,
- name: `Region ${regionId}`,
- emoji: ':earth_americas:',
- latitude: 1,
- longitude: 2,
- })
- .expect(HTTP_STATUS.OK)
- .execute();
- await createBuilder<CreateVoiceServerResponse>(harness, `${admin.token}`)
- .post(`/admin/voice/regions/${regionId}/servers`)
- .body({
- server_id: serverId,
- endpoint: 'https://voice-keep.example.com/socket',
- api_key: 'keep-api-key',
- api_secret: 'keep-api-secret',
- required_guild_features: ['VIP_VOICE'],
- })
- .expect(HTTP_STATUS.OK)
- .execute();
- await createBuilder<UpdateVoiceServerResponse>(harness, `${admin.token}`)
- .patch(`/admin/voice/regions/${regionId}/servers/${serverId}`)
- .body({is_active: false})
- .expect(HTTP_STATUS.OK)
- .execute();
- const persisted = await voiceRepository.getServer(regionId, serverId);
- expect(Array.from(persisted?.restrictions.requiredGuildFeatures ?? [])).toEqual(['VIP_VOICE']);
- expect(persisted?.isActive).toBe(false);
- });
});
diff --git a/fluxer_api/src/api/auth/tests/DesktopHandoffDeepLink.test.ts b/fluxer_api/src/api/auth/tests/DesktopHandoffDeepLink.test.ts
index 33c5ac75c..53cd7ef34 100644
--- a/fluxer_api/src/api/auth/tests/DesktopHandoffDeepLink.test.ts
+++ b/fluxer_api/src/api/auth/tests/DesktopHandoffDeepLink.test.ts
@@ -106,36 +106,6 @@ describe('Auth desktop handoff deep link return', () => {
expect(released.status).toBe('completed');
});
- it('still completes through the typed code when the app registered a deep link', async () => {
- const account = await createTestAccount(harness);
- const login = await loginAccount(harness, account);
- const initResp = await initiate({return_uri: RETURN_URI});
- await createBuilderWithoutAuth(harness).get(`/auth/handoff/${initResp.code}/info`).execute();
- await createBuilderWithoutAuth(harness)
- .post('/auth/handoff/complete')
- .body({code: initResp.code, token: login.token, user_id: login.userId, return_method: 'code'})
- .expect(204)
- .execute();
- const released = await readStatus(initResp.code, {poll_secret: initResp.poll_secret});
- expect(released.status).toBe('completed');
- });
-
- it('reports the code return method when the app did not register a deep link', async () => {
- const account = await createTestAccount(harness);
- const login = await loginAccount(harness, account);
- const initResp = await initiate(null);
- expect(initResp.return_method).toBe('code');
- const info = await createBuilderWithoutAuth<HandoffInfoResponse>(harness)
- .get(`/auth/handoff/${initResp.code}/info`)
- .execute();
- expect(info.return_method).toBe('code');
- await createBuilderWithoutAuth(harness)
- .post('/auth/handoff/complete')
- .body({code: initResp.code, token: login.token, user_id: login.userId, return_method: 'deep_link'})
- .expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.INVALID_HANDOFF_CODE)
- .execute();
- });
-
it('rejects a return deep link outside the desktop app schemes', async () => {
for (const returnUri of ['https://evil.example/handoff', 'fluxer://handoff/extra', 'javascript://handoff']) {
await createBuilderWithoutAuth(harness)
diff --git a/fluxer_api/src/api/auth/tests/DesktopHandoffFlow.test.ts b/fluxer_api/src/api/auth/tests/DesktopHandoffFlow.test.ts
index 8087bee5b..a835b21e3 100644
--- a/fluxer_api/src/api/auth/tests/DesktopHandoffFlow.test.ts
+++ b/fluxer_api/src/api/auth/tests/DesktopHandoffFlow.test.ts
@@ -1,6 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import {createAuthHarness, createTestAccount, fetchMe, loginAccount} from '@app/api/auth/tests/AuthTestUtils';
+import {createAuthHarness, createTestAccount, loginAccount} from '@app/api/auth/tests/AuthTestUtils';
import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';
import {HTTP_STATUS} from '@app/api/test/TestConstants';
import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
@@ -44,17 +44,6 @@ interface HandoffStatusResponse {
user_id?: string;
}
-interface UserMeResponse {
- id: string;
- email: string | null;
- username: string;
- global_name: string | null;
-}
-
-function validateHandoffCodeFormat(code: string): boolean {
- return /^[A-Z0-9]{6}-[A-Z0-9]{6}$/.test(code);
-}
-
describe('Auth desktop handoff flow', () => {
let harness: ApiTestHarness;
beforeAll(async () => {
@@ -107,73 +96,6 @@ describe('Auth desktop handoff flow', () => {
expect(sessions.some((session) => session.client_info?.browser === 'Chrome')).toBe(false);
expect(handedOff[0]?.masked_ip).toBe(maskIpForDisplay(DESKTOP_IP));
});
- it('completes full handoff flow: initiate → info → complete → status', 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(initResp.code).toBeTruthy();
- expect(validateHandoffCodeFormat(initResp.code)).toBe(true);
- expect(initResp.expires_at).toBeTruthy();
- expect(initResp.poll_secret).toBeTruthy();
- const info = await createBuilderWithoutAuth<HandoffInfoResponse>(harness)
- .get(`/auth/handoff/${initResp.code}/info`)
- .execute();
- expect(info.status).toBe('pending');
- expect(info.client_info).toBeTruthy();
- const pending = await createBuilderWithoutAuth<HandoffStatusResponse>(harness)
- .post(`/auth/handoff/${initResp.code}/status`)
- .body({poll_secret: initResp.poll_secret})
- .execute();
- expect(pending.status).toBe('pending');
- await createBuilderWithoutAuth(harness)
- .post('/auth/handoff/complete')
- .body({
- code: initResp.code,
- token: login.token,
- user_id: login.userId,
- })
- .expect(204)
- .execute();
- const completed = await createBuilderWithoutAuth<HandoffStatusResponse>(harness)
- .post(`/auth/handoff/${initResp.code}/status`)
- .body({poll_secret: initResp.poll_secret})
- .execute();
- expect(completed.status).toBe('completed');
- expect(completed.token).toBeTruthy();
- expect(completed.token).not.toBe(login.token);
- expect(completed.user_id).toBe(login.userId);
- const originalSession = await fetchMe(harness, login.token);
- expect(originalSession.response.status).toBe(200);
- const originalUser = originalSession.json as UserMeResponse;
- expect(originalUser.id).toBe(login.userId);
- const handoffSession = await fetchMe(harness, completed.token!);
- expect(handoffSession.response.status).toBe(200);
- const handoffUser = handoffSession.json as UserMeResponse;
- expect(handoffUser.id).toBe(login.userId);
- const retrieved = await createBuilderWithoutAuth<HandoffStatusResponse>(harness)
- .post(`/auth/handoff/${initResp.code}/status`)
- .body({poll_secret: initResp.poll_secret})
- .execute();
- expect(retrieved.status).toBe('expired');
- });
- it('cancels handoff correctly', async () => {
- const initResp = await createBuilderWithoutAuth<HandoffInitiateResponse>(harness)
- .post('/auth/handoff/initiate')
- .body(null)
- .execute();
- await createBuilderWithoutAuth(harness)
- .delete(`/auth/handoff/${initResp.code}`)
- .body({poll_secret: initResp.poll_secret})
- .expect(204)
- .execute();
- const cancelled = await createBuilderWithoutAuth<HandoffStatusResponse>(harness)
- .get(`/auth/handoff/${initResp.code}/status`)
- .execute();
- expect(cancelled.status).toBe('expired');
- });
it('rejects info lookup after 3 attempts on same code', async () => {
const initResp = await createBuilderWithoutAuth<HandoffInitiateResponse>(harness)
.post('/auth/handoff/initiate')
@@ -225,39 +147,4 @@ describe('Auth desktop handoff flow', () => {
expect(completed.status).toBe('completed');
expect(completed.user_id).toBe(login.userId);
});
- it('allows desktop handoff across different IPv4 addresses', async () => {
- const originIp = '203.0.113.10';
- const approverInfoIp = '203.0.113.11';
- const approverCompleteIp = '203.0.113.12';
- const pollerIp = '203.0.113.13';
- const account = await createTestAccount(harness, {ipAddress: originIp});
- const login = await loginAccount(harness, account);
- const initResp = await createBuilderWithoutAuth<HandoffInitiateResponse>(harness)
- .post('/auth/handoff/initiate')
- .header('x-forwarded-for', originIp)
- .body(null)
- .execute();
- const info = await createBuilderWithoutAuth<HandoffInfoResponse>(harness)
- .get(`/auth/handoff/${initResp.code}/info`)
- .header('x-forwarded-for', approverInfoIp)
- .execute();
- expect(info.status).toBe('pending');
- await createBuilderWithoutAuth(harness)
- .post('/auth/handoff/complete')
- .header('x-forwarded-for', approverCompleteIp)
- .header('Authorization', login.token)
- .body({
- code: initResp.code,
- user_id: login.userId,
- })
- .expect(204)
- .execute();
- const completed = await createBuilderWithoutAuth<HandoffStatusResponse>(harness)
- .post(`/auth/handoff/${initResp.code}/status`)
- .header('x-forwarded-for', pollerIp)
- .body({poll_secret: initResp.poll_secret})
- .execute();
- expect(completed.status).toBe('completed');
- expect(completed.user_id).toBe(login.userId);
- });
});
diff --git a/fluxer_api/src/api/auth/tests/DesktopHandoffUsage.test.ts b/fluxer_api/src/api/auth/tests/DesktopHandoffUsage.test.ts
index 3719d093d..512f976ff 100644
--- a/fluxer_api/src/api/auth/tests/DesktopHandoffUsage.test.ts
+++ b/fluxer_api/src/api/auth/tests/DesktopHandoffUsage.test.ts
@@ -60,35 +60,4 @@ describe('Auth desktop handoff complete single use', () => {
expect(status.status).toBe('pending');
expect(status.token).toBeUndefined();
});
- it('releases the token only to a poller presenting the correct secret', 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(initResp.poll_secret).toBeTruthy();
- await createBuilderWithoutAuth(harness).get(`/auth/handoff/${initResp.code}/info`).execute();
- await createBuilderWithoutAuth(harness)
- .post('/auth/handoff/complete')
- .header('Authorization', login.token)
- .body({
- code: initResp.code,
- user_id: login.userId,
- })
- .expect(204)
- .execute();
- const withoutSecret = await createBuilderWithoutAuth<HandoffStatusResponse>(harness)
- .get(`/auth/handoff/${initResp.code}/status`)
- .execute();
- expect(withoutSecret.status).toBe('pending');
- expect(withoutSecret.token).toBeUndefined();
- const withSecret = await createBuilderWithoutAuth<HandoffStatusResponse>(harness)
- .post(`/auth/handoff/${initResp.code}/status`)
- .body({poll_secret: initResp.poll_secret})
- .execute();
- expect(withSecret.status).toBe('completed');
- expect(withSecret.token).toBeTruthy();
- expect(withSecret.token).not.toBe(login.token);
- });
});
diff --git a/fluxer_api/src/api/auth/tests/IPAuthResend.test.ts b/fluxer_api/src/api/auth/tests/IPAuthResend.test.ts
index ce665654d..9155a629b 100644
--- a/fluxer_api/src/api/auth/tests/IPAuthResend.test.ts
+++ b/fluxer_api/src/api/auth/tests/IPAuthResend.test.ts
@@ -5,7 +5,6 @@ import {
createAuthHarness,
createUniqueEmail,
createUniqueUsername,
- listTestEmails,
registerUser,
} from '@app/api/auth/tests/AuthTestUtils';
import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';
@@ -120,63 +119,5 @@ describe('Auth IP Authorization Resend', () => {
expect(errorResp.code).toBe(APIErrorCodes.IP_AUTHORIZATION_RESEND_LIMIT_EXCEEDED);
expect(response.headers.get('Retry-After')).toBeNull();
});
- it('returns 400 after IP has already been authorized', async () => {
- const email = createUniqueEmail('ip-resend-after-auth');
- const password = 'a-strong-password';
- await registerUser(harness, {
- email,
- username: createUniqueUsername('resendafterauth'),
- global_name: 'Resend After Auth User',
- password,
- date_of_birth: '2000-01-01',
- consent: true,
- });
- await clearTestEmails(harness);
- const newIP = '10.26.27.28';
- const ipAuthResp = await triggerIpAuthorization(email, password, newIP);
- const emails = await listTestEmails(harness);
- const ipAuthEmail = emails.find((e) => e.type === 'ip_authorization' && e.to === email);
- expect(ipAuthEmail).toBeDefined();
- const authToken = ipAuthEmail!.metadata['token'];
- expect(authToken).toBeTruthy();
- await createBuilderWithoutAuth(harness)
- .post('/auth/authorize-ip')
- .body({token: authToken})
- .header('x-forwarded-for', newIP)
- .expect(HTTP_STATUS.NO_CONTENT)
- .execute();
- await createBuilderWithoutAuth(harness)
- .post('/auth/ip-authorization/resend')
- .body({ticket: ipAuthResp.ticket})
- .header('x-forwarded-for', newIP)
- .expect(HTTP_STATUS.BAD_REQUEST)
- .execute();
- });
- });
- describe('Resend with invalid ticket', () => {
- it('returns 400 when ticket has expired', async () => {
- const email = createUniqueEmail('ip-ticket-expired');
- const password = 'a-strong-password';
- await registerUser(harness, {
- email,
- username: createUniqueUsername('ticketexp'),
- global_name: 'Ticket Expired User',
- password,
- date_of_birth: '2000-01-01',
- consent: true,
- });
- const newIP = '10.70.80.90';
- const ipAuthResp = await triggerIpAuthorization(email, password, newIP);
- await createBuilderWithoutAuth(harness)
- .post('/test/auth/ip-authorization/expire')
- .body({ticket: ipAuthResp.ticket})
- .execute();
- await createBuilderWithoutAuth(harness)
- .post('/auth/ip-authorization/resend')
- .body({ticket: ipAuthResp.ticket})
- .header('x-forwarded-for', newIP)
- .expect(HTTP_STATUS.BAD_REQUEST)
- .execute();
- });
});
});
diff --git a/fluxer_api/src/api/oauth/tests/OAuth2ApplicationCreate.test.ts b/fluxer_api/src/api/oauth/tests/OAuth2ApplicationCreate.test.ts
index 22013f63c..f4680c925 100644
--- a/fluxer_api/src/api/oauth/tests/OAuth2ApplicationCreate.test.ts
+++ b/fluxer_api/src/api/oauth/tests/OAuth2ApplicationCreate.test.ts
@@ -1,13 +1,12 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';
-import {createOAuth2Application, createUniqueApplicationName} from '@app/api/oauth/tests/OAuth2TestUtils';
+import {createUniqueApplicationName} from '@app/api/oauth/tests/OAuth2TestUtils';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
import {CAPTCHA_TEST_HEADER, useCheapCaptcha} from '@app/api/test/CaptchaTestUtils';
import {HTTP_STATUS} from '@app/api/test/TestConstants';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
-import {UsernameType} from '@fluxer/schema/src/primitives/UserValidators';
import {afterEach, beforeEach, describe, expect, test} from 'vitest';
interface ValidationErrorResponse {
@@ -26,47 +25,6 @@ describe('OAuth2 Application Create', () => {
afterEach(async () => {
await harness?.shutdown();
});
- test('creates OAuth2 application with bot user', async () => {
- const account = await createTestAccount(harness);
- const appName = createUniqueApplicationName();
- const redirectURIs = ['https://example.com/callback'];
- const result = await createOAuth2Application(harness, account.token, {
- name: appName,
- redirect_uris: redirectURIs,
- bot_public: true,
- });
- expect(result.application.id).toBeTruthy();
- expect(result.application.name).toBe(appName);
- expect(result.application.redirect_uris).toEqual(redirectURIs);
- expect(result.application.bot).toBeDefined();
- expect(result.application.bot?.id).toBeTruthy();
- expect(result.application.bot?.username).toBeTruthy();
- expect(result.application.bot?.discriminator).toBeTruthy();
- expect(result.application.bot?.token).toBeTruthy();
- expect(result.clientSecret).toBeTruthy();
- expect(result.botUserId).toBe(result.application.bot?.id);
- expect(result.botToken).toBe(result.application.bot?.token);
- const botUser = await createBuilder<{
- id: string;
- bot: boolean;
- }>(harness, `Bot ${result.botToken}`)
- .get('/users/@me')
- .expect(HTTP_STATUS.OK)
- .execute();
- expect(botUser.id).toBe(result.botUserId);
- expect(botUser.bot).toBe(true);
- });
- test('falls back to a valid random bot username when the application name sanitizes to a forbidden username', async () => {
- const account = await createTestAccount(harness);
- const result = await createOAuth2Application(harness, account.token, {
- name: 'fluxer system message',
- });
- const botUsername = result.application.bot?.username;
- expect(botUsername).toBeTruthy();
- expect(UsernameType.safeParse(botUsername).success).toBe(true);
- expect(botUsername?.toLowerCase()).not.toContain('fluxer');
- expect(botUsername?.toLowerCase()).not.toContain('systemmessage');
- });
test('requires captcha when creating a bot application', async () => {
const account = await createTestAccount(harness);
await useCheapCaptcha();
diff --git a/fluxer_api/src/api/oauth/tests/OAuth2ApplicationGet.test.ts b/fluxer_api/src/api/oauth/tests/OAuth2ApplicationGet.test.ts
index 49de12ff0..e71cfd6f7 100644
--- a/fluxer_api/src/api/oauth/tests/OAuth2ApplicationGet.test.ts
+++ b/fluxer_api/src/api/oauth/tests/OAuth2ApplicationGet.test.ts
@@ -20,25 +20,6 @@ describe('OAuth2 Application Get', () => {
beforeEach(async () => {
harness = await createApiTestHarness();
});
- test('returns application response shape', async () => {
- const account = await createTestAccount(harness);
- const appName = createUniqueApplicationName();
- const redirectURIs = ['https://example.com/callback', 'https://example.com/callback2'];
- const createResult = await createOAuth2Application(harness, account.token, {
- name: appName,
- redirect_uris: redirectURIs,
- });
- const application = await getOAuth2Application(harness, account.token, createResult.application.id);
- expect(application.id).toBeTruthy();
- expect(application.name).toBe(appName);
- expect(application.redirect_uris).toEqual(redirectURIs);
- expect(application.bot).toBeDefined();
- expect(application.bot?.id).toBeTruthy();
- expect(application.bot?.username).toBeTruthy();
- expect(application.bot?.discriminator).toBeTruthy();
- expect(application.bot?.token).toBeUndefined();
- expect(application.client_secret).toBeUndefined();
- });
test('enforces access control - user cannot access another users application', async () => {
const owner = await createTestAccount(harness);
const otherUser = await createTestAccount(harness);
diff --git a/fluxer_api/src/api/oauth/tests/OAuth2ApplicationList.test.ts b/fluxer_api/src/api/oauth/tests/OAuth2ApplicationList.test.ts
index 08c20f23f..345638a5f 100644
--- a/fluxer_api/src/api/oauth/tests/OAuth2ApplicationList.test.ts
+++ b/fluxer_api/src/api/oauth/tests/OAuth2ApplicationList.test.ts
@@ -14,25 +14,6 @@ describe('OAuth2 Application List', () => {
beforeEach(async () => {
harness = await createApiTestHarness();
});
- test('returns list response shape', async () => {
- const account = await createTestAccount(harness);
- const appName = createUniqueApplicationName();
- await createOAuth2Application(harness, account.token, {
- name: appName,
- redirect_uris: ['https://example.com/callback'],
- });
- const applications = await listOAuth2Applications(harness, account.token);
- expect(applications.length).toBeGreaterThan(0);
- const app = applications[0]!;
- expect(app.id).toBeTruthy();
- expect(app.name).toBeTruthy();
- expect(app.redirect_uris).toBeDefined();
- expect(app.bot?.id).toBeTruthy();
- expect(app.bot?.username).toBeTruthy();
- expect(app.bot?.discriminator).toBeTruthy();
- expect(app.bot?.token).toBeUndefined();
- expect(app.client_secret).toBeUndefined();
- });
test('returns only applications owned by user', async () => {
const owner1 = await createTestAccount(harness);
const owner2 = await createTestAccount(harness);
diff --git a/fluxer_api/src/api/oauth/tests/OAuth2ApplicationUpdate.test.ts b/fluxer_api/src/api/oauth/tests/OAuth2ApplicationUpdate.test.ts
index 4cb79df25..4a96159b4 100644
--- a/fluxer_api/src/api/oauth/tests/OAuth2ApplicationUpdate.test.ts
+++ b/fluxer_api/src/api/oauth/tests/OAuth2ApplicationUpdate.test.ts
@@ -5,31 +5,13 @@ import {createOAuth2Application, createUniqueApplicationName} from '@app/api/oau
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
import {HTTP_STATUS} from '@app/api/test/TestConstants';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
-import type {ApplicationResponse} from '@fluxer/schema/src/domains/oauth/OAuthSchemas';
-import {beforeEach, describe, expect, test} from 'vitest';
+import {beforeEach, describe, test} from 'vitest';
describe('OAuth2 Application Update', () => {
let harness: ApiTestHarness;
beforeEach(async () => {
harness = await createApiTestHarness();
});
- test('supports partial updates', async () => {
- const account = await createTestAccount(harness);
- const originalName = createUniqueApplicationName();
- const originalURIs = ['https://example.com/old'];
- const createResult = await createOAuth2Application(harness, account.token, {
- name: originalName,
- redirect_uris: originalURIs,
- });
- const newName = createUniqueApplicationName();
- const updated = await createBuilder<ApplicationResponse>(harness, account.token)
- .patch(`/oauth2/applications/${createResult.application.id}`)
- .body({name: newName})
- .expect(HTTP_STATUS.OK)
- .execute();
- expect(updated.name).toBe(newName);
- expect(updated.redirect_uris).toEqual(originalURIs);
- });
test('enforces access control', async () => {
const owner = await createTestAccount(harness);
const otherUser = await createTestAccount(harness);
diff --git a/fluxer_api/src/api/oauth/tests/OAuth2TokenExpiration.test.ts b/fluxer_api/src/api/oauth/tests/OAuth2TokenExpiration.test.ts
index 675e761d2..66a6d88cc 100644
--- a/fluxer_api/src/api/oauth/tests/OAuth2TokenExpiration.test.ts
+++ b/fluxer_api/src/api/oauth/tests/OAuth2TokenExpiration.test.ts
@@ -3,11 +3,7 @@
import {createApplicationID, createUserID} from '@app/api/BrandedTypes';
import {ACCESS_TOKEN_TTL_SECONDS} from '@app/api/oauth/OAuth2TokenConstants';
import {OAuth2TokenRepository} from '@app/api/oauth/repositories/OAuth2TokenRepository';
-import {
- authorizeOAuth2,
- createOAuth2TestSetup,
- exchangeOAuth2AuthorizationCode,
-} from '@app/api/oauth/tests/OAuthTestUtils';
+import {createOAuth2TestSetup} from '@app/api/oauth/tests/OAuthTestUtils';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
import {HTTP_STATUS} from '@app/api/test/TestConstants';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
@@ -37,33 +33,4 @@ describe('OAuth2 Token Expiration', () => {
expect(await repository.getAccessToken(token)).toBeNull();
await createBuilder(harness, `Bearer ${token}`).get('/oauth2/userinfo').expect(HTTP_STATUS.UNAUTHORIZED).execute();
});
- test('should provide expires timestamp through oauth2/@me endpoint', async () => {
- const {endUser, redirectURI, application} = await createOAuth2TestSetup(harness);
- const authCodeResponse = await authorizeOAuth2(harness, endUser.token, {
- client_id: application.id,
- redirect_uri: redirectURI,
- scope: 'identify',
- });
- const tokens = await exchangeOAuth2AuthorizationCode(harness, {
- client_id: application.id,
- client_secret: application.client_secret,
- code: authCodeResponse.code,
- redirect_uri: redirectURI,
- });
- const json = await createBuilder<{
- application: {
- id: string;
- };
- scopes: Array<string>;
- expires: string;
- }>(harness, `Bearer ${tokens.access_token}`)
- .get('/oauth2/@me')
- .expect(HTTP_STATUS.OK)
- .execute();
- expect(json.application.id).toBe(application.id);
- expect(json.scopes).toContain('identify');
- expect(json.expires).toBeTruthy();
- const expiresDate = new Date(json.expires);
- expect(expiresDate.getTime()).toBeGreaterThan(Date.now());
- });
});