A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
test(billing): drop store API token client and config unit tests
Hampus7bf71df83142
diff --git a/fluxer_api/src/api/store_billing/tests/AppStoreServerApiClient.test.ts b/fluxer_api/src/api/store_billing/tests/AppStoreServerApiClient.test.tsindex 51f2075a5..2f180f352 100644--- a/fluxer_api/src/api/store_billing/tests/AppStoreServerApiClient.test.ts+++ b/fluxer_api/src/api/store_billing/tests/AppStoreServerApiClient.test.ts@@ -1,9 +1,5 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import {createPublicKey} from 'node:crypto';-import {mkdtemp, rm, writeFile} from 'node:fs/promises';-import {tmpdir} from 'node:os';-import {join} from 'node:path';import {Config} from '@app/api/Config';import {setInjectedAppleRootCertificates} from '@app/api/store_billing/app_store/AppleRootCertificates';import {AppStoreJwsVerificationError} from '@app/api/store_billing/app_store/AppStoreJwsVerifier';@@ -21,7 +17,6 @@ import {} from '@app/api/test/msw/handlers/AppStoreServerApiHandlers';import {server} from '@app/api/test/msw/server';import {ms} from 'itty-time';-import {decodeJwt, decodeProtectedHeader, jwtVerify} from 'jose';import {delay, HttpResponse, http} from 'msw';import {afterEach, beforeAll, beforeEach, describe, expect, it} from 'vitest';@@ -66,117 +61,6 @@ describe('AppStoreServerApiClient', () => {setInjectedAppleRootCertificates(undefined);});- describe('authentication', () => {- it('signs an ES256 bearer token with the documented claims', async () => {- const authorizations: Array<string> = [];- server.use(- http.get(`${APP_STORE_PRODUCTION_BASE_URL}/inApps/v1/transactions/:id`, ({request}) => {- authorizations.push(request.headers.get('authorization') ?? '');- return HttpResponse.json({errorCode: 4040010, errorMessage: 'not found'}, {status: 404});- }),- );- const client = new AppStoreServerApiClient();- await captureError(- client.getTransactionInfo({environment: 'production', bundleId: 'com.fluxer', transactionId: '1'}),- );- expect(authorizations).toHaveLength(1);- const token = authorizations[0].replace(/^Bearer /, '');- expect(decodeProtectedHeader(token)).toEqual({alg: 'ES256', kid: 'FLUXERTEST', typ: 'JWT'});- const claims = decodeJwt(token);- expect(claims).toMatchObject({- iss: Config.appStore.issuerId,- aud: 'appstoreconnect-v1',- bid: 'com.fluxer',- });- expect((claims.exp ?? 0) - (claims.iat ?? 0)).toBe(3600);- const publicKey = createPublicKey(Config.appStore.privateKey ?? '');- await expect(jwtVerify(token, publicKey, {algorithms: ['ES256']})).resolves.toBeDefined();- });-- it('reuses a token for 50 minutes per bundle', async () => {- let now = Date.parse('2026-09-29T10:00:00Z');- const tokens: Array<string> = [];- server.use(- http.get(`${APP_STORE_PRODUCTION_BASE_URL}/inApps/v1/transactions/:id`, ({request}) => {- tokens.push(request.headers.get('authorization') ?? '');- return HttpResponse.json({errorCode: 4040010}, {status: 404});- }),- );- const client = new AppStoreServerApiClient({now: () => now});- const call = (bundleId: string) =>- captureError(client.getTransactionInfo({environment: 'production', bundleId, transactionId: '1'}));- await call('com.fluxer');- now += ms('49 minutes');- await call('com.fluxer');- await call('com.fluxer.beta');- now += ms('2 minutes');- await call('com.fluxer');- expect(tokens[1]).toBe(tokens[0]);- expect(tokens[2]).not.toBe(tokens[0]);- expect(decodeJwt(tokens[2].replace(/^Bearer /, '')).bid).toBe('com.fluxer.beta');- expect(tokens[3]).not.toBe(tokens[0]);- });-- it('signs a new token when the key id changes', async () => {- seedSubscription(fake, 'production', '100');- const client = new AppStoreServerApiClient();- await client.getTransactionInfo({environment: 'production', bundleId: 'com.fluxer', transactionId: '100'});- Config.appStore.keyId = 'ROTATED';- await expect(- client.getTransactionInfo({environment: 'production', bundleId: 'com.fluxer', transactionId: '100'}),- ).resolves.toMatchObject({environment: 'production'});- expect(fake.requests.map((request) => request.bundleId)).toEqual(['com.fluxer', 'com.fluxer']);- });-- it('surfaces a rejected token as final', async () => {- seedSubscription(fake, 'production', '103');- fake.failNext({}, {status: 401});- const client = new AppStoreServerApiClient();- const error = await captureError(- client.getTransactionInfo({environment: 'production', bundleId: 'com.fluxer', transactionId: '103'}),- );- expect(error).toMatchObject({status: 401, errorCode: null, retryable: false});- });-- it('accepts a private key with escaped newlines', async () => {- seedSubscription(fake, 'production', '101');- Config.appStore.privateKey = (savedAppStore.privateKey ?? '').replaceAll('\n', '\\n');- const client = new AppStoreServerApiClient();- await expect(- client.getTransactionInfo({environment: 'production', bundleId: 'com.fluxer', transactionId: '101'}),- ).resolves.toMatchObject({environment: 'production'});- });-- it('reads the private key from a file', async () => {- seedSubscription(fake, 'production', '102');- const directory = await mkdtemp(join(tmpdir(), 'app-store-key-'));- try {- const path = join(directory, 'AuthKey.p8');- await writeFile(path, savedAppStore.privateKey ?? '');- Config.appStore.privateKey = undefined;- Config.appStore.privateKeyPath = path;- const client = new AppStoreServerApiClient();- await expect(- client.getTransactionInfo({environment: 'production', bundleId: 'com.fluxer', transactionId: '102'}),- ).resolves.toMatchObject({environment: 'production'});- } finally {- await rm(directory, {recursive: true, force: true});- }- });-- it('fails without credentials and makes no request', async () => {- Config.appStore.privateKey = undefined;- Config.appStore.privateKeyPath = undefined;- const client = new AppStoreServerApiClient();- const error = await captureError(- client.getTransactionInfo({environment: 'production', bundleId: 'com.fluxer', transactionId: '1'}),- );- expect(error).toBeInstanceOf(AppStoreServerApiError);- expect((error as AppStoreServerApiError).retryable).toBe(false);- expect(fake.requests).toHaveLength(0);- });- });-describe('environment routing', () => {it('calls only the sandbox host for a sandbox transaction', async () => {seedSubscription(fake, 'sandbox', '200');diff --git a/fluxer_api/src/api/store_billing/tests/GooglePlayAccessTokenProvider.test.ts b/fluxer_api/src/api/store_billing/tests/GooglePlayAccessTokenProvider.test.tsdeleted file mode 100644index 1d064c32f..000000000--- a/fluxer_api/src/api/store_billing/tests/GooglePlayAccessTokenProvider.test.ts+++ /dev/null@@ -1,204 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {generateKeyPairSync} from 'node:crypto';-import {mkdtemp, rm, writeFile} from 'node:fs/promises';-import {tmpdir} from 'node:os';-import path from 'node:path';-import {Config} from '@app/api/Config';-import {- GOOGLE_PLAY_ANDROIDPUBLISHER_SCOPE,- GooglePlayAccessTokenProvider,- resolveGooglePlayCredentials,-} from '@app/api/store_billing/google_play/GooglePlayAccessTokenProvider';-import {GooglePlayApiError} from '@app/api/store_billing/google_play/GooglePlayApiError';-import {- createGooglePlayDeveloperApiHandlers,- type FakeGooglePlayDeveloperApi,-} from '@app/api/test/msw/handlers/GooglePlayDeveloperApiHandlers';-import {server} from '@app/api/test/msw/server';-import {HttpResponse, http} from 'msw';-import {afterEach, beforeEach, describe, expect, it} from 'vitest';--function generateRsaPem(): string {- const {privateKey} = generateKeyPairSync('rsa', {modulusLength: 2048});- return privateKey.export({format: 'pem', type: 'pkcs8'}).toString();-}--describe('GooglePlayAccessTokenProvider', () => {- let fake: FakeGooglePlayDeveloperApi;- let savedGooglePlay: typeof Config.googlePlay;- let tempDir: string | null;-- beforeEach(() => {- savedGooglePlay = {...Config.googlePlay};- tempDir = null;- fake = createGooglePlayDeveloperApiHandlers();- server.use(...fake.handlers);- });-- afterEach(async () => {- Object.assign(Config.googlePlay, savedGooglePlay);- if (tempDir) {- await rm(tempDir, {recursive: true, force: true});- }- });-- async function writeServiceAccountFile(contents: unknown): Promise<string> {- tempDir = await mkdtemp(path.join(tmpdir(), 'fluxer-play-sa-'));- const filePath = path.join(tempDir, 'service-account.json');- await writeFile(filePath, typeof contents === 'string' ? contents : JSON.stringify(contents));- return filePath;- }-- it('exchanges a signed RS256 assertion for an access token', async () => {- const provider = new GooglePlayAccessTokenProvider();- const token = await provider.getAccessToken();- expect(token).toBe('ya29.fake-1');- expect(fake.spies.tokenAssertions).toHaveLength(1);- const [{header, claims}] = fake.spies.tokenAssertions;- expect(header).toEqual({alg: 'RS256', typ: 'JWT'});- expect(claims.iss).toBe(Config.googlePlay.clientEmail);- expect(claims.aud).toBe('https://oauth2.googleapis.com/token');- expect(claims['scope']).toBe(GOOGLE_PLAY_ANDROIDPUBLISHER_SCOPE);- expect((claims.exp ?? 0) - (claims.iat ?? 0)).toBe(3600);- });-- it('reuses the cached token until five minutes before expiry', async () => {- let now = Date.now();- const provider = new GooglePlayAccessTokenProvider({now: () => now});- expect(await provider.getAccessToken()).toBe('ya29.fake-1');- now += 54 * 60 * 1000;- expect(await provider.getAccessToken()).toBe('ya29.fake-1');- now += 60 * 1000 + 1;- expect(await provider.getAccessToken()).toBe('ya29.fake-2');- expect(fake.spies.tokenAssertions).toHaveLength(2);- });-- it('accepts expires_in sent as a string', async () => {- fake.setAccessTokenExpiresIn('600');- let now = Date.now();- const provider = new GooglePlayAccessTokenProvider({now: () => now});- await provider.getAccessToken();- now += 4 * 60 * 1000;- expect(await provider.getAccessToken()).toBe('ya29.fake-1');- now += 60 * 1000 + 1;- expect(await provider.getAccessToken()).toBe('ya29.fake-2');- });-- it('shares one token request between concurrent callers', async () => {- const provider = new GooglePlayAccessTokenProvider();- const tokens = await Promise.all([provider.getAccessToken(), provider.getAccessToken(), provider.getAccessToken()]);- expect(new Set(tokens)).toEqual(new Set(['ya29.fake-1']));- expect(fake.spies.tokenAssertions).toHaveLength(1);- });-- it('fetches a new token after invalidation of the current one', async () => {- const provider = new GooglePlayAccessTokenProvider();- const first = await provider.getAccessToken();- provider.invalidate('ya29.other');- expect(await provider.getAccessToken()).toBe(first);- provider.invalidate(first);- expect(await provider.getAccessToken()).toBe('ya29.fake-2');- });-- it('fetches a new token when the credentials change', async () => {- const provider = new GooglePlayAccessTokenProvider();- await provider.getAccessToken();- const pem = generateRsaPem();- Config.googlePlay.privateKey = pem;- expect(await provider.getAccessToken()).toBe('ya29.fake-2');- });-- it('reads credentials from a service account JSON file', async () => {- const pem = generateRsaPem();- Config.googlePlay.clientEmail = undefined;- Config.googlePlay.privateKey = undefined;- Config.googlePlay.serviceAccountJsonPath = await writeServiceAccountFile({- type: 'service_account',- client_email: '[email protected]',- private_key: pem,- private_key_id: 'abc123',- token_uri: 'https://oauth2.googleapis.com/token',- });- fake.setServiceAccountPrivateKey(pem);- const provider = new GooglePlayAccessTokenProvider();- expect(await provider.getAccessToken()).toBe('ya29.fake-1');- const [{header, claims}] = fake.spies.tokenAssertions;- expect(header['kid']).toBe('abc123');- expect(claims.iss).toBe('[email protected]');- });-- it('prefers explicit config values over the service account file', async () => {- const filePem = generateRsaPem();- Config.googlePlay.serviceAccountJsonPath = await writeServiceAccountFile({- client_email: '[email protected]',- private_key: filePem,- });- const credentials = await resolveGooglePlayCredentials();- expect(credentials.clientEmail).toBe(savedGooglePlay.clientEmail);- expect(credentials.privateKey).toBe(savedGooglePlay.privateKey);- });-- it('uses the token_uri from the service account file when the config keeps the default', async () => {- Config.googlePlay.serviceAccountJsonPath = await writeServiceAccountFile({- token_uri: 'https://oauth2.fluxer.test/token',- });- expect((await resolveGooglePlayCredentials()).tokenUri).toBe('https://oauth2.fluxer.test/token');- Config.googlePlay.tokenUri = 'https://oauth2.override.test/token';- expect((await resolveGooglePlayCredentials()).tokenUri).toBe('https://oauth2.override.test/token');- });-- it('accepts escaped newlines in an inline private key', async () => {- Config.googlePlay.privateKey = savedGooglePlay.privateKey?.replaceAll('\n', '\\n');- const provider = new GooglePlayAccessTokenProvider();- expect(await provider.getAccessToken()).toBe('ya29.fake-1');- });-- it('rejects an unreadable service account file', async () => {- Config.googlePlay.clientEmail = undefined;- Config.googlePlay.privateKey = undefined;- Config.googlePlay.serviceAccountJsonPath = await writeServiceAccountFile('not json');- const provider = new GooglePlayAccessTokenProvider();- await expect(provider.getAccessToken()).rejects.toMatchObject({kind: 'auth', reason: 'invalid_credentials'});- });-- it('rejects when no credentials are configured', async () => {- Config.googlePlay.clientEmail = undefined;- Config.googlePlay.privateKey = undefined;- Config.googlePlay.serviceAccountJsonPath = undefined;- const provider = new GooglePlayAccessTokenProvider();- await expect(provider.getAccessToken()).rejects.toMatchObject({kind: 'auth', reason: 'missing_credentials'});- expect(fake.spies.tokenAssertions).toHaveLength(0);- });-- it('reports a rejected grant as an auth error', async () => {- fake.setServiceAccountPrivateKey(generateRsaPem());- const provider = new GooglePlayAccessTokenProvider();- const error = await provider.getAccessToken().catch((caught: unknown) => caught);- expect(error).toBeInstanceOf(GooglePlayApiError);- expect(error).toMatchObject({kind: 'auth', status: 400, reason: 'invalid_grant'});- });-- it('reports token endpoint outages as retryable and does not cache the failure', async () => {- fake.failNext('token', {status: 503, retryAfter: '7'});- const provider = new GooglePlayAccessTokenProvider();- await expect(provider.getAccessToken()).rejects.toMatchObject({- kind: 'retryable',- status: 503,- retryAfterMs: 7000,- });- expect(await provider.getAccessToken()).toBe('ya29.fake-1');- });-- it('reports a malformed token response as retryable', async () => {- server.use(http.post('https://oauth2.googleapis.com/token', () => HttpResponse.json({token_type: 'Bearer'})));- const provider = new GooglePlayAccessTokenProvider();- await expect(provider.getAccessToken()).rejects.toMatchObject({kind: 'retryable', reason: 'malformed_response'});- });-- it('reports network failures as retryable', async () => {- server.use(http.post('https://oauth2.googleapis.com/token', () => HttpResponse.error()));- const provider = new GooglePlayAccessTokenProvider();- await expect(provider.getAccessToken()).rejects.toMatchObject({kind: 'retryable', reason: 'network_error'});- });-});diff --git a/fluxer_api/src/api/store_billing/tests/StoreBillingConfig.test.ts b/fluxer_api/src/api/store_billing/tests/StoreBillingConfig.test.tsindex 97e133900..c09da1db7 100644--- a/fluxer_api/src/api/store_billing/tests/StoreBillingConfig.test.ts+++ b/fluxer_api/src/api/store_billing/tests/StoreBillingConfig.test.ts@@ -3,37 +3,13 @@import {createUserID} from '@app/api/BrandedTypes';import {Config} from '@app/api/Config';import {- getAppStoreApp,- getAppStoreProductSlot,- getGooglePlayOneTimeProductSlot,- getGooglePlaySubscriptionSlot,isAppStoreConfigured,isGooglePlayConfigured,- isGooglePlayPackageConfigured,- isGooglePlaySubscriptionProduct,isSandboxEntitlementAllowed,- listAppStoreProducts,- listGooglePlayProducts,- STORE_PRODUCT_SLOTS,} from '@app/api/store_billing/StoreBillingConfig';-import {- buildAppStoreStoreKey,- buildGooglePlayStoreKey,- isTerminalStorePurchaseState,-} from '@app/api/store_billing/StoreBillingTypes';+import {isTerminalStorePurchaseState} from '@app/api/store_billing/StoreBillingTypes';import {afterEach, beforeEach, describe, expect, it} from 'vitest';-describe('store product slots', () => {- it('mirrors the Stripe product shapes', () => {- expect(STORE_PRODUCT_SLOTS).toEqual({- monthly: {kind: 'subscription', billingCycle: 'monthly', durationMonths: 1},- yearly: {kind: 'subscription', billingCycle: 'yearly', durationMonths: 12},- gift_1_month: {kind: 'gift', billingCycle: null, durationMonths: 1},- gift_1_year: {kind: 'gift', billingCycle: null, durationMonths: 12},- });- });-});-describe('store billing config', () => {let savedAppStore: typeof Config.appStore;let savedGooglePlay: typeof Config.googlePlay;@@ -84,45 +60,6 @@ describe('store billing config', () => {expect(isAppStoreConfigured()).toBe(false);});- it('accepts Google Play credentials inline or from a service account file', () => {- Config.googlePlay.privateKey = undefined;- expect(isGooglePlayConfigured()).toBe(false);- Config.googlePlay.clientEmail = undefined;- Config.googlePlay.serviceAccountJsonPath = '/etc/fluxer/keys/play.json';- expect(isGooglePlayConfigured()).toBe(true);- Config.googlePlay.packages = [];- expect(isGooglePlayConfigured()).toBe(false);- });-- it('resolves App Store apps and product slots', () => {- expect(getAppStoreApp('com.fluxer')).toEqual({bundleId: 'com.fluxer', appAppleId: 1234567890});- expect(getAppStoreApp('com.other')).toBeNull();- expect(getAppStoreProductSlot('com.fluxer.plutonium.yearly')).toBe('yearly');- expect(getAppStoreProductSlot('com.fluxer.gift.1month')).toBe('gift_1_month');- expect(getAppStoreProductSlot('com.fluxer.unknown')).toBeNull();- expect(getAppStoreProductSlot('toString')).toBeNull();- expect(listAppStoreProducts()).toContainEqual({productId: 'com.fluxer.plutonium.monthly', slot: 'monthly'});- });-- it('resolves Google Play subscriptions by base plan and one-time products by id', () => {- expect(getGooglePlaySubscriptionSlot('plutonium', 'monthly')).toBe('monthly');- expect(getGooglePlaySubscriptionSlot('plutonium', 'weekly')).toBeNull();- expect(getGooglePlaySubscriptionSlot('gift_1_month', '')).toBeNull();- expect(getGooglePlayOneTimeProductSlot('gift_1_year')).toBe('gift_1_year');- expect(getGooglePlayOneTimeProductSlot('plutonium')).toBeNull();- expect(getGooglePlayOneTimeProductSlot('constructor')).toBeNull();- expect(isGooglePlaySubscriptionProduct('plutonium')).toBe(true);- expect(isGooglePlaySubscriptionProduct('gift_1_month')).toBe(false);- expect(isGooglePlayPackageConfigured('com.fluxer')).toBe(true);- expect(isGooglePlayPackageConfigured('com.fluxer.canary')).toBe(false);- expect(listGooglePlayProducts()).toEqual(- expect.arrayContaining([- {productId: 'plutonium', basePlanId: 'yearly', slot: 'yearly'},- {productId: 'gift_1_month', basePlanId: null, slot: 'gift_1_month'},- ]),- );- });-it('entitles sandbox purchases only for allowed users unless every user is allowed', () => {const allowed = createUserID(4242n);const other = createUserID(4343n);@@ -138,11 +75,6 @@ describe('store billing config', () => {});describe('store purchase keys and states', () => {- it('builds store keys per provider and environment', () => {- expect(buildAppStoreStoreKey('sandbox', '2000000000000001')).toBe('app_store:sandbox:2000000000000001');- expect(buildGooglePlayStoreKey('token.abc')).toBe('google_play:token.abc');- });-it('treats only final states as terminal', () => {for (const state of ['expired', 'revoked', 'superseded', 'fulfilled', 'refunded'] as const) {expect(isTerminalStorePurchaseState(state)).toBe(true);diff --git a/fluxer_api/src/api/store_billing/tests/StoreNotificationClaims.test.ts b/fluxer_api/src/api/store_billing/tests/StoreNotificationClaims.test.tsindex f6c088330..f610c0340 100644--- a/fluxer_api/src/api/store_billing/tests/StoreNotificationClaims.test.ts+++ b/fluxer_api/src/api/store_billing/tests/StoreNotificationClaims.test.ts@@ -5,47 +5,11 @@ import {appStoreNotificationClaimKey} from '@app/api/store_billing/StoreNotificaimport {WORKER_LANES} from '@app/api/worker/WorkerLaneConfig';import type {IKVProvider} from '@pkgs/kv_client/src/IKVProvider';import {ms} from 'itty-time';-import {describe, expect, it, vi} from 'vitest';+import {describe, expect, it} from 'vitest';const LIFECYCLE_REDELIVERY_DELAY_MS = ms('5 seconds');describe('StoreNotificationClaims', () => {- it.each([- {options: {}, id: 'app-store-notification:notification', key: 'app-store-notification:notification', ttl: 90},- {- options: {keyPrefix: 'stripe-webhook:', inFlightTtlSeconds: 600},- id: 'evt_1',- key: 'stripe-webhook:evt_1',- ttl: 600,- },- ])('preserves durable claim keys and expiry times for $key', async ({options, id, key, ttl}) => {- let value: string | null = null;- const setnx = vi.fn(async (_key: string, next: string, _ttl?: number) => {- if (value !== null) return false;- value = next;- return true;- });- const get = vi.fn(async (_key: string) => value);- const setex = vi.fn(async (_key: string, _ttl: number, next: string) => {- value = next;- });- const del = vi.fn(async (_key: string) => {- value = null;- return 1;- });- const claims = new KvOnceClaims({setnx, get, setex, del} as unknown as IKVProvider, options);- expect(await claims.tryClaim(id)).toBe('claimed');- expect(setnx).toHaveBeenCalledWith(key, 'in_flight', ttl);- expect(await claims.tryClaim(id)).toBe('in_flight');- expect(get).toHaveBeenCalledWith(key);- await claims.markProcessed(id);- expect(setex).toHaveBeenCalledWith(key, 604800, 'processed');- expect(await claims.tryClaim(id)).toBe('already_processed');- await claims.releaseClaim(id);- expect(del).toHaveBeenCalledWith(key);- expect(await claims.tryClaim(id)).toBe('claimed');- });-it('lets an abandoned claim expire before the lifecycle lane stops redelivering', async () => {const ttls: Array<number> = [];const kv = {