A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
test(api): cover verification level limits on actions
Hampusae44c5edf89a
diff --git a/fluxer_api/src/api/user/tests/AccountTierGates.test.ts b/fluxer_api/src/api/user/tests/AccountTierGates.test.tsnew file mode 100644index 000000000..e62dabb64--- /dev/null+++ b/fluxer_api/src/api/user/tests/AccountTierGates.test.ts@@ -0,0 +1,125 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';+import {Config} from '@app/api/Config';+import {getInstanceConfigRepository} from '@app/api/middleware/ServiceSingletons';+import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';+import {createStripeApiHandlers} from '@app/api/test/msw/handlers/StripeApiHandlers';+import {server} from '@app/api/test/msw/server';+import {HTTP_STATUS} from '@app/api/test/TestConstants';+import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';+import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';+import {Headers} from '@fluxer/constants/src/Headers';+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';++const MOCK_PRICES = {+ monthlyUsd: 'price_tier_monthly_usd',+ yearlyUsd: 'price_tier_yearly_usd',+ monthlyBrl: 'price_tier_monthly_brl',+ yearlyBrl: 'price_tier_yearly_brl',+ gift1MonthUsd: 'price_tier_gift_1_month_usd',+ gift1YearUsd: 'price_tier_gift_1_year_usd',+ gift1MonthBrl: 'price_tier_gift_1_month_brl',+ gift1YearBrl: 'price_tier_gift_1_year_brl',+};++interface Registered {+ token: string;+ user_id: string;+}++describe('Tier gates on purchases and joins', () => {+ let harness: ApiTestHarness;+ let originalPrices: typeof Config.stripe.prices | undefined;+ beforeAll(async () => {+ originalPrices = Config.stripe.prices;+ Config.stripe.prices = MOCK_PRICES;+ harness = await createApiTestHarness();+ });+ beforeEach(async () => {+ await harness.reset();+ Config.stripe.prices = MOCK_PRICES;+ server.use(+ ...createStripeApiHandlers({+ prices: {[MOCK_PRICES.monthlyUsd]: {unit_amount: 499, currency: 'usd', interval: 'month'}},+ subscriptionsListEmpty: true,+ }).handlers,+ );+ await getInstanceConfigRepository().updateAccountsConfig({interaction_tier: 'enforced'});+ });+ afterAll(async () => {+ await harness?.shutdown();+ Config.stripe.prices = originalPrices;+ });++ async function createUnclaimed(): Promise<Registered> {+ return await createBuilderWithoutAuth<Registered>(harness)+ .post('/auth/register')+ .body({username: 'shopper', consent: true, date_of_birth: '1995-05-05'})+ .execute();+ }++ async function createInvite(): Promise<string> {+ const owner = await createTestAccount(harness);+ const guild = await createBuilder<{system_channel_id: string}>(harness, owner.token)+ .post('/guilds')+ .body({name: 'Gate Guild'})+ .execute();+ const invite = await createBuilder<{code: string}>(harness, owner.token)+ .post(`/channels/${guild.system_channel_id}/invites`)+ .body({})+ .execute();+ return invite.code;+ }++ it('asks unclaimed and unconfirmed accounts to finish their account before checkout', async () => {+ const unclaimed = await createUnclaimed();+ await createBuilder(harness, unclaimed.token)+ .post('/stripe/checkout/subscription')+ .body({price_id: MOCK_PRICES.monthlyUsd})+ .expect(HTTP_STATUS.FORBIDDEN, APIErrorCodes.UNCLAIMED_ACCOUNT_CANNOT_MAKE_PURCHASES)+ .execute();+ const unverified = await createTestAccount(harness, {skipEmailVerification: true});+ await createBuilder(harness, unverified.token)+ .post('/stripe/checkout/subscription')+ .body({price_id: MOCK_PRICES.monthlyUsd})+ .expect(HTTP_STATUS.FORBIDDEN, APIErrorCodes.PURCHASE_EMAIL_VERIFICATION_REQUIRED)+ .execute();+ });++ it('refuses unclaimed accounts a full join on every client once visits are on', async () => {+ const code = await createInvite();+ const plain = await createUnclaimed();+ await createBuilder(harness, plain.token).post(`/invites/${code}`).body(null).execute();+ await getInstanceConfigRepository().updateGuildVisitsConfig({enabled: true, user_basis_points: 10000});+ const visitor = await createUnclaimed();+ const refused = await createBuilder<{action: string; tier: string}>(harness, visitor.token)+ .post(`/invites/${code}`)+ .header(Headers.X_FLUXER_CAPABILITIES, 'guild_visits')+ .body(null)+ .expect(HTTP_STATUS.FORBIDDEN, APIErrorCodes.ACCOUNT_VERIFICATION_REQUIRED)+ .execute();+ expect(refused).toMatchObject({action: 'guild_join', tier: 'unclaimed'});+ await createBuilder(harness, visitor.token)+ .post(`/invites/${code}`)+ .body(null)+ .expect(HTTP_STATUS.FORBIDDEN, APIErrorCodes.ACCOUNT_VERIFICATION_REQUIRED)+ .execute();+ const member = await createTestAccount(harness);+ await createBuilder(harness, member.token).post(`/invites/${code}`).body(null).execute();+ });++ it('lets older clients join when the instance limits the gate to visits clients', async () => {+ const code = await createInvite();+ await getInstanceConfigRepository().updateGuildVisitsConfig({enabled: true, user_basis_points: 10000});+ await getInstanceConfigRepository().updateAccountsConfig({guild_join_gate: 'visits_capable'});+ const visitor = await createUnclaimed();+ await createBuilder(harness, visitor.token)+ .post(`/invites/${code}`)+ .header(Headers.X_FLUXER_CAPABILITIES, 'guild_visits')+ .body(null)+ .expect(HTTP_STATUS.FORBIDDEN, APIErrorCodes.ACCOUNT_VERIFICATION_REQUIRED)+ .execute();+ await createBuilder(harness, visitor.token).post(`/invites/${code}`).body(null).execute();+ });+});diff --git a/fluxer_api/src/api/user/tests/AccountTierProfileGates.test.ts b/fluxer_api/src/api/user/tests/AccountTierProfileGates.test.tsnew file mode 100644index 000000000..61b66d34b--- /dev/null+++ b/fluxer_api/src/api/user/tests/AccountTierProfileGates.test.ts@@ -0,0 +1,91 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {createTestAccount, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';+import {acceptInvite, createChannelInvite, createGuild} from '@app/api/message/tests/MessageTestUtils';+import {getInstanceConfigRepository} 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 {type InteractionTierMode, InteractionTierModes} from '@fluxer/constants/src/AccountConfigConstants';+import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';+import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';++interface ErrorBody {+ code: string;+ errors?: Array<{path: string; code: string}>;+}++describe('profile and password gates', () => {+ let harness: ApiTestHarness;+ beforeAll(async () => {+ harness = await createApiTestHarness();+ });+ beforeEach(async () => {+ await harness.reset();+ });+ afterAll(async () => {+ await harness?.shutdown();+ });++ async function useInteractionTier(mode: InteractionTierMode): Promise<void> {+ await getInstanceConfigRepository().updateAccountsConfig({interaction_tier: mode});+ }++ async function joinCommunity(member: TestAccount): Promise<string> {+ const owner = await createTestAccount(harness);+ const guild = await createGuild(harness, owner.token, 'Profile Gates');+ const invite = await createChannelInvite(harness, owner.token, guild.system_channel_id!);+ await acceptInvite(harness, member.token, invite.code);+ return guild.id;+ }++ async function profileStatuses(member: TestAccount, guildId: string): Promise<[number, number]> {+ const account = await createBuilder<ErrorBody>(harness, member.token)+ .patch('/users/@me')+ .body({global_name: 'Gate Tester'})+ .executeRaw();+ const community = await createBuilder<ErrorBody>(harness, member.token)+ .patch(`/guilds/${guildId}/members/@me`)+ .body({nick: 'Gate Tester'})+ .executeRaw();+ return [account.response.status, community.response.status];+ }++ it('refuses an unconfirmed email on both profile routes in legacy mode', async () => {+ await useInteractionTier(InteractionTierModes.LEGACY);+ const member = await createTestAccount(harness, {skipEmailVerification: true});+ const guildId = await joinCommunity(member);+ await createBuilder(harness, member.token)+ .patch('/users/@me')+ .body({global_name: 'Gate Tester'})+ .expect(HTTP_STATUS.FORBIDDEN, APIErrorCodes.PROFILE_EMAIL_VERIFICATION_REQUIRED)+ .execute();+ await createBuilder(harness, member.token)+ .patch(`/guilds/${guildId}/members/@me`)+ .body({nick: 'Gate Tester'})+ .expect(HTTP_STATUS.FORBIDDEN, APIErrorCodes.PROFILE_EMAIL_VERIFICATION_REQUIRED)+ .execute();+ });++ it('lets an unconfirmed email edit both profiles under the enforced tier', async () => {+ await useInteractionTier(InteractionTierModes.ENFORCED);+ const member = await createTestAccount(harness, {skipEmailVerification: true});+ const guildId = await joinCommunity(member);+ expect(await profileStatuses(member, guildId)).toEqual([HTTP_STATUS.OK, HTTP_STATUS.OK]);+ });++ it.each([InteractionTierModes.LEGACY, InteractionTierModes.ENFORCED])(+ 'asks for the current password before changing it in %s mode',+ async (mode) => {+ await useInteractionTier(mode);+ const account = await createTestAccount(harness);+ const {json} = await createBuilder<ErrorBody>(harness, account.token)+ .patch('/users/@me')+ .body({new_password: 'An0ther-Str0ng-Passw0rd!'})+ .expect(HTTP_STATUS.BAD_REQUEST)+ .executeWithResponse();+ expect(json.errors?.[0]).toMatchObject({path: 'password', code: ValidationErrorCodes.PASSWORD_NOT_SET});+ },+ );+});diff --git a/fluxer_api/src/api/user/tests/AccountTierServiceGates.test.ts b/fluxer_api/src/api/user/tests/AccountTierServiceGates.test.tsnew file mode 100644index 000000000..dd5b337ec--- /dev/null+++ b/fluxer_api/src/api/user/tests/AccountTierServiceGates.test.ts@@ -0,0 +1,207 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {createAuthSession} from '@app/api/auth/AuthSession';+import {getSudoModeService} from '@app/api/auth/services/SudoModeService';+import {createTotpSecret, totpCodeNow} from '@app/api/auth/tests/AuthTestUtils';+import {createGuildID, createUserID} from '@app/api/BrandedTypes';+import {Config} from '@app/api/Config';+import {createApiContext} from '@app/api/CreateApiContext';+import {EMPTY_USER_ROW, type UserRow} from '@app/api/database/types/UserTypes';+import {setCachedAccountIdentity} from '@app/api/instance/AccountIdentityModeCache';+import {+ hostedAccountsDefaults,+ setCachedAccountsConfig,+ setCachedEmailDeliveryState,+} from '@app/api/instance/AccountsConfigCache';+import {+ getGuildRepository,+ getInstanceConfigRepository,+ getUserRepository,+} from '@app/api/middleware/ServiceSingletons';+import {SUDO_MODE_HEADER} from '@app/api/middleware/SudoModeMiddleware';+import {User} from '@app/api/models/User';+import {assertUserCanPurchase} from '@app/api/stripe/services/StripeCheckoutService';+import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';+import {createBuilder} from '@app/api/test/TestRequestBuilder';+import {EmailDeliveryStates} from '@fluxer/constants/src/AccountConfigConstants';+import {AccountIdentityModes, TagStyles} from '@fluxer/constants/src/AccountIdentityConstants';+import {AdminACLs} from '@fluxer/constants/src/AdminACLs';+import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';+import {HttpStatus} from '@fluxer/constants/src/HttpConstants';+import {UserAuthenticatorTypes, UserFlags} from '@fluxer/constants/src/UserConstants';+import {PurchaseReceiptEmailRequiredError} from '@fluxer/errors/src/domains/user/PurchaseReceiptEmailRequiredError';+import {MfaBackupCodesResponse} from '@fluxer/schema/src/domains/auth/AuthSchemas';+import {ChannelResponse} from '@fluxer/schema/src/domains/channel/ChannelSchemas';+import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it} from 'vitest';++function createUser(overrides: Partial<UserRow> = {}): User {+ return new User({+ ...EMPTY_USER_ROW,+ user_id: createUserID(10n),+ username: 'service_user',+ discriminator: 1,+ bot: false,+ email: '[email protected]',+ email_verified: true,+ password_hash: 'hash',+ traits: new Set<string>(),+ flags: UserFlags.HAS_SESSION_STARTED,+ date_of_birth: types.LocalDate.fromString('1990-01-01'),+ ...overrides,+ });+}++const UNCLAIMED = createUser({email: null, email_verified: false, password_hash: null});+const UNVERIFIED = createUser({email_verified: false});+const VERIFIED = createUser();++const selfHosted = Config.instance.selfHosted;++afterEach(() => {+ setCachedAccountsConfig(null);+ setCachedEmailDeliveryState(null);+ setCachedAccountIdentity(null);+ Config.instance.selfHosted = selfHosted;+});++let harness: ApiTestHarness;+let recipient: User;+let nextUserId = 100n;++async function authenticate(fixture: User): Promise<{user: User; token: string}> {+ const id = createUserID(nextUserId++);+ const user = await getUserRepository().create({+ ...fixture.toRow(),+ user_id: id,+ username: `service_${id}`,+ email: fixture.email === null ? null : `service_${id}@example.com`,+ });+ const [token] = await createAuthSession(createApiContext(), {+ user,+ origin: {ip: '127.0.0.1', userAgent: 'AccountTierServiceGates', clientOs: null},+ });+ return {user, token};+}++beforeAll(async () => {+ harness = await createApiTestHarness();+});++beforeEach(async () => {+ await harness.reset();+ setCachedAccountsConfig({...hostedAccountsDefaults().accounts, interaction_tier: 'legacy'});+ setCachedEmailDeliveryState(EmailDeliveryStates.ON);+ recipient = (await authenticate(VERIFIED)).user;+});++afterAll(async () => {+ await harness.shutdown();+});++describe('account tier service wiring', () => {+ it('requires a confirmed email to open a DM and stores the allowed conversation', async () => {+ const unverified = await authenticate(UNVERIFIED);+ await createBuilder(harness, unverified.token)+ .post('/users/@me/channels')+ .body({recipient_id: recipient.id.toString()})+ .expect(HttpStatus.FORBIDDEN, APIErrorCodes.DIRECT_MESSAGE_EMAIL_VERIFICATION_REQUIRED)+ .execute();+ expect(await getUserRepository().findExistingDmState(unverified.user.id, recipient.id)).toBeNull();+ const verified = await authenticate(VERIFIED);+ const channel = ChannelResponse.parse(+ await createBuilder(harness, verified.token)+ .post('/users/@me/channels')+ .body({recipient_id: recipient.id.toString()})+ .execute(),+ );+ expect((await getUserRepository().findExistingDmState(verified.user.id, recipient.id))?.id.toString()).toBe(+ channel.id,+ );+ });++ it('gates TOTP enrollment before storing the credential and backup codes', async () => {+ const unverified = await authenticate(UNVERIFIED);+ const secret = createTotpSecret();+ const unverifiedSudoToken = await getSudoModeService().generateSudoToken(unverified.user.id);+ await createBuilder(harness, unverified.token)+ .post('/users/@me/mfa/totp/enable')+ .header(SUDO_MODE_HEADER, unverifiedSudoToken)+ .body({secret, code: totpCodeNow(secret)})+ .expect(HttpStatus.FORBIDDEN, APIErrorCodes.MFA_EMAIL_VERIFICATION_REQUIRED)+ .execute();+ expect((await getUserRepository().findUnique(unverified.user.id))?.totpSecret).toBeNull();+ const verified = await authenticate(VERIFIED);+ const verifiedSudoToken = await getSudoModeService().generateSudoToken(verified.user.id);+ const codes = MfaBackupCodesResponse.parse(+ await createBuilder(harness, verified.token)+ .post('/users/@me/mfa/totp/enable')+ .header(SUDO_MODE_HEADER, verifiedSudoToken)+ .body({secret, code: totpCodeNow(secret)})+ .execute(),+ );+ expect(codes.backup_codes).toHaveLength(10);+ const stored = await getUserRepository().findUnique(verified.user.id);+ expect(stored?.totpSecret).toBe(secret);+ expect(stored?.authenticatorTypes.has(UserAuthenticatorTypes.TOTP)).toBe(true);+ });++ it('gates guild creation and stores the allowed community and membership', async () => {+ const unclaimed = await authenticate(UNCLAIMED);+ await createBuilder(harness, unclaimed.token)+ .post('/guilds')+ .body({name: 'Gate'})+ .expect(HttpStatus.FORBIDDEN, APIErrorCodes.UNCLAIMED_ACCOUNT_CANNOT_CREATE_GUILDS)+ .execute();+ const verified = await authenticate(VERIFIED);+ const created = await createBuilder<{id: string; owner_id: string}>(harness, verified.token)+ .post('/guilds')+ .body({name: 'Gate'})+ .execute();+ expect(created.owner_id).toBe(verified.user.id.toString());+ const guildId = createGuildID(BigInt(created.id));+ expect((await getGuildRepository().findUnique(guildId))?.name).toBe('Gate');+ expect((await getGuildRepository().getMember(guildId, verified.user.id))?.userId).toBe(verified.user.id);+ });++ it('refuses the stock community path for an unclaimed owner', async () => {+ await getInstanceConfigRepository().setAppPublicConfig({setup: {configured: false}});+ const admin = await authenticate(+ createUser({+ ...UNCLAIMED.toRow(),+ acls: new Set([AdminACLs.AUTHENTICATE, AdminACLs.INSTANCE_CONFIG_UPDATE]),+ }),+ );+ await createBuilder(harness, admin.token)+ .patch('/admin/instance/config')+ .body({policy: {single_community_enabled: true, single_community_name: 'Stock'}})+ .expect(HttpStatus.FORBIDDEN, APIErrorCodes.UNCLAIMED_ACCOUNT_CANNOT_CREATE_GUILDS)+ .execute();+ expect((await getInstanceConfigRepository().getInstancePolicyConfig()).single_community_guild_id).toBeNull();+ });+});++function operatorPassBlockedReason(user: User): string | null {+ return resolveOperatorPassPurchaseBlockedReason({+ phase: 'standard',+ user,+ removed: false,+ countryStopped: false,+ paymentDisputeOpen: false,+ });+}++describe('purchase eligibility service wiring', () => {+ it('passes account eligibility through to the Operator Pass purchase reason', () => {+ expect(operatorPassBlockedReason(UNCLAIMED)).toBe(PurchaseBlockedReasons.UNCLAIMED);+ expect(operatorPassBlockedReason(VERIFIED)).toBeNull();+ expect(() => assertUserCanPurchase(VERIFIED)).not.toThrow();+ });++ it('requires a receipt address at both purchase entry points on username instances', () => {+ Config.instance.selfHosted = true;+ setCachedAccountIdentity({mode: AccountIdentityModes.USERNAME, tagStyle: TagStyles.NONE});+ setCachedEmailDeliveryState(EmailDeliveryStates.OFF_DISABLED);+ const user = createUser({email: null, email_verified: false});+ expect(() => assertUserCanPurchase(user)).toThrowError(PurchaseReceiptEmailRequiredError);+ });+});