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 middleware, config, job and worker cases

Hampus02d80715a18d
diff --git a/fluxer_api/src/api/app/tests/DeletionQueueStartup.test.ts b/fluxer_api/src/api/app/tests/DeletionQueueStartup.test.ts
index 7b9b3cec6..47a05d213 100644
--- a/fluxer_api/src/api/app/tests/DeletionQueueStartup.test.ts
+++ b/fluxer_api/src/api/app/tests/DeletionQueueStartup.test.ts
@@ -31,32 +31,6 @@ class RecordingLogger implements LoggerInterface {
}
}
-class UnreadableStateKVProvider extends MockKVProvider {
- override async get(): Promise<string | null> {
- throw new Error('kv unavailable');
- }
-}
-
-class UnlockableKVProvider extends MockKVProvider {
- override async acquireLock(): Promise<boolean> {
- throw new Error('kv lock unavailable');
- }
-}
-
-class UnreleasableKVProvider extends MockKVProvider {
- override async releaseLock(): Promise<boolean> {
- throw new Error('kv lock release failed');
- }
-}
-
-function createFailingRepository(): UserRepository {
- return {
- async scanAllUsersPage() {
- throw new Error('paged user scan failed');
- },
- } as unknown as UserRepository;
-}
-
function createPendingUser(index: number): User {
return new User({
...EMPTY_USER_ROW,
@@ -136,38 +110,6 @@ describe('ensureDeletionQueueState', () => {
expect(await queue.acquireRebuildLock()).not.toBeNull();
});
- it('aborts startup when the queue state cannot be read', async () => {
- const queue = new KVAccountDeletionQueueService(new UnreadableStateKVProvider(), createFailingRepository());
- const logger = new RecordingLogger();
-
- await expect(ensureDeletionQueueState(queue, logger)).rejects.toThrow('kv unavailable');
-
- expect(logger.errors).toEqual(['Failed to read KV deletion queue state, aborting startup']);
- });
-
- it('aborts startup when the rebuild lock cannot be acquired', async () => {
- const queue = new KVAccountDeletionQueueService(new UnlockableKVProvider(), createFailingRepository());
- const logger = new RecordingLogger();
-
- await expect(ensureDeletionQueueState(queue, logger)).rejects.toThrow('kv lock unavailable');
-
- expect(logger.errors).toEqual(['Failed to acquire the KV deletion queue rebuild lock, aborting startup']);
- });
-
- it('does not abort startup when releasing the rebuild lock fails', async () => {
- const queue = new KVAccountDeletionQueueService(
- new UnreleasableKVProvider(),
- createWorkerRepository(async () => {}),
- );
- const logger = new RecordingLogger();
-
- await expect(ensureDeletionQueueState(queue, logger)).resolves.toBeUndefined();
-
- const queued = await queue.getReadyDeletions(Date.parse('2026-06-02T00:00:00.000Z'), 10);
- expect(queued.map((deletion) => deletion.userId).sort()).toEqual([9101n, 9102n]);
- expect(logger.errors).toEqual(['Failed to release the KV deletion queue rebuild lock']);
- });
-
it('rebuilds under the lock when no other instance holds it', async () => {
const kvClient = new MockKVProvider();
const queue = new KVAccountDeletionQueueService(
diff --git a/fluxer_api/src/api/instance/InstanceConfigRepository.test.ts b/fluxer_api/src/api/instance/InstanceConfigRepository.test.ts
index aaca23faa..94f6834fc 100644
--- a/fluxer_api/src/api/instance/InstanceConfigRepository.test.ts
+++ b/fluxer_api/src/api/instance/InstanceConfigRepository.test.ts
@@ -2,44 +2,23 @@
import {createHash} from 'node:crypto';
import {createUserID} from '@app/api/BrandedTypes';
-import {Config, getConfig} from '@app/api/Config';
+import {getConfig} from '@app/api/Config';
import type {CassandraQueryExecutorForTesting} from '@app/api/database/CassandraQueryExecution';
import {setCassandraQueryExecutorForTesting} from '@app/api/database/CassandraQueryExecution';
-import {PostgresKvQueryExecutor} from '@app/api/database/PostgresKvQueryExecutor';
import {
- INSTANCE_CONFIG_REFRESH_CHANNEL,
INSTANCE_CONFIG_WRITE_ATTEMPTS,
InstanceConfigRepository,
InstanceConfigWriteConflictError,
- type InstanceRegistrationConfig,
} from '@app/api/instance/InstanceConfigRepository';
-import {getLegalUrls, setCachedConfiguredLegalUrls} from '@app/api/instance/LegalUrls';
-import {getInstanceProductName, setCachedProductName} from '@app/api/instance/ProductName';
import {ensureSetupToken, isSetupTokenEnforced} from '@app/api/instance/SetupToken';
import {InstanceConfigWriteRaceExecutor} from '@app/api/instance/tests/InstanceConfigWriteRaceExecutor';
-import {dockerAvailable, startPostgresKv, stopPostgresKv} from '@app/api/test/DockerTestContainer';
import {InMemoryCassandraQueryExecutor} from '@app/api/test/InMemoryCassandraQueryExecutor';
-import {
- DEFAULT_CHANNEL_THREADS_CONFIG,
- everyoneChannelThreadsConfig,
-} from '@fluxer/schema/src/domains/admin/ChannelThreadsSchemas';
-import {DEFAULT_DOMAIN_MIGRATION_CONFIG} from '@fluxer/schema/src/domains/admin/DomainMigrationSchemas';
-import {DEFAULT_EXPERIMENT_DELIVERY_CONFIG} from '@fluxer/schema/src/domains/experiment/ExperimentSchemas';
import {MockKVProvider} from '@pkgs/kv_client/src/testing/MockKVProvider';
-import type {IPostgresClient} from '@pkgs/postgres/src/Client';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
-
-const DOMAIN_MIGRATION_CONFIG_KEY = 'domain_migration_config';
-const CHANNEL_THREADS_CONFIG_KEY = 'channel_threads_config';
-const EXPERIMENT_DELIVERY_CONFIG_KEY = 'experiment_delivery_config';
-const APP_PUBLIC_CONFIG_KEY = 'app_public_config';
-const INSTANCE_POLICY_CONFIG_KEY = 'instance_policy_config';
-const INSTANCE_INTEGRATIONS_CONFIG_KEY = 'instance_integrations_config';
-const LEGACY_ALTCHA_CAPTCHA_CONFIG_KEY = 'altcha_captcha_config';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+
const REGISTRATION_CONFIG_KEY = 'registration_config';
const REGISTRATION_URLS_KEY = 'registration_urls';
const REGISTRATION_PENDING_APPROVALS_KEY = 'registration_pending_approvals';
-const POSTGRES_KV_TABLE = 'kv_instance_config_races';
const SETUP_TOKEN_HASH_KEY = 'setup_token_hash';
const ENV_SETUP_TOKEN = 'setup-token-for-tests-0123456789-abcdefghijklmnopqrstuvwxyz';
describe('InstanceConfigRepository', () => {
@@ -58,368 +37,6 @@ describe('InstanceConfigRepository', () => {
return repository;
}
- it('serves repeated config reads from the hydrated in-memory cache', async () => {
- const executor = new InMemoryCassandraQueryExecutor();
- setCassandraQueryExecutorForTesting(executor);
- const kvProvider = new MockKVProvider();
- const repository = createRepository(kvProvider);
-
- await repository.setRegistrationConfig({mode: 'closed'});
- executor.executed.length = 0;
-
- expect(await repository.getRegistrationConfig()).toEqual({
- mode: 'closed',
- admin_registration_urls_enabled: true,
- } satisfies InstanceRegistrationConfig);
- expect(await repository.getRegistrationConfig()).toEqual({
- mode: 'closed',
- admin_registration_urls_enabled: true,
- } satisfies InstanceRegistrationConfig);
- expect(executor.countStatements('select:instance_configuration')).toBe(0);
- expect(kvProvider.getSubscription().subscribedChannels).toContain(INSTANCE_CONFIG_REFRESH_CHANNEL);
- });
-
- it('refreshes a hydrated cache after another repository publishes a config update', async () => {
- const executor = new InMemoryCassandraQueryExecutor();
- setCassandraQueryExecutorForTesting(executor);
- const kvProvider = new MockKVProvider();
- const reader = createRepository(kvProvider);
- const writer = createRepository(kvProvider);
-
- expect(await reader.getRegistrationConfig()).toEqual({
- mode: 'open',
- admin_registration_urls_enabled: true,
- } satisfies InstanceRegistrationConfig);
-
- await writer.setRegistrationConfig({mode: 'approval'});
-
- await vi.waitFor(async () => {
- expect(await reader.getRegistrationConfig()).toEqual({
- mode: 'approval',
- admin_registration_urls_enabled: true,
- } satisfies InstanceRegistrationConfig);
- });
- });
-
- it('reuses the memoized effective bluesky config until the integrations blob changes', async () => {
- const executor = new InMemoryCassandraQueryExecutor();
- setCassandraQueryExecutorForTesting(executor);
- const kvProvider = new MockKVProvider();
- const repository = createRepository(kvProvider);
-
- const first = await repository.getEffectiveBlueskyConfig();
- expect(await repository.getEffectiveBlueskyConfig()).toBe(first);
-
- await repository.setInstanceIntegrationsConfig({bluesky: {client_name: 'Memoized Instance'}});
-
- const updated = await repository.getEffectiveBlueskyConfig();
- expect(updated).not.toBe(first);
- expect(updated.client_name).toBe('Memoized Instance');
- expect(await repository.getEffectiveBlueskyConfig()).toBe(updated);
- });
-
- it('recomputes the effective bluesky config after another repository publishes an integrations update', async () => {
- const executor = new InMemoryCassandraQueryExecutor();
- setCassandraQueryExecutorForTesting(executor);
- const kvProvider = new MockKVProvider();
- const reader = createRepository(kvProvider);
- const writer = createRepository(kvProvider);
-
- const before = await reader.getEffectiveBlueskyConfig();
- expect(await reader.getEffectiveBlueskyConfig()).toBe(before);
-
- await writer.setInstanceIntegrationsConfig({bluesky: {client_name: 'Refreshed Instance'}});
-
- await vi.waitFor(async () => {
- expect((await reader.getEffectiveBlueskyConfig()).client_name).toBe('Refreshed Instance');
- });
- });
-
- it('turns the captcha on at the default difficulty when no row is stored', async () => {
- setCassandraQueryExecutorForTesting(new InMemoryCassandraQueryExecutor());
- const repository = createRepository(new MockKVProvider());
-
- await expect(repository.getCaptchaConfig()).resolves.toEqual({enabled: true, cost: 5000, max_counter: 1000});
- });
-
- it('ignores a legacy altcha captcha row that turned the experiment off', async () => {
- setCassandraQueryExecutorForTesting(new InMemoryCassandraQueryExecutor());
- const repository = createRepository(new MockKVProvider());
-
- await repository.setConfig(
- LEGACY_ALTCHA_CAPTCHA_CONFIG_KEY,
- JSON.stringify({enabled: false, config_version: 4, cost: 5000, max_counter: 10000}),
- );
-
- await expect(repository.getCaptchaConfig()).resolves.toEqual({enabled: true, cost: 5000, max_counter: 1000});
- });
-
- it('merges a partial captcha update onto the stored config', async () => {
- setCassandraQueryExecutorForTesting(new InMemoryCassandraQueryExecutor());
- const repository = createRepository(new MockKVProvider());
-
- await repository.updateCaptchaConfig({cost: 2000});
- await repository.updateCaptchaConfig({enabled: false});
-
- await expect(repository.getCaptchaConfig()).resolves.toEqual({enabled: false, cost: 2000, max_counter: 1000});
- });
-
- it('drops a legacy captcha integration, secrets included, on the next integrations write', async () => {
- setCassandraQueryExecutorForTesting(new InMemoryCassandraQueryExecutor());
- const repository = createRepository(new MockKVProvider());
-
- await repository.setConfig(
- INSTANCE_INTEGRATIONS_CONFIG_KEY,
- JSON.stringify({
- captcha: {provider: 'legacy-provider', site_key: 'legacy-site-key', secret_key: 'legacy-secret-key'},
- youtube: {api_key: 'youtube-key'},
- }),
- );
- expect(await repository.getInstanceIntegrationsConfig()).not.toHaveProperty('captcha');
-
- await repository.setInstanceIntegrationsConfig({gif: {klipy_api_key: 'klipy-key'}});
-
- const stored = JSON.parse((await repository.getConfig(INSTANCE_INTEGRATIONS_CONFIG_KEY)) ?? '{}');
- expect(stored).not.toHaveProperty('captcha');
- expect(stored.youtube.api_key).toBe('youtube-key');
- expect(stored.gif.klipy_api_key).toBe('klipy-key');
- });
-
- it('keeps the stored setup state when a branding field is invalid', async () => {
- const executor = new InMemoryCassandraQueryExecutor();
- setCassandraQueryExecutorForTesting(executor);
- const kvProvider = new MockKVProvider();
- const repository = createRepository(kvProvider);
-
- await repository.setConfig(
- APP_PUBLIC_CONFIG_KEY,
- JSON.stringify({branding: {product_name: 'Kept', icon_url: 42}, setup: {configured: false}}),
- );
-
- const config = await repository.getAppPublicConfig();
- expect(config.setup.configured).toBe(false);
- expect(config.branding.product_name).toBe('Kept');
- });
-
- it('serves the theme colour as six-digit hex and drops a stored value that is not hex', async () => {
- setCassandraQueryExecutorForTesting(new InMemoryCassandraQueryExecutor());
- const repository = createRepository(new MockKVProvider());
-
- expect((await repository.setAppPublicConfig({branding: {theme_color: '7B2CE4'}})).branding.theme_color).toBe(
- '#7b2ce4',
- );
- expect((await repository.setAppPublicConfig({branding: {theme_color: '#AbC'}})).branding.theme_color).toBe(
- '#aabbcc',
- );
-
- await repository.setConfig(APP_PUBLIC_CONFIG_KEY, JSON.stringify({branding: {theme_color: 'rgb(123, 44, 228)'}}));
- expect((await repository.getAppPublicConfig()).branding.theme_color).toBeNull();
- });
-
- it('treats the black theme colour the setup wizard used to store as unset', async () => {
- setCassandraQueryExecutorForTesting(new InMemoryCassandraQueryExecutor());
- const repository = createRepository(new MockKVProvider());
-
- await repository.setConfig(APP_PUBLIC_CONFIG_KEY, JSON.stringify({branding: {theme_color: '#000000'}}));
- expect((await repository.getAppPublicConfig()).branding.theme_color).toBeNull();
- expect((await repository.setAppPublicConfig({branding: {theme_color: '#000'}})).branding.theme_color).toBeNull();
- expect((await repository.setAppPublicConfig({branding: {theme_color: '#000001'}})).branding.theme_color).toBe(
- '#000001',
- );
- });
-
- it('stores uploaded branding assets as references and resolves them against the current media endpoint', async () => {
- setCassandraQueryExecutorForTesting(new InMemoryCassandraQueryExecutor());
- const repository = createRepository(new MockKVProvider());
- const media = Config.endpoints.media;
- const foreign = 'https://cdn.example.com/favicon.ico';
-
- await repository.setAppPublicConfig({
- branding: {favicon_url: `${media}/branding/0/0123abcd.png`, logo_url: foreign},
- });
-
- const stored = JSON.parse((await repository.getConfig(APP_PUBLIC_CONFIG_KEY)) ?? '{}');
- expect(stored.branding.favicon_url).toBe('branding/0/0123abcd.png');
- expect(stored.branding.logo_url).toBe(foreign);
- Config.endpoints.media = 'https://media.moved.example';
- try {
- const config = await repository.getAppPublicConfig();
- expect(config.branding.favicon_url).toBe('https://media.moved.example/branding/0/0123abcd.png');
- expect(config.branding.logo_url).toBe(foreign);
- } finally {
- Config.endpoints.media = media;
- }
- });
-
- it('normalises legacy branding URLs from an old domain only when the object is ours', async () => {
- setCassandraQueryExecutorForTesting(new InMemoryCassandraQueryExecutor());
- const repository = createRepository(new MockKVProvider());
- await repository.setConfig(
- APP_PUBLIC_CONFIG_KEY,
- JSON.stringify({
- branding: {
- favicon_url: 'https://old.example/media/branding/0/a_0123abcd.gif',
- icon_url: 'https://other.example/branding/0/89abcdef.png',
- },
- }),
- );
- const storage = {
- getObjectMetadata: vi.fn(async (_bucket: string, key: string) =>
- key === 'branding/0/0123abcd' ? {contentLength: 1, contentType: 'image/gif'} : null,
- ),
- };
-
- expect(await repository.normalizeStoredBrandingAssets(storage as never)).toBe(1);
- expect(await repository.normalizeStoredBrandingAssets(storage as never)).toBe(0);
-
- const config = await repository.getAppPublicConfig();
- expect(config.branding.favicon_url).toBe(`${Config.endpoints.media}/branding/0/a_0123abcd.gif`);
- expect(config.branding.icon_url).toBe('https://other.example/branding/0/89abcdef.png');
- });
-
- it('round-trips the community guidelines URL and clears a blank one', async () => {
- setCassandraQueryExecutorForTesting(new InMemoryCassandraQueryExecutor());
- const repository = createRepository(new MockKVProvider());
- const originalSelfHosted = getConfig().instance.selfHosted;
- getConfig().instance.selfHosted = true;
- try {
- expect((await repository.getAppPublicConfig()).legal).toEqual({
- terms_url: null,
- privacy_url: null,
- guidelines_url: null,
- });
- const saved = await repository.setAppPublicConfig({
- legal: {terms_url: 'https://example.org/tos', guidelines_url: ' https://example.org/rules '},
- });
- expect(saved.legal).toEqual({
- terms_url: 'https://example.org/tos',
- privacy_url: null,
- guidelines_url: 'https://example.org/rules',
- });
- expect((await repository.getAppPublicConfig()).legal.guidelines_url).toBe('https://example.org/rules');
- expect(getLegalUrls()).toEqual({termsUrl: 'https://example.org/tos', guidelinesUrl: 'https://example.org/rules'});
- await repository.setAppPublicConfig({legal: {privacy_url: 'https://example.org/privacy'}});
- expect((await repository.getAppPublicConfig()).legal.guidelines_url).toBe('https://example.org/rules');
- await repository.setAppPublicConfig({legal: {guidelines_url: ' '}});
- expect((await repository.getAppPublicConfig()).legal.guidelines_url).toBeNull();
- expect(getLegalUrls()).toEqual({termsUrl: 'https://example.org/tos', guidelinesUrl: null});
- } finally {
- getConfig().instance.selfHosted = originalSelfHosted;
- setCachedConfiguredLegalUrls({terms_url: null, guidelines_url: null});
- }
- });
-
- it('loads the stored guidelines URL into the legal URL cache on initialize', async () => {
- setCassandraQueryExecutorForTesting(new InMemoryCassandraQueryExecutor());
- const kvProvider = new MockKVProvider();
- const originalSelfHosted = getConfig().instance.selfHosted;
- getConfig().instance.selfHosted = true;
- try {
- await createRepository(kvProvider).setConfig(
- APP_PUBLIC_CONFIG_KEY,
- JSON.stringify({legal: {terms_url: null, privacy_url: null, guidelines_url: 'https://example.org/rules'}}),
- );
- setCachedConfiguredLegalUrls({terms_url: null, guidelines_url: null});
- expect(getLegalUrls().guidelinesUrl).toBeNull();
- await createRepository(kvProvider).initialize();
- expect(getLegalUrls().guidelinesUrl).toBe('https://example.org/rules');
- } finally {
- getConfig().instance.selfHosted = originalSelfHosted;
- setCachedConfiguredLegalUrls({terms_url: null, guidelines_url: null});
- }
- });
-
- it('keeps the product name cache in step with the stored branding', async () => {
- setCassandraQueryExecutorForTesting(new InMemoryCassandraQueryExecutor());
- const kvProvider = new MockKVProvider();
- try {
- await createRepository(kvProvider).setConfig(
- APP_PUBLIC_CONFIG_KEY,
- JSON.stringify({branding: {product_name: 'Example Chat'}}),
- );
- setCachedProductName(null);
- await createRepository(kvProvider).initialize();
- expect(getInstanceProductName()).toBe('Example Chat');
- await createRepository(kvProvider).setAppPublicConfig({branding: {product_name: 'Renamed Chat'}});
- expect(getInstanceProductName()).toBe('Renamed Chat');
- } finally {
- setCachedProductName(null);
- }
- });
-
- it('reads a stored legal config written before the guidelines URL existed', async () => {
- setCassandraQueryExecutorForTesting(new InMemoryCassandraQueryExecutor());
- const repository = createRepository(new MockKVProvider());
- await repository.setConfig(
- APP_PUBLIC_CONFIG_KEY,
- JSON.stringify({legal: {terms_url: 'https://example.org/tos', privacy_url: null}}),
- );
- expect((await repository.getAppPublicConfig()).legal).toEqual({
- terms_url: 'https://example.org/tos',
- privacy_url: null,
- guidelines_url: null,
- });
- });
-
- it('keeps valid stored instance policy flags when one field is invalid', async () => {
- const executor = new InMemoryCassandraQueryExecutor();
- setCassandraQueryExecutorForTesting(executor);
- const kvProvider = new MockKVProvider();
- const repository = createRepository(kvProvider);
-
- await repository.setConfig(
- INSTANCE_POLICY_CONFIG_KEY,
- JSON.stringify({direct_messages_disabled: true, single_community_enabled: true, premium_mode: 'nonsense'}),
- );
-
- const policy = await repository.getInstancePolicyConfig();
- expect(policy.direct_messages_disabled).toBe(true);
- expect(policy.single_community_enabled).toBe(true);
- expect(policy.premium_mode).toBe('everyone');
- });
-
- it('keeps valid stored integration settings when one field is invalid', async () => {
- const executor = new InMemoryCassandraQueryExecutor();
- setCassandraQueryExecutorForTesting(executor);
- const kvProvider = new MockKVProvider();
- const repository = createRepository(kvProvider);
-
- await repository.setConfig(
- INSTANCE_INTEGRATIONS_CONFIG_KEY,
- JSON.stringify({bluesky: {client_name: 'Kept Instance', enabled: 'yes'}}),
- );
-
- expect((await repository.getEffectiveBlueskyConfig()).client_name).toBe('Kept Instance');
- expect((await repository.getInstanceIntegrationsConfig()).bluesky.enabled).toBeNull();
- });
-
- it('drops invalid stored SSO allowed domains and keeps the valid ones', async () => {
- const executor = new InMemoryCassandraQueryExecutor();
- setCassandraQueryExecutorForTesting(executor);
- const kvProvider = new MockKVProvider();
- const repository = createRepository(kvProvider);
-
- await repository.setConfig('sso_allowed_domains', JSON.stringify(['example.com', '[email protected]', 'Kept.ORG']));
-
- expect((await repository.getSsoConfig()).allowedEmailDomains).toEqual(['example.com', 'kept.org']);
- });
-
- it('falls back to the default SSO flags when a stored flag is not a boolean', async () => {
- const executor = new InMemoryCassandraQueryExecutor();
- setCassandraQueryExecutorForTesting(executor);
- const kvProvider = new MockKVProvider();
- const repository = createRepository(kvProvider);
-
- await repository.setConfig('sso_enabled', 'yes');
- await repository.setConfig('sso_enforced', 'sometimes');
- await repository.setConfig('sso_auto_provision', 'maybe');
-
- const config = await repository.getSsoConfig();
- expect(config.enabled).toBe(false);
- expect(config.enforced).toBe(false);
- expect(config.autoProvision).toBe(true);
- });
-
it('clears an invalid allowed domain list only while SSO is disabled', async () => {
const executor = new InMemoryCassandraQueryExecutor();
setCassandraQueryExecutorForTesting(executor);
@@ -444,129 +61,6 @@ describe('InstanceConfigRepository', () => {
expect(domains.length).toBeGreaterThan(0);
expect(domains).not.toContain('example.com');
});
-
- it('serves the everyone channel threads config at version zero when the key is absent', async () => {
- setCassandraQueryExecutorForTesting(new InMemoryCassandraQueryExecutor());
- const repository = createRepository(new MockKVProvider());
-
- await expect(repository.getChannelThreadsConfig()).resolves.toEqual(everyoneChannelThreadsConfig(0));
- });
-
- it.each([
- {
- name: 'a disabled row',
- stored: JSON.stringify({
- ...DEFAULT_CHANNEL_THREADS_CONFIG,
- enabled: false,
- config_version: 9,
- disabled_guild_ids: ['1400000000000000001'],
- excluded_user_ids: ['1400000000000000002'],
- }),
- version: 9,
- },
- {name: 'a partial rollout row', stored: '{"enabled":true,"config_version":4,"guild_basis_points":100}', version: 4},
- {name: 'a row with an invalid version', stored: '{"enabled":false,"config_version":-1}', version: 0},
- {name: 'unparseable text', stored: 'not-json', version: 0},
- ])('serves the everyone channel threads config for $name and keeps the stored version', async ({stored, version}) => {
- setCassandraQueryExecutorForTesting(new InMemoryCassandraQueryExecutor());
- const repository = createRepository(new MockKVProvider());
-
- await repository.setConfig(CHANNEL_THREADS_CONFIG_KEY, stored);
-
- await expect(repository.getChannelThreadsConfig()).resolves.toEqual(everyoneChannelThreadsConfig(version));
- });
-
- it('returns the default domain migration config when the key is absent', async () => {
- const executor = new InMemoryCassandraQueryExecutor();
- setCassandraQueryExecutorForTesting(executor);
- const kvProvider = new MockKVProvider();
- const repository = createRepository(kvProvider);
-
- await expect(repository.getDomainMigrationConfig()).resolves.toEqual(DEFAULT_DOMAIN_MIGRATION_CONFIG);
- });
-
- it.each([
- {name: 'unparseable text', stored: 'not-json'},
- {name: 'a json array', stored: '[]'},
- {name: 'out-of-range values', stored: '{"rollout_basis_points":99999}'},
- {name: 'a non-boolean enabled flag', stored: '{"enabled":"yes"}'},
- ])('falls back to the default domain migration config for $name', async ({stored}) => {
- const executor = new InMemoryCassandraQueryExecutor();
- setCassandraQueryExecutorForTesting(executor);
- const kvProvider = new MockKVProvider();
- const repository = createRepository(kvProvider);
-
- await repository.setConfig(DOMAIN_MIGRATION_CONFIG_KEY, stored);
-
- await expect(repository.getDomainMigrationConfig()).resolves.toEqual(DEFAULT_DOMAIN_MIGRATION_CONFIG);
- });
-
- it('publishes a refresh so another repository observes the domain migration config', async () => {
- const executor = new InMemoryCassandraQueryExecutor();
- setCassandraQueryExecutorForTesting(executor);
- const kvProvider = new MockKVProvider();
- const reader = createRepository(kvProvider);
- const writer = createRepository(kvProvider);
-
- await expect(reader.getDomainMigrationConfig()).resolves.toEqual(DEFAULT_DOMAIN_MIGRATION_CONFIG);
-
- await writer.setDomainMigrationConfig({
- ...DEFAULT_DOMAIN_MIGRATION_CONFIG,
- enabled: true,
- config_version: 1,
- });
-
- await vi.waitFor(async () => {
- expect(await reader.getDomainMigrationConfig()).toMatchObject({enabled: true, config_version: 1});
- });
- });
-
- it('returns the default experiment delivery config when the key is absent', async () => {
- const executor = new InMemoryCassandraQueryExecutor();
- setCassandraQueryExecutorForTesting(executor);
- const kvProvider = new MockKVProvider();
- const repository = createRepository(kvProvider);
-
- await expect(repository.getExperimentDeliveryConfig()).resolves.toEqual(DEFAULT_EXPERIMENT_DELIVERY_CONFIG);
- });
-
- it.each([
- {name: 'unparseable text', stored: 'not-json'},
- {name: 'a json array', stored: '[]'},
- {name: 'an out-of-range poll interval', stored: '{"poll_interval_seconds":1}'},
- {name: 'an out-of-range jitter', stored: '{"poll_jitter_percent":99}'},
- {name: 'a non-numeric poll interval', stored: '{"poll_interval_seconds":"often"}'},
- ])('falls back to the default experiment delivery config for $name', async ({stored}) => {
- const executor = new InMemoryCassandraQueryExecutor();
- setCassandraQueryExecutorForTesting(executor);
- const kvProvider = new MockKVProvider();
- const repository = createRepository(kvProvider);
-
- await repository.setConfig(EXPERIMENT_DELIVERY_CONFIG_KEY, stored);
-
- await expect(repository.getExperimentDeliveryConfig()).resolves.toEqual(DEFAULT_EXPERIMENT_DELIVERY_CONFIG);
- });
-
- it('uses the registration URL id as the admin-visible registration code', async () => {
- const executor = new InMemoryCassandraQueryExecutor();
- setCassandraQueryExecutorForTesting(executor);
- const kvProvider = new MockKVProvider();
- const repository = createRepository(kvProvider);
-
- const created = await repository.createRegistrationUrl({
- label: 'Support invite',
- createdByUserId: '1500000000000000000',
- expiresAt: null,
- maxUses: null,
- approvalRequired: false,
- });
-
- expect(created.code).toBe(created.registrationUrl.id);
- expect(created.registrationUrl).not.toHaveProperty('code_hash');
- await expect(repository.resolveRegistrationUrlCode(created.registrationUrl.id)).resolves.toMatchObject({
- id: created.registrationUrl.id,
- });
- });
});
function describeConcurrentInstanceConfigWrites(prepareBase: () => Promise<CassandraQueryExecutorForTesting>): void {
@@ -609,7 +103,11 @@ function describeConcurrentInstanceConfigWrites(prepareBase: () => Promise<Cassa
expect(executor.events.filter((event) => event === 'write rejected')).toHaveLength(1);
expect(executor.events.filter((event) => event === 'write')).toHaveLength(2);
- expect(await readStoredRegistrationConfig()).toEqual({mode: 'closed', admin_registration_urls_enabled: false});
+ expect(await readStoredRegistrationConfig()).toEqual({
+ mode: 'closed',
+ admin_registration_urls_enabled: false,
+ allowed_email_domains: [],
+ });
});
it('lets one of two concurrent first writes create the config and applies the other on top', async () => {
@@ -627,7 +125,11 @@ function describeConcurrentInstanceConfigWrites(prepareBase: () => Promise<Cassa
expect(executor.events.filter((event) => event === 'write rejected')).toHaveLength(1);
expect(executor.events.filter((event) => event === 'write')).toHaveLength(2);
- expect(await readStoredRegistrationConfig()).toEqual({mode: 'closed', admin_registration_urls_enabled: false});
+ expect(await readStoredRegistrationConfig()).toEqual({
+ mode: 'closed',
+ admin_registration_urls_enabled: false,
+ allowed_email_domains: [],
+ });
});
it('re-reads the database, not its stale cache, when a concurrent write lands between its read and its write', async () => {
@@ -636,7 +138,11 @@ function describeConcurrentInstanceConfigWrites(prepareBase: () => Promise<Cassa
await stale.setRegistrationConfig({mode: 'open', admin_registration_urls_enabled: true});
await stale.getRegistrationConfig();
await other.setRegistrationConfig({mode: 'approval'});
- expect(await stale.getRegistrationConfig()).toEqual({mode: 'open', admin_registration_urls_enabled: true});
+ expect(await stale.getRegistrationConfig()).toEqual({
+ mode: 'open',
+ admin_registration_urls_enabled: true,
+ allowed_email_domains: [],
+ });
executor.watch(REGISTRATION_CONFIG_KEY);
let competed = false;
executor.competeBeforeEachWrite(async () => {
@@ -651,7 +157,11 @@ function describeConcurrentInstanceConfigWrites(prepareBase: () => Promise<Cassa
await stale.setRegistrationConfig({mode: 'closed'});
expect(executor.events).toEqual(['read', 'write rejected', 'read', 'write']);
- expect(await readStoredRegistrationConfig()).toEqual({mode: 'closed', admin_registration_urls_enabled: false});
+ expect(await readStoredRegistrationConfig()).toEqual({
+ mode: 'closed',
+ admin_registration_urls_enabled: false,
+ allowed_email_domains: [],
+ });
});
it('fails loudly and writes nothing once every attempt has lost the race', async () => {
@@ -737,7 +247,7 @@ function describeConcurrentInstanceConfigWrites(prepareBase: () => Promise<Cassa
const {code, registrationUrl} = await admin.createRegistrationUrl(registrationUrlParams(null));
expect(await signup.resolveRegistrationUrlCode(code)).not.toBeNull();
- await admin.revokeRegistrationUrl(registrationUrl.id);
+ await admin.revokeOrRemoveRegistrationUrl(registrationUrl.id);
await expect(signup.resolveRegistrationUrlCode(code)).resolves.toBeNull();
await expect(signup.claimRegistrationUrlUse(registrationUrl.id, '1400000000000000501')).resolves.toBeNull();
@@ -1067,15 +577,6 @@ describe('InstanceConfigRepository setup token', () => {
expect(await pod.claimAdminBootstrap()).toBe(false);
});
- it('keeps a won admin bootstrap claim when the refresh cannot be published', async () => {
- const pod = createPod();
- await pod.isAdminBootstrapped();
- vi.spyOn(kvProvider, 'publish').mockRejectedValueOnce(new Error('kv down'));
- expect(await pod.claimAdminBootstrap()).toBe(true);
- expect(await pod.isAdminBootstrapped()).toBe(true);
- expect(await executor.readDirectly('admin_bootstrapped')).toBe('true');
- });
-
it('enforces the setup token only on self-hosted instances that run in production or configure one', async () => {
const pod = createPod();
const gate = async () => ({
@@ -1195,12 +696,10 @@ describe('InstanceConfigRepository setup token', () => {
const stale = createPod();
const writer = createPod();
expect(await stale.isAdminBootstrapped()).toBe(false);
- vi.spyOn(kvProvider, 'publish').mockRejectedValueOnce(new Error('kv down'));
await writer.claimAdminBootstrap();
expect(await stale.isAdminBootstrapped()).toBe(false);
expect(await stale.confirmAdminBootstrapped()).toBe(true);
expect(await stale.isAdminBootstrapped()).toBe(true);
- vi.spyOn(kvProvider, 'publish').mockRejectedValueOnce(new Error('kv down'));
await writer.releaseAdminBootstrap();
expect(await stale.isAdminBootstrapped()).toBe(true);
expect(await stale.confirmAdminBootstrapped()).toBe(false);
@@ -1219,29 +718,4 @@ describe('InstanceConfigRepository concurrent writes', () => {
describe('in memory', () => {
describeConcurrentInstanceConfigWrites(async () => new InMemoryCassandraQueryExecutor());
});
-
- describe.skipIf(!dockerAvailable)('on postgres', () => {
- let client: IPostgresClient;
-
- let postgresContainer: string;
- beforeAll(async () => {
- const started = await startPostgresKv({
- namePrefix: 'fluxer-instance-config-races',
- kvTable: POSTGRES_KV_TABLE,
- maxConnections: 4,
- });
- postgresContainer = started.container;
- client = started.client;
- }, 900_000);
-
- afterAll(async () => {
- setCassandraQueryExecutorForTesting(new InMemoryCassandraQueryExecutor());
- await stopPostgresKv(postgresContainer);
- });
-
- describeConcurrentInstanceConfigWrites(async () => {
- await client.query(`DELETE FROM ${POSTGRES_KV_TABLE}`);
- return new PostgresKvQueryExecutor(client);
- });
- });
});
diff --git a/fluxer_api/src/api/instance/InstanceConfigRepositoryBilling.test.ts b/fluxer_api/src/api/instance/InstanceConfigRepositoryBilling.test.ts
index fabf24ec5..3281612eb 100644
--- a/fluxer_api/src/api/instance/InstanceConfigRepositoryBilling.test.ts
+++ b/fluxer_api/src/api/instance/InstanceConfigRepositoryBilling.test.ts
@@ -11,7 +11,7 @@ import {
} from '@app/api/stripe/BillingConfigCache';
import {InMemoryCassandraQueryExecutor} from '@app/api/test/InMemoryCassandraQueryExecutor';
import {MockKVProvider} from '@pkgs/kv_client/src/testing/MockKVProvider';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterEach, beforeEach, describe, expect, it} from 'vitest';
const INSTANCE_BILLING_CONFIG_KEY = 'instance_billing_config';
@@ -100,47 +100,6 @@ describe('InstanceConfigRepository billing and premium branding', () => {
expect(await readRaw(repository, INSTANCE_BILLING_CONFIG_KEY)).toEqual(cleared);
});
- it('fills missing price slots with null and treats an empty price map as the env catalog', async () => {
- const repository = createRepository();
- const partial = await repository.setInstanceBillingConfig({prices: {GBP: {monthly: 'price_GbpMonthly'}}});
- expect(partial.prices).toEqual({
- GBP: {monthly: 'price_GbpMonthly', yearly: null, gift_1_month: null, gift_1_year: null},
- });
- const emptied = await repository.setInstanceBillingConfig({prices: {}});
- expect(emptied.prices).toBeNull();
- expect(getEffectiveBillingConfig().catalogMode).toBe('env');
- });
-
- it('rejects a patch that would store an invalid value', async () => {
- const repository = createRepository();
- await expect(repository.setInstanceBillingConfig({default_currency: 'gbp'})).rejects.toThrow(/billing/);
- await expect(repository.setInstanceBillingConfig({prices: {GBP: {monthly: 'not-a-price-id'}}})).rejects.toThrow(
- /billing/,
- );
- expect(await repository.getConfig(INSTANCE_BILLING_CONFIG_KEY)).toBeNull();
- });
-
- it('keeps, sets and clears the checkout flags like the other nullable fields', async () => {
- const repository = createRepository();
- const set = await repository.setInstanceBillingConfig({automatic_tax: true, terms_consent_required: false});
- expect(set.automatic_tax).toBe(true);
- expect(set.tax_id_collection).toBeNull();
- expect(set.terms_consent_required).toBe(false);
- const kept = await repository.setInstanceBillingConfig({tax_id_collection: true});
- expect(kept.automatic_tax).toBe(true);
- expect(kept.tax_id_collection).toBe(true);
- expect(kept.terms_consent_required).toBe(false);
- const cleared = await repository.setInstanceBillingConfig({automatic_tax: null});
- expect(cleared.automatic_tax).toBeNull();
- const admin = await repository.getInstanceBillingAdminConfig();
- expect(admin.automatic_tax).toBeNull();
- expect(admin.tax_id_collection).toBe(true);
- expect(admin.terms_consent_required).toBe(false);
- expect(admin.effective_automatic_tax).toBe(false);
- expect(admin.effective_tax_id_collection).toBe(true);
- expect(admin.effective_terms_consent_required).toBe(false);
- });
-
it('reports env-sourced secrets as set but not stored', async () => {
const repository = createRepository();
const admin = await repository.getInstanceBillingAdminConfig();
@@ -175,56 +134,4 @@ describe('InstanceConfigRepository billing and premium branding', () => {
expect(admin.effective_tax_id_collection).toBe(true);
expect(admin.effective_terms_consent_required).toBe(true);
});
-
- it('salvages the valid fields of a partly invalid stored billing config', async () => {
- const repository = createRepository();
- await repository.setConfig(
- INSTANCE_BILLING_CONFIG_KEY,
- JSON.stringify({
- enabled: 'yes',
- stripe_secret_key: 'sk_test_kept',
- default_currency: 'GBP',
- prices: {
- GBP: GBP_PRICES,
- gbp: GBP_PRICES,
- EUR: {...GBP_PRICES, monthly: 'bogus'},
- },
- country_currencies: {GB: 'GBP', gb: 'GBP'},
- }),
- );
-
- const config = await repository.getInstanceBillingConfig();
- expect(config.enabled).toBeNull();
- expect(config.stripe_secret_key).toBe('sk_test_kept');
- expect(config.default_currency).toBe('GBP');
- expect(config.prices?.GBP).toEqual(GBP_PRICES);
- expect(config.prices).not.toHaveProperty('gbp');
- expect(config.prices?.EUR?.monthly ?? null).toBeNull();
- expect(config.country_currencies).toEqual({GB: 'GBP'});
- });
-
- it('falls back to an empty billing config when the stored value is not JSON', async () => {
- const repository = createRepository();
- await repository.setConfig(INSTANCE_BILLING_CONFIG_KEY, '{not json');
- expect((await repository.getInstanceBillingConfig()).prices).toBeNull();
- });
-
- it('updates the process billing cache when another repository publishes a billing change', async () => {
- const kvProvider = new MockKVProvider();
- const reader = createRepository(kvProvider);
- const writer = createRepository(kvProvider);
- await reader.getInstanceBillingConfig();
- await writer.getInstanceBillingConfig();
- setStoredBillingConfig(null);
-
- await writer.setConfig(
- INSTANCE_BILLING_CONFIG_KEY,
- JSON.stringify({enabled: true, prices: {GBP: GBP_PRICES}, default_currency: 'GBP'}),
- );
-
- await vi.waitFor(() => {
- expect(getStoredBillingConfig()?.default_currency).toBe('GBP');
- });
- expect(getEffectiveBillingConfig().catalogMode).toBe('operator');
- });
});
diff --git a/fluxer_api/src/api/jobs/JobLedgerRepository.test.ts b/fluxer_api/src/api/jobs/JobLedgerRepository.test.ts
index 7217dee7c..33cbef8cb 100644
--- a/fluxer_api/src/api/jobs/JobLedgerRepository.test.ts
+++ b/fluxer_api/src/api/jobs/JobLedgerRepository.test.ts
@@ -14,7 +14,6 @@ import {
JOB_STALE_AFTER_MS,
JobLedgerRepository,
} from '@app/api/jobs/JobLedgerRepository';
-import {describeListJobsPaging} from '@app/api/jobs/ListJobsPagingSuite';
import {JobsActive, JobsByDayBucket, JobsById} from '@app/api/Tables';
import {InMemoryCassandraQueryExecutor} from '@app/api/test/InMemoryCassandraQueryExecutor';
import {createSnowflake} from '@fluxer/snowflake/src/Snowflake';
@@ -50,20 +49,6 @@ async function createJobAt(repository: JobLedgerRepository, jobId: bigint): Prom
});
}
-describe('JobLedgerRepository listJobs on the in-memory executor', () => {
- beforeEach(() => {
- executor = new InMemoryCassandraQueryExecutor();
- setCassandraQueryExecutorForTesting(executor);
- });
-
- afterEach(() => {
- executor.reset();
- setCassandraQueryExecutorForTesting(null);
- });
-
- describeListJobsPaging();
-});
-
let staleSequence = 0;
function jobIdAgedDays(days: number): bigint {
@@ -153,42 +138,16 @@ describe('JobLedgerRepository expireStaleActiveJobs', () => {
});
});
-describe('JobLedgerRepository getJob', () => {
- beforeEach(() => {
- executor = new InMemoryCassandraQueryExecutor();
- setCassandraQueryExecutorForTesting(executor);
- });
-
- afterEach(() => {
- executor.reset();
- setCassandraQueryExecutorForTesting(null);
- });
-
- it('hides a job row that lost its status, creation time or task type', async () => {
- const repository = new JobLedgerRepository();
- await createJob(repository, 9n, 'syncUrlBlocklists');
- expect((await repository.getJob(9n))?.status).toBe('queued');
- for (const column of ['status', 'created_at', 'task_type'] as const) {
- await createJob(repository, 9n, 'syncUrlBlocklists');
- await executeQuery(JobsById.patchByPk({job_id: 9n}, {[column]: Db.clear()}));
- expect(await repository.getJob(9n)).toBeNull();
- }
- });
-});
-
describe('JobLedgerRepository discardJob', () => {
let inner: InMemoryCassandraQueryExecutor;
- let log: Array<string>;
let failDeleteOn: string | null;
beforeEach(() => {
inner = new InMemoryCassandraQueryExecutor();
- log = [];
failDeleteOn = null;
const wrapper: CassandraQueryExecutorForTesting = {
async executeQuery<T>(query: PreparedQuery) {
const meta = query.kvMeta;
- if (meta) log.push(`${meta.action} ${meta.table.name}`);
if (meta?.action === 'delete' && meta.table.name === failDeleteOn) {
throw new Error('write timeout');
}
@@ -204,25 +163,6 @@ describe('JobLedgerRepository discardJob', () => {
setCassandraQueryExecutorForTesting(null);
});
- it('removes every ledger row of a duplicate with three deletes and no read', async () => {
- const repository = new JobLedgerRepository();
- const createdAt = await createJobAt(repository, 7n);
- log.length = 0;
-
- await repository.discardJob(7n, createdAt);
-
- expect([...log].sort()).toEqual(['delete jobs_active', 'delete jobs_by_day_bucket', 'delete jobs_by_id']);
- expect(await repository.getJob(7n)).toBeNull();
- expect(await repository.listActiveJobs()).toEqual([]);
- expect(
- await fetchMany(
- JobsByDayBucket.select({where: JobsByDayBucket.where.eq('bucket_day')}).bind({
- bucket_day: createdAt.toISOString().slice(0, 10),
- }),
- ),
- ).toEqual([]);
- });
-
it('keeps deleting the other ledger rows when one delete fails', async () => {
const repository = new JobLedgerRepository();
const createdAt = await createJobAt(repository, 8n);
diff --git a/fluxer_api/src/api/middleware/tests/ContentFilterMiddleware.test.ts b/fluxer_api/src/api/middleware/tests/ContentFilterMiddleware.test.ts
index 184c7617e..1175396e9 100644
--- a/fluxer_api/src/api/middleware/tests/ContentFilterMiddleware.test.ts
+++ b/fluxer_api/src/api/middleware/tests/ContentFilterMiddleware.test.ts
@@ -4,52 +4,6 @@ import {extractStringValues, shouldSkipContentFilterPath} from '@app/api/middlew
import {describe, expect, test} from 'vitest';
describe('extractStringValues', () => {
- test('returns text from user-generated content fields', () => {
- const body = {
- content: 'visible message content',
- code: 'public-vanity-code',
- embeds: [{title: 'embed title', description: 'embed description'}],
- attachments: [{filename: 'visible-filename.png', title: 'attachment title'}],
- };
- const result = extractStringValues(body);
- expect(result).toEqual([
- 'visible message content',
- 'public-vanity-code',
- 'embed title',
- 'embed description',
- 'visible-filename.png',
- 'attachment title',
- ]);
- });
- test('omits machine metadata fields from nested payloads', () => {
- const body = {
- content: 'visible message content',
- attachments: [
- {
- id: '1',
- upload_filename: '2f31b930-d1ea-453f-aa6a-4f7ddc7d04d5',
- content_type: 'image/png',
- waveform: 'AA==',
- title: 'visible attachment title',
- },
- ],
- allowed_mentions: {
- users: ['111111111111111111'],
- roles: ['222222222222222222'],
- },
- message_reference: {
- channel_id: '333333333333333333',
- message_id: '444444444444444444',
- },
- response: {
- clientDataJSON: 'eyJjaGFsbGVuZ2UiOiJub25jZSJ9',
- },
- synced_preferences: 'CgIIAQ==',
- thumbnail: 'data:image/png;base64,AAAA',
- };
- const result = extractStringValues(body);
- expect(result).toEqual(['visible message content', 'visible attachment title']);
- });
test('omits fields with identifier and secret suffixes', () => {
const body = {
label: 'visible label',
@@ -63,22 +17,6 @@ describe('extractStringValues', () => {
const result = extractStringValues(body);
expect(result).toEqual(['visible label']);
});
- test('omits the structural fields of report flow submissions', () => {
- const body = {
- channel_id: '111111111111111111',
- message_id: '222222222222222222',
- user_id: '333333333333333333',
- guild_id: '444444444444444444',
- revision_hash: '6b1f0c9e2a7d4413',
- locale: 'de',
- steps: [
- {screen_id: 'root_message', option_id: 'private_info'},
- {screen_id: 'private_info', item_ids: ['email', 'phone']},
- ],
- };
- const result = extractStringValues(body);
- expect(result).toEqual([]);
- });
});
describe('shouldSkipContentFilterPath', () => {
@@ -92,11 +30,6 @@ describe('shouldSkipContentFilterPath', () => {
const result = paths.map((path) => shouldSkipContentFilterPath(path));
expect(result).toEqual([true, true, true, true]);
});
- test('skips every DSA report body, which has to quote the reported content', () => {
- const paths = ['/reports/dsa', '/reports/dsa/email/send', '/reports/dsa/email/verify'];
- const result = paths.map((path) => shouldSkipContentFilterPath(path));
- expect(result).toEqual([true, true, true]);
- });
test('does not skip in-app report submissions', () => {
const paths = ['/reports/message', '/reports/user', '/reports/flows/message/submissions'];
const result = paths.map((path) => shouldSkipContentFilterPath(path));
@@ -107,14 +40,4 @@ describe('shouldSkipContentFilterPath', () => {
const result = paths.map((path) => shouldSkipContentFilterPath(path));
expect(result).toEqual([false, false, false]);
});
- test('skips blocklist writes whose values are the blocked content', () => {
- const paths = [
- '/admin/blocklists/phrase/entries',
- '/admin/blocklists/url/entries',
- '/admin/blocklists/url-domain/entries',
- '/admin/blocklists/profile-substring/entries',
- ];
- const result = paths.map((path) => shouldSkipContentFilterPath(path));
- expect(result).toEqual([true, true, true, false]);
- });
});
diff --git a/fluxer_api/src/api/middleware/tests/RateLimitMiddleware.test.ts b/fluxer_api/src/api/middleware/tests/RateLimitMiddleware.test.ts
index bf14981ac..c514bafe9 100644
--- a/fluxer_api/src/api/middleware/tests/RateLimitMiddleware.test.ts
+++ b/fluxer_api/src/api/middleware/tests/RateLimitMiddleware.test.ts
@@ -1,6 +1,5 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import {createHash} from 'node:crypto';
import {Config} from '@app/api/Config';
import type {TrustedCallerConfig} from '@app/api/config/APIConfig';
import {RateLimitMiddleware, type RouteRateLimitConfig} from '@app/api/middleware/RateLimitMiddleware';
@@ -13,22 +12,9 @@ import type {
RateLimitConfig,
RateLimitResult,
} from '@pkgs/rate_limit/src/IRateLimitService';
-import {type Context, Hono} from 'hono';
+import {Hono} from 'hono';
import {afterEach, beforeEach, describe, expect, test} from 'vitest';
-const CLIENT_IP = '203.0.113.10';
-const SWAPPED_CLIENT_IP = '198.51.100.7';
-
-const WEBHOOK_READ: RouteRateLimitConfig = {
- bucket: 'webhook:read::webhook_id',
- config: {limit: 40, windowMs: 10000},
-};
-
-const WEBHOOK_UPDATE: RouteRateLimitConfig = {
- bucket: 'webhook:update::webhook_id',
- config: {limit: 20, windowMs: 10000},
-};
-
function createAllowedResult(limit: number): RateLimitResult {
return {
allowed: true,
@@ -42,7 +28,6 @@ function createAllowedResult(limit: number): RateLimitResult {
class RecordingRateLimitService implements IRateLimitService {
readonly globalIdentifiers: Array<string> = [];
readonly buckets: Array<string> = [];
- onGlobalCheck: () => void = () => undefined;
async checkLimit(config: RateLimitConfig): Promise<RateLimitResult> {
return createAllowedResult(config.maxAttempts);
@@ -59,7 +44,6 @@ class RecordingRateLimitService implements IRateLimitService {
async checkGlobalLimit(identifier: string, limit: number): Promise<RateLimitResult> {
this.globalIdentifiers.push(identifier);
- this.onGlobalCheck();
return createAllowedResult(limit);
}
@@ -73,84 +57,8 @@ class RecordingRateLimitService implements IRateLimitService {
interface Harness {
app: Hono<HonoEnv>;
service: RecordingRateLimitService;
- getContext(): Context<HonoEnv>;
-}
-
-function buildHarness(routeConfig: RouteRateLimitConfig): Harness {
- const service = new RecordingRateLimitService();
- let context: Context<HonoEnv> | null = null;
- const app = new Hono<HonoEnv>({strict: true});
- app.use('*', async (ctx, next) => {
- context = ctx;
- ctx.set('rateLimitService', service);
- await next();
- });
- app.get('/webhooks/:webhook_id/:token', RateLimitMiddleware(routeConfig), (ctx) => ctx.text('ok'));
- return {
- app,
- service,
- getContext(): Context<HonoEnv> {
- if (!context) {
- throw new Error('no request has run yet');
- }
- return context;
- },
- };
-}
-
-async function callRoute(harness: Harness, webhookId: string, clientIp = CLIENT_IP): Promise<Response> {
- return await harness.app.request(`http://localhost/webhooks/${webhookId}/secret`, {
- headers: {
- 'x-forwarded-for': clientIp,
- 'x-fluxer-test-enable-rate-limits': 'true',
- },
- });
}
-function expectedBucketHash(bucket: string): string {
- return createHash('sha256').update(bucket).digest('hex').slice(0, 16);
-}
-
-describe('RateLimitMiddleware', () => {
- test('reports the same bucket hash for every request to a route', async () => {
- const harness = buildHarness(WEBHOOK_READ);
-
- const first = await callRoute(harness, '111');
- const second = await callRoute(harness, '222');
-
- expect(first.status).toBe(200);
- expect(second.status).toBe(200);
- expect(first.headers.get('X-RateLimit-Bucket')).toBe(expectedBucketHash(WEBHOOK_READ.bucket));
- expect(second.headers.get('X-RateLimit-Bucket')).toBe(first.headers.get('X-RateLimit-Bucket'));
- expect(harness.service.buckets).toEqual([`ip:${CLIENT_IP}:webhook:read:111`, `ip:${CLIENT_IP}:webhook:read:222`]);
- });
-
- test('gives routes with different buckets different bucket hashes', async () => {
- const readHarness = buildHarness(WEBHOOK_READ);
- const updateHarness = buildHarness(WEBHOOK_UPDATE);
-
- const read = await callRoute(readHarness, '111');
- const update = await callRoute(updateHarness, '111');
-
- expect(read.headers.get('X-RateLimit-Bucket')).toBe(expectedBucketHash(WEBHOOK_READ.bucket));
- expect(update.headers.get('X-RateLimit-Bucket')).toBe(expectedBucketHash(WEBHOOK_UPDATE.bucket));
- expect(read.headers.get('X-RateLimit-Bucket')).not.toBe(update.headers.get('X-RateLimit-Bucket'));
- });
-
- test('resolves the client identifier once and reuses it for the bucket key', async () => {
- const harness = buildHarness(WEBHOOK_READ);
- harness.service.onGlobalCheck = () => {
- harness.getContext().req.raw.headers.set('x-forwarded-for', SWAPPED_CLIENT_IP);
- };
-
- const response = await callRoute(harness, '111');
-
- expect(response.status).toBe(200);
- expect(harness.service.globalIdentifiers).toEqual([`ip:${CLIENT_IP}`]);
- expect(harness.service.buckets).toEqual([`ip:${CLIENT_IP}:webhook:read:111`]);
- });
-});
-
const CALLER_IP = '192.0.2.50';
const FORWARDED_IP = '203.0.113.77';
const OTHER_FORWARDED_IP = '203.0.113.78';
@@ -168,24 +76,13 @@ const TRUSTED_CALLERS: Array<TrustedCallerConfig> = [
function buildTrustedHarness(routeConfig: RouteRateLimitConfig): Harness {
const service = new RecordingRateLimitService();
- let context: Context<HonoEnv> | null = null;
const app = new Hono<HonoEnv>({strict: true});
app.use('*', async (ctx, next) => {
- context = ctx;
ctx.set('rateLimitService', service);
await next();
});
app.post('/route', RateLimitMiddleware(routeConfig), (ctx) => ctx.text('ok'));
- return {
- app,
- service,
- getContext(): Context<HonoEnv> {
- if (!context) {
- throw new Error('no request has run yet');
- }
- return context;
- },
- };
+ return {app, service};
}
async function callTrustedRoute(harness: Harness, headers: Record<string, string>): Promise<Response> {
diff --git a/fluxer_api/src/api/middleware/tests/ResponseTypeMiddleware.test.ts b/fluxer_api/src/api/middleware/tests/ResponseTypeMiddleware.test.ts
index 37d402a30..cc92da6b0 100644
--- a/fluxer_api/src/api/middleware/tests/ResponseTypeMiddleware.test.ts
+++ b/fluxer_api/src/api/middleware/tests/ResponseTypeMiddleware.test.ts
@@ -3,10 +3,9 @@
import {Config} from '@app/api/Config';
import {OpenAPI} from '@app/api/middleware/ResponseTypeMiddleware';
import type {HonoEnv} from '@app/api/types/HonoEnv';
-import {Logger} from '@fluxer/logger/src/Logger';
import {SnowflakeType} from '@fluxer/schema/src/primitives/SchemaPrimitives';
import {Hono} from 'hono';
-import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';
+import {afterEach, beforeEach, describe, expect, test} from 'vitest';
import {z} from 'zod';
const SnowflakeResponse = z.object({id: SnowflakeType});
@@ -42,63 +41,6 @@ describe('ResponseTypeMiddleware', () => {
expect(await response.json()).toEqual({id: '123456789012345678'});
});
- test.each([undefined, 'application/json', 'application/json; charset=utf-8', 'Application/JSON; charset=utf-8'])(
- 'rejects mismatching responses while validation is enabled (content type: %s)',
- async (responseContentType) => {
- const app = new Hono<HonoEnv>();
- const middleware = OpenAPI({
- operationId: 'get_invalid_snowflake_test',
- summary: 'Get invalid snowflake',
- description: 'Returns an invalid snowflake to verify JSON response validation.',
- responseSchema: SnowflakeResponse,
- ...(responseContentType === undefined ? {} : {responseContentType}),
- tags: ['Tests'],
- });
- app.get('/snowflake', middleware, (ctx) => ctx.json({id: 'not-a-snowflake'}));
- const errorLoggerSpy = vi.spyOn(Logger.prototype, 'error').mockImplementation(() => {});
-
- try {
- const response = await app.request('/snowflake');
-
- expect(response.status).toBe(500);
- expect(errorLoggerSpy).toHaveBeenCalledTimes(1);
- expect(errorLoggerSpy).toHaveBeenCalledWith(
- {
- body: {id: 'not-a-snowflake'},
- method: 'GET',
- path: '/snowflake',
- status: 200,
- validationErrors: [{message: 'INVALID_SNOWFLAKE_FORMAT', path: 'id'}],
- },
- 'Response validation failed',
- );
- } finally {
- errorLoggerSpy.mockRestore();
- }
- },
- );
-
- test('passes the OpenAPI response through untouched while validation is disabled', async () => {
- Config.dev.validateResponses = false;
- const app = new Hono<HonoEnv>();
- app.get(
- '/snowflake',
- OpenAPI({
- operationId: 'get_snowflake_unvalidated_test',
- summary: 'Get snowflake test',
- description: 'Returns an unvalidated payload for response validation gating coverage.',
- responseSchema: SnowflakeResponse,
- tags: ['Tests'],
- }),
- (ctx) => ctx.json({id: 'not-a-snowflake', extra: 'kept'}),
- );
-
- const response = await app.request('/snowflake');
-
- expect(response.status).toBe(200);
- expect(await response.json()).toEqual({id: 'not-a-snowflake', extra: 'kept'});
- });
-
test('preserves raw JSON file bytes under a binary response contract', async () => {
const body = '{ "file": "contents" }';
const app = new Hono<HonoEnv>();
diff --git a/fluxer_api/src/api/test/InMemoryCassandraQueryExecutor.ts b/fluxer_api/src/api/test/InMemoryCassandraQueryExecutor.ts
index 9fcd7f0dc..fafe70def 100644
--- a/fluxer_api/src/api/test/InMemoryCassandraQueryExecutor.ts
+++ b/fluxer_api/src/api/test/InMemoryCassandraQueryExecutor.ts
@@ -97,7 +97,6 @@ function parseRawMeta(cql: string): KvQueryMeta<Row> | null {
export class InMemoryCassandraQueryExecutor implements CassandraQueryExecutorForTesting {
private readonly tables = new Map<string, Map<string, Row>>();
readonly executed: Array<KvQueryMeta> = [];
- readonly batchAtomicity: Array<boolean> = [];
countStatements(statement: string): number {
return this.executed.filter((meta) => `${meta.action}:${meta.table.name}` === statement).length;
}
@@ -105,7 +104,6 @@ export class InMemoryCassandraQueryExecutor implements CassandraQueryExecutorFor
reset(): void {
this.tables.clear();
this.executed.length = 0;
- this.batchAtomicity.length = 0;
}
private table(meta: KvQueryMeta): Map<string, Row> {
@@ -160,12 +158,21 @@ export class InMemoryCassandraQueryExecutor implements CassandraQueryExecutorFor
return [];
}
+ async executePagedQuery<T = Row>(
+ query: PreparedQuery,
+ options: {pageSize: number; pageState?: string | null},
+ ): Promise<{rows: Array<T>; pageState: string | null}> {
+ const rows = await this.executeQuery<T>(query);
+ const offset = options.pageState ? Number.parseInt(options.pageState, 10) : 0;
+ const page = rows.slice(offset, offset + options.pageSize);
+ const nextOffset = offset + page.length;
+ return {rows: page, pageState: nextOffset < rows.length ? String(nextOffset) : null};
+ }
+
async executeBatch(
queries: Array<{query: string; params: object; meta?: KvQueryMeta}>,
- atomic?: boolean,
+ _atomic?: boolean,
): Promise<void> {
- this.batchAtomicity.push(atomic ?? true);
-
for (const query of queries) {
if (isConditionalQuery({cql: query.query, params: query.params as CassandraParams, kvMeta: query.meta})) {
throw new Error('Conditional writes must use executeConditional to preserve their result');
diff --git a/fluxer_api/src/api/utils/tests/CurrencyUtils.test.ts b/fluxer_api/src/api/utils/tests/CurrencyUtils.test.ts
index a0a7fab7e..d3b236f3b 100644
--- a/fluxer_api/src/api/utils/tests/CurrencyUtils.test.ts
+++ b/fluxer_api/src/api/utils/tests/CurrencyUtils.test.ts
@@ -12,40 +12,6 @@ describe('getCurrencyPreferences first choice', () => {
it.each(['US', 'CA', 'GB', 'JP', 'AU', 'CH'])('returns USD for non-EEA country %s', (country) => {
expect(getCurrencyPreferences(country)[0]).toBe('USD');
});
- describe('handles case insensitivity', () => {
- it('returns EUR for lowercase country code', () => {
- expect(getCurrencyPreferences('de')[0]).toBe('EUR');
- expect(getCurrencyPreferences('fr')[0]).toBe('EUR');
- });
- it('returns USD for lowercase non-EEA', () => {
- expect(getCurrencyPreferences('us')[0]).toBe('USD');
- expect(getCurrencyPreferences('gb')[0]).toBe('USD');
- });
- it('handles mixed case', () => {
- expect(getCurrencyPreferences('De')[0]).toBe('EUR');
- expect(getCurrencyPreferences('dE')[0]).toBe('EUR');
- });
- });
- describe('handles null and undefined', () => {
- it('returns USD for null', () => {
- expect(getCurrencyPreferences(null)[0]).toBe('USD');
- });
- it('returns USD for undefined', () => {
- expect(getCurrencyPreferences(undefined)[0]).toBe('USD');
- });
- });
- describe('handles empty and invalid inputs', () => {
- it('returns USD for empty string', () => {
- expect(getCurrencyPreferences('')[0]).toBe('USD');
- });
- it('returns USD for invalid country code', () => {
- expect(getCurrencyPreferences('XX')[0]).toBe('USD');
- expect(getCurrencyPreferences('ZZ')[0]).toBe('USD');
- });
- it('returns USD for numeric strings', () => {
- expect(getCurrencyPreferences('12')[0]).toBe('USD');
- });
- });
describe('covers all EEA member states', () => {
const eeaCountries = [
'AT',
diff --git a/fluxer_api/src/api/worker/tests/PerMessageJobLedger.test.ts b/fluxer_api/src/api/worker/tests/PerMessageJobLedger.test.ts
index b3988aa28..e5688d76f 100644
--- a/fluxer_api/src/api/worker/tests/PerMessageJobLedger.test.ts
+++ b/fluxer_api/src/api/worker/tests/PerMessageJobLedger.test.ts
@@ -28,34 +28,6 @@ function createOverflowingWorkerService(): RecordingWorkerService {
}
describe('per-message worker jobs', () => {
- it('enqueues handleMentions without a ledger row', async () => {
- const workerService = new RecordingWorkerService();
- const mentionService = new MessageMentionService(
- null as never,
- null as never,
- null as never,
- workerService,
- null as never,
- );
- await mentionService.handleMentionTasks({
- guildId: null,
- message: makeMentionMessage(),
- authorId: createUserID(1n),
- });
- expect(workerService.jobs).toHaveLength(1);
- expect(workerService.jobs[0]!.taskType).toBe('handleMentions');
- expect(workerService.jobs[0]!.options?.skipLedger).toBe(true);
- });
-
- it('enqueues extractEmbeds without a ledger row', async () => {
- const workerService = new RecordingWorkerService();
- const embedService = new EmbedService(null as never, null as never, workerService);
- await embedService.enqueueUrlEmbedExtraction(createChannelID(3n), createMessageID(2n), null, 'block');
- expect(workerService.jobs).toHaveLength(1);
- expect(workerService.jobs[0]!.taskType).toBe('extractEmbeds');
- expect(workerService.jobs[0]!.options?.skipLedger).toBe(true);
- });
-
it('drops mention fanout instead of failing the send when the jobs stream is full', async () => {
const mentionService = new MessageMentionService(
null as never,