Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add public registration disabled / invite link test case to web app (#2143)
Leendert de Borst329b06f50641
diff --git a/apps/web/tests/e2e/01-registration.spec.ts b/apps/web/tests/e2e/01-registration.spec.tsindex 7b9f986c1..b9c3b65bb 100644--- a/apps/web/tests/e2e/01-registration.spec.ts+++ b/apps/web/tests/e2e/01-registration.spec.ts@@ -2,6 +2,7 @@* Category 1: Full registration setup flow via web app UI (requires API)*/import { test, expect } from '../fixtures';+import { createRegistrationInvite, TEST_DISABLE_PUBLIC_REGISTRATION_HEADER } from '../helpers/test-api';test.describe('1. Registration', () => {test('1.1 should create a new account through the setup wizard', async ({ app, credentials }) => {@@ -42,3 +43,80 @@ test.describe('1. Registration', () => {await expect(page.getByText('No items yet')).toBeVisible();});});++test.describe('1. Registration with public registration disabled', () => {+ test.use({ publicRegistrationEnabled: false });++ test('1.2 should refuse registration without an invite link', async ({ app, apiUrl, credentials }) => {+ const { page } = app;++ await test.step('the start page offers no way to create a vault', async () => {+ await app.openStart();+ await expect(page.getByRole('link', { name: 'Log in with existing account' })).toBeVisible();+ await expect(page.getByRole('link', { name: 'Create new vault' })).toHaveCount(0);+ });++ await test.step('the setup wizard explains registration is disabled without an invite link', async () => {+ await page.goto('/user/setup');+ await expect(page.getByText('User registration is disabled')).toBeVisible();+ await expect(page.getByText('Ask the server administrator for an invite.')).toBeVisible();+ await expect(page.getByRole('button', { name: 'Continue' })).toHaveCount(0);+ });++ await test.step('the API refuses a username check without an invite and accepts one with a valid invite', async () => {+ /**+ * Check the test username as a client of the closed server would.+ */+ const validateUsername = (inviteCode?: string): Promise<Response> => fetch(`${apiUrl}/v2/Auth/validate-username`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', [TEST_DISABLE_PUBLIC_REGISTRATION_HEADER]: 'true' },+ body: JSON.stringify({ username: credentials.username, inviteCode }),+ });+ expect((await validateUsername()).status).toBe(400);+ expect((await validateUsername('AAAA-AAAA-AAAA-AAAA-AAAA')).status).toBe(400);+ expect((await validateUsername(await createRegistrationInvite(apiUrl))).status).toBe(200);+ });+ });++ test('1.3 should create an account through an invite link and use up the invite', async ({ app, apiUrl, credentials }) => {+ const { page } = app;+ const continueButton = page.getByRole('button', { name: 'Continue' });+ const inviteCode = await createRegistrationInvite(apiUrl);++ await test.step('open the invite link', async () => {+ await page.goto(`/user/setup?invite=${encodeURIComponent(inviteCode)}`);+ await page.locator('#agreeTerms').check();+ await continueButton.click();+ });++ await test.step('choose a username, checked against the server with the invite', async () => {+ await page.locator('#username').fill(credentials.username);+ await expect(page.getByText('Username is available')).toBeVisible();+ await continueButton.click();+ });++ await test.step('set the master password and create the account', async () => {+ await page.locator('#password').fill(credentials.password);+ await page.locator('#confirmPassword').fill(credentials.password);+ await page.getByRole('button', { name: 'Create Account' }).click();+ await expect(page).toHaveURL(/\/welcome$/);+ });++ await test.step('the single-use invite is now used up', async () => {+ const response = await fetch(`${apiUrl}/v2/Auth/validate-invite-code`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ inviteCode }),+ });+ expect(response.status).toBe(400);+ });+ });++ test('1.4 should reject an unknown invite link', async ({ app }) => {+ const { page } = app;++ await page.goto('/user/setup?invite=AAAA-AAAA-AAAA-AAAA-AAAA');+ await expect(page.getByText('This invite link is invalid, has expired or has already been used.')).toBeVisible();+ await expect(page.getByRole('button', { name: 'Continue' })).toHaveCount(0);+ });+});diff --git a/apps/web/tests/fixtures/fixtures.ts b/apps/web/tests/fixtures/fixtures.tsindex 808414646..218085436 100644--- a/apps/web/tests/fixtures/fixtures.ts+++ b/apps/web/tests/fixtures/fixtures.ts@@ -1,7 +1,7 @@import { test as base } from '@playwright/test';import { resolveApiUrl } from '../helpers/api-url';-import { createTestUser, generateTestUsername, TEST_PASSWORD, type TestUser } from '../helpers/test-api';+import { createTestUser, generateTestUsername, TEST_DISABLE_PUBLIC_REGISTRATION_HEADER, TEST_PASSWORD, type TestUser } from '../helpers/test-api';import { WebApp } from './WebApp';@@ -18,6 +18,7 @@ export type TestCredentials = {*/type TestFixtures = {apiUrl: string;+ publicRegistrationEnabled: boolean;app: WebApp;credentials: TestCredentials;testUser: TestUser;@@ -32,10 +33,16 @@ type TestFixtures = {export const test = base.extend<TestFixtures>({apiUrl: [resolveApiUrl(), { option: true }],+ /**+ * Set to false with `test.use` to run the test as if registration is closed, in both the web app and (for this test's+ * requests only) the API.+ */+ publicRegistrationEnabled: [true, { option: true }],+/*** The default context, with appsettings.json answered by the test configuration.*/- context: async ({ context, apiUrl }, use) => {+ context: async ({ context, apiUrl, publicRegistrationEnabled }, use) => {await context.route(/\/appsettings(\.Development)?\.json(\?.*)?$/, (route) => route.fulfill({contentType: 'application/json',body: JSON.stringify({@@ -43,10 +50,13 @@ export const test = base.extend<TestFixtures>({PrivateEmailDomains: ['example.tld', 'example2.tld'],HiddenPrivateEmailDomains: [],SupportEmail: '[email protected]',- PublicRegistrationEnabled: 'true',+ PublicRegistrationEnabled: String(publicRegistrationEnabled),DeploymentMode: 'e2e',}),}));+ if (!publicRegistrationEnabled) {+ await context.setExtraHTTPHeaders({ [TEST_DISABLE_PUBLIC_REGISTRATION_HEADER]: 'true' });+ }await use(context);},diff --git a/apps/web/tests/helpers/test-api.ts b/apps/web/tests/helpers/test-api.tsindex 8e610988e..2335b163f 100644--- a/apps/web/tests/helpers/test-api.ts+++ b/apps/web/tests/helpers/test-api.ts@@ -84,6 +84,24 @@ export async function isApiAvailable(apiUrl: string): Promise<boolean> {}}+/**+ * Request header with which the API (DEBUG build in Development) handles that request as if public registration is disabled.+ */+export const TEST_DISABLE_PUBLIC_REGISTRATION_HEADER = 'X-AliasVault-Test-Disable-Public-Registration';++/**+ * Create a registration invite via the DEBUG-only test controller, as the admin panel would.+ * @returns The invite code+ */+export async function createRegistrationInvite(apiUrl: string, maxUses = 1): Promise<string> {+ const url = `${apiUrl}/v2/Test/registration-invites?maxUses=${maxUses}`;+ const response = await fetch(url, { method: 'POST' });+ if (!response.ok) {+ throw new Error(`Failed to create a registration invite via ${url} (status ${response.status}). The test controller only exists in DEBUG builds running with ASPNETCORE_ENVIRONMENT=Development.`);+ }+ return ((await response.json()) as { code: string }).code;+}+/*** Set a server setting via the DEBUG-only test controller.*/diff --git a/core/client/src/auth/SrpLoginService.ts b/core/client/src/auth/SrpLoginService.tsindex cba47e8ab..117d0f923 100644--- a/core/client/src/auth/SrpLoginService.ts+++ b/core/client/src/auth/SrpLoginService.ts@@ -46,12 +46,13 @@ export class SrpLoginService {* holds no vault content yet; the first sync writes the empty vault.* @param username - The username* @param password - The master password+ * @param inviteCode - The registration invite code, required when public registration is disabled* @returns The normalized username, session tokens and key material of the new account* @throws {ApiRequestError} with the server's error code when the server refuses the registration*/- public async register(username: string, password: string): Promise<RegistrationResult> {+ public async register(username: string, password: string, inviteCode?: string): Promise<RegistrationResult> {const prepared = await SrpAuthService.prepareRegistration(username, password);- const token = await this.parseAuthResponse<TokenModel>(await this.post('Auth/register', prepared.request));+ const token = await this.parseAuthResponse<TokenModel>(await this.post('Auth/register', { ...prepared.request, inviteCode }));const { salt, encryptionType, encryptionSettings } = prepared.request;return { username: prepared.request.username, token, keys: prepared.keys, derivedKey: prepared.derivedKey, derivationParams: { salt, encryptionType, encryptionSettings } };}