Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add basic sharing web app test fixture
Leendert de Borst31508f305dde
diff --git a/apps/server/AliasVault.Api/Controllers/Tests/CreateSharedGroupRequest.cs b/apps/server/AliasVault.Api/Controllers/Tests/CreateSharedGroupRequest.csnew file mode 100644index 000000000..be603b679--- /dev/null+++ b/apps/server/AliasVault.Api/Controllers/Tests/CreateSharedGroupRequest.cs@@ -0,0 +1,32 @@+//-----------------------------------------------------------------------+// <copyright file="CreateSharedGroupRequest.cs" company="aliasvault">+// Copyright (c) aliasvault. All rights reserved.+// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.+// </copyright>+//-----------------------------------------------------------------------++namespace AliasVault.Api.Controllers.Tests;++#if DEBUG++/// <summary>+/// Request to create a shared group from the E2E TestController.+/// </summary>+public class CreateSharedGroupRequest+{+ /// <summary>+ /// Gets the group name.+ /// </summary>+ public required string Name { get; init; }++ /// <summary>+ /// Gets the username of the group's owner.+ /// </summary>+ public required string OwnerUsername { get; init; }++ /// <summary>+ /// Gets the usernames added to the group as plain members.+ /// </summary>+ public List<string> MemberUsernames { get; init; } = [];+}+#endifdiff --git a/apps/server/AliasVault.Api/Controllers/Tests/SetCapabilityRequest.cs b/apps/server/AliasVault.Api/Controllers/Tests/SetCapabilityRequest.csnew file mode 100644index 000000000..44693a314--- /dev/null+++ b/apps/server/AliasVault.Api/Controllers/Tests/SetCapabilityRequest.cs@@ -0,0 +1,27 @@+//-----------------------------------------------------------------------+// <copyright file="SetCapabilityRequest.cs" company="aliasvault">+// Copyright (c) aliasvault. All rights reserved.+// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.+// </copyright>+//-----------------------------------------------------------------------++namespace AliasVault.Api.Controllers.Tests;++#if DEBUG++/// <summary>+/// Request to set a capability for one account from the E2E TestController.+/// </summary>+public class SetCapabilityRequest+{+ /// <summary>+ /// Gets the capability key (e.g. "vault-sharing").+ /// </summary>+ public required string Key { get; init; }++ /// <summary>+ /// Gets the value the capability resolves to for the account.+ /// </summary>+ public string Value { get; init; } = "true";+}+#endifdiff --git a/apps/server/AliasVault.Api/Controllers/V2/Tests/TestController.cs b/apps/server/AliasVault.Api/Controllers/V2/Tests/TestController.csindex 452752b79..7ea5b1528 100644--- a/apps/server/AliasVault.Api/Controllers/V2/Tests/TestController.cs+++ b/apps/server/AliasVault.Api/Controllers/V2/Tests/TestController.cs@@ -17,6 +17,8 @@ namespace AliasVault.Api.Controllers.V2.Tests;using AliasServerDb;using AliasVault.Api.Controllers.Abstracts;using AliasVault.Api.Controllers.Tests;+using AliasVault.Api.Helpers;+using AliasVault.Api.Services;using AliasVault.Shared.Server.Services;using Asp.Versioning;using Microsoft.AspNetCore.Authorization;@@ -35,13 +37,15 @@ using Microsoft.EntityFrameworkCore;/// <param name="dbContextFactory">DbContext factory instance.</param>/// <param name="serverSettingsService">ServerSettingsService instance.</param>/// <param name="registrationInviteService">RegistrationInviteService instance.</param>+/// <param name="capabilityService">CapabilityService instance.</param>[ApiVersion("2")]public class TestController(UserManager<AliasVaultUser> userManager,IWebHostEnvironment environment,IAliasServerDbContextFactory dbContextFactory,ServerSettingsService serverSettingsService,- RegistrationInviteService registrationInviteService) : AuthenticatedRequestController(userManager)+ RegistrationInviteService registrationInviteService,+ CapabilityService capabilityService) : AuthenticatedRequestController(userManager){/// <summary>/// Authenticated test request. Used to verify authentication is working.@@ -485,6 +489,105 @@ public class TestController(return Ok(new { code });}+ /// <summary>+ /// Create a shared group with an owner and members.+ /// Only available in DEBUG builds.+ /// </summary>+ /// <param name="request">The group name and the usernames of its owner and members.</param>+ /// <returns>OK with the group id.</returns>+ [AllowAnonymous]+ [HttpPost("shared-groups")]+ public async Task<IActionResult> CreateSharedGroup([FromBody] CreateSharedGroupRequest request)+ {+ if (!environment.IsDevelopment())+ {+ return NotFound();+ }++ await using var context = await dbContextFactory.CreateDbContextAsync();++ var usernames = request.MemberUsernames.Prepend(request.OwnerUsername).Select(u => u.ToUpperInvariant()).ToList();+ var users = await context.AliasVaultUsers.Where(u => usernames.Contains(u.NormalizedUserName!)).ToDictionaryAsync(u => u.NormalizedUserName!, u => u.Id);+ var missing = usernames.Where(u => !users.ContainsKey(u)).ToList();+ if (missing.Count > 0)+ {+ return NotFound($"Users not found: {string.Join(", ", missing)}");+ }++ var now = DateTime.UtcNow;+ var group = new Group { Id = Guid.NewGuid(), Name = request.Name, Type = GroupType.Shared, CreatedAt = now, UpdatedAt = now };+ context.Groups.Add(group);+ context.GroupMembers.Add(GroupHelper.CreateOwnerMembership(group, users[usernames[0]], now));+ foreach (var username in usernames.Skip(1))+ {+ context.GroupMembers.Add(new GroupMember { Id = Guid.NewGuid(), GroupId = group.Id, UserId = users[username], Role = GroupRole.Member, CreatedAt = now, UpdatedAt = now });+ }++ await context.SaveChangesAsync();++ return Ok(new { groupId = group.Id });+ }++ /// <summary>+ /// Set a capability for one account with a per-account rule, and drop the rule cache so it applies right away.+ /// Only available in DEBUG builds.+ /// </summary>+ /// <param name="username">The username of the account.</param>+ /// <param name="request">The capability key and value.</param>+ /// <returns>OK with the key and value.</returns>+ [AllowAnonymous]+ [HttpPost("capabilities/by-username/{username}")]+ public async Task<IActionResult> SetCapabilityByUsername(string username, [FromBody] SetCapabilityRequest request)+ {+ if (!environment.IsDevelopment())+ {+ return NotFound();+ }++ await using var context = await dbContextFactory.CreateDbContextAsync();++ var user = await context.AliasVaultUsers.FirstOrDefaultAsync(u => u.NormalizedUserName == username.ToUpperInvariant());+ if (user == null)+ {+ return NotFound($"User '{username}' not found");+ }++ var now = DateTime.UtcNow;+ context.CapabilityRules.Add(new CapabilityRule+ {+ Id = Guid.NewGuid(),+ CapabilityKey = request.Key,+ UserId = user.Id,+ Value = request.Value,+ Notes = "E2E test",+ CreatedBy = "e2e",+ CreatedAt = now,+ UpdatedAt = now,+ });+ await context.SaveChangesAsync();+ capabilityService.ClearCache();++ return Ok(new { key = request.Key, value = request.Value });+ }++ /// <summary>+ /// Drop the cached capability rules, so rules changed in the database apply on the next request.+ /// Only available in DEBUG builds.+ /// </summary>+ /// <returns>OK.</returns>+ [AllowAnonymous]+ [HttpPost("capabilities/reset-cache")]+ public IActionResult ResetCapabilityCache()+ {+ if (!environment.IsDevelopment())+ {+ return NotFound();+ }++ capabilityService.ClearCache();+ return Ok();+ }+/// <summary>/// Get a server setting by key./// Anonymous endpoint for E2E tests that cannot access auth tokens.diff --git a/apps/server/AliasVault.Api/Services/CapabilityService.cs b/apps/server/AliasVault.Api/Services/CapabilityService.csindex b05ca329b..2e06c5ade 100644--- a/apps/server/AliasVault.Api/Services/CapabilityService.cs+++ b/apps/server/AliasVault.Api/Services/CapabilityService.cs@@ -59,6 +59,14 @@ public class CapabilityService(IAliasServerDbContextFactory dbContextFactory, IMreturn CapabilityValue.IsEnabled(CapabilityResolver.Resolve(rules, subject, capabilityKey, timeProvider.GetUtcNow().UtcDateTime));}+ /// <summary>+ /// Drops the cached rules, so the next call reads them from the database.+ /// </summary>+ public void ClearCache()+ {+ cache.Remove(EnabledRulesCacheKey);+ }+/// <summary>/// Gathers what the caller can be targeted by./// </summary>diff --git a/apps/web/tests/e2e/70-sharing.spec.ts b/apps/web/tests/e2e/70-sharing.spec.tsnew file mode 100644index 000000000..bb9a050bb--- /dev/null+++ b/apps/web/tests/e2e/70-sharing.spec.ts@@ -0,0 +1,76 @@+/**+ * Category 70: Vault sharing between two clients (requires API)+ */+import { test, expect } from '../fixtures';+import { createSharedGroup, createTestUser, enableCapability } from '../helpers/test-api';++test.describe('70. Sharing', () => {+ test('70.1 should show an item created in a shared vault to the invited member', async ({ app: owner, newApp, apiUrl }) => {+ test.slow();+ const vaultName = 'E2E shared vault';+ const itemName = 'Shared item';+ const ownerUser = await createTestUser(apiUrl);+ const memberUser = await createTestUser(apiUrl);+ let groupId = '';+ let manifestId = '';++ await test.step('set up the group and its sharing capability on the server', async () => {+ groupId = await createSharedGroup(apiUrl, 'E2E family', ownerUser.username, [memberUser.username]);+ await enableCapability(apiUrl, ownerUser.username, 'vault-sharing');+ await enableCapability(apiUrl, memberUser.username, 'vault-sharing');+ });++ const member = await newApp();+ await test.step('log in both clients', async () => {+ await owner.login(ownerUser.username, ownerUser.password);+ await member.login(memberUser.username, memberUser.password);+ });++ await test.step('the owner creates a shared vault', async () => {+ await owner.openFamilySharing();+ await owner.page.locator(`#new-vault-name-${groupId}`).fill(vaultName);+ await owner.page.getByRole('button', { name: 'Create', exact: true }).click();+ await expect(owner.page.getByRole('link', { name: vaultName })).toBeVisible();+ await owner.pause();+ });++ await test.step('the owner invites the member', async () => {+ await owner.page.getByRole('listitem').filter({ hasText: memberUser.username }).getByRole('button', { name: 'Invite' }).click();+ await expect(owner.page.getByText(`Invitation sent to ${memberUser.username}.`)).toBeVisible();+ await owner.pause();+ });++ await test.step('the member accepts the invitation', async () => {+ await member.openFamilySharing();+ await member.page.getByRole('button', { name: 'Accept' }).click();+ await expect(member.page.getByRole('link', { name: vaultName })).toBeVisible();+ await member.pause();+ });++ await test.step('the owner creates an item in the shared vault', async () => {+ await owner.page.getByRole('link', { name: vaultName }).click();+ await expect(owner.page).toHaveURL(/\/items\/folder\/[0-9a-f-]{36}\/[0-9a-f-]{36}$/);+ manifestId = owner.page.url().split('/').at(-2) ?? '';+ await owner.createItem(itemName);+ expect(owner.page.url()).toContain(`/items/${manifestId}/`);+ await owner.pause();+ });++ await test.step('the member sees the item after pulling', async () => {+ await member.page.getByRole('link', { name: vaultName }).click();+ await expect(member.page).toHaveURL(new RegExp(`/items/folder/${manifestId}/`));+ await expect(async () => {+ await member.page.getByRole('button', { name: 'Refresh' }).click();+ await expect(member.page.getByText(itemName, { exact: true })).toBeVisible({ timeout: 2000 });+ }).toPass({ timeout: 30000 });+ await member.pause();+ });++ await test.step('the item opens in the shared vault for the member', async () => {+ await member.page.getByText(itemName, { exact: true }).click();+ await member.expectItemView(itemName);+ expect(member.page.url()).toContain(`/items/${manifestId}/`);+ await member.pause();+ });+ });+});diff --git a/apps/web/tests/e2e/90-vault-upgrade.spec.ts b/apps/web/tests/e2e/90-vault-upgrade.spec.tsindex 89a462480..a2b6d9110 100644--- a/apps/web/tests/e2e/90-vault-upgrade.spec.ts+++ b/apps/web/tests/e2e/90-vault-upgrade.spec.ts@@ -10,6 +10,16 @@ import { test, expect, type WebApp } from '../fixtures';import { requireSmtp, sendMail } from '../helpers/smtp';import { readLegacyVaultFixture, restoreLegacyVault, type LegacyVaultFixture, type LegacyVaultItem, type TestUser } from '../helpers/test-api';+/**+ * Log in from the start page to an account whose vault still needs an upgrade, ending on the sync page.+ */+async function loginToUpgradeScreen(app: WebApp, username: string, password: string): Promise<void> {+ await app.openStart();+ await app.page.getByRole('link', { name: 'Log in with existing account' }).click();+ await app.submitLogin(username, password);+ await expect(app.page).toHaveURL(/\/sync$/);+}+/*** Put a legacy vault on the account, log in and run the upgrade steps it needs, ending on the items page.*/@@ -20,10 +30,7 @@ async function upgradeLegacyVault(app: WebApp, apiUrl: string, testUser: TestUseconst startUpgrade = page.getByRole('button', { name: 'Start upgrade process' });await test.step(`log in to the account with the ${version} vault`, async () => {- await app.openStart();- await page.getByRole('link', { name: 'Log in with existing account' }).click();- await app.submitLogin(testUser.username, fixture.password);- await expect(page).toHaveURL(/\/sync$/);+ await loginToUpgradeScreen(app, testUser.username, fixture.password);});// Only a vault from before database version 2.0.0 has to run the legacy database upgrade first.@@ -319,4 +326,64 @@ test.describe('90. Vault upgrades', () => {await expectLegacyVaultContent(app, fixture);});});++ for (const [number, version] of [['90.5', '0.1.0'], ['90.6', '0.30.7']]) {+ test(`${number} should open a ${version} vault that another session upgraded while this one waited on the upgrade screen`, async ({ app, newApp, apiUrl, testUser }) => {+ const fixture = readLegacyVaultFixture(version);+ await restoreLegacyVault(apiUrl, testUser.username, fixture);+ // A separate browser context: a standalone client that shares nothing with the first.+ const other = await newApp();+ const runsLegacyDatabaseUpgrade = Number(String(fixture.vault.version).split('.')[0]) < 2;+ const firstScreenText = runsLegacyDatabaseUpgrade ? 'New available version:' : 'your other AliasVault apps need version';++ await test.step('both sessions log in and wait on the upgrade screen', async () => {+ // One after the other: the server keys the login handshake on the account's SRP identity.+ for (const session of [app, other]) {+ await loginToUpgradeScreen(session, testUser.username, fixture.password);+ await expect(session.page.getByText(firstScreenText)).toBeVisible();+ }+ });++ await test.step('the first session upgrades the vault', async () => {+ await app.pause();+ if (runsLegacyDatabaseUpgrade) {+ await app.page.getByRole('button', { name: 'Start upgrade process' }).click();+ await expect(app.page.getByText('your other AliasVault apps need version')).toBeVisible();+ }+ await app.page.getByRole('button', { name: 'Start upgrade process' }).click();+ await expect(app.page.getByText('Vault upgrade successful.')).toBeVisible();+ await app.page.locator('#upgrade-continue-button').click();+ await app.expectVaultOpen(testUser.username);+ });++ await test.step('the second session starts the upgrade too and takes the upgraded vault', async () => {+ await other.pause();+ await other.page.getByRole('button', { name: 'Start upgrade process' }).click();+ if (!runsLegacyDatabaseUpgrade) {+ // The storage format step ran here as well, so this session confirms it like the first one did.+ await expect(other.page.getByText('Vault upgrade successful.')).toBeVisible();+ await other.page.locator('#upgrade-continue-button').click();+ }+ await other.expectVaultOpen(testUser.username);+ });++ await test.step('both sessions show the vault', async () => {+ for (const session of [app, other]) {+ await session.openVault();+ for (const name of fixture.expectedItemNames) {+ await expect(session.page.getByText(name, { exact: true }).first()).toBeVisible();+ }+ }+ });++ await test.step('the second session can save to the upgraded vault', async () => {+ await other.createItem('Saved by the second session');+ await app.page.reload();+ await app.page.locator('#password').fill(fixture.password);+ await app.page.locator('#unlock-button').click();+ await app.openVault();+ await expect(app.page.getByText('Saved by the second session', { exact: true })).toBeVisible();+ });+ });+ }});diff --git a/apps/web/tests/fixtures/WebApp.ts b/apps/web/tests/fixtures/WebApp.tsindex 4b56339f7..a0f5d6af0 100644--- a/apps/web/tests/fixtures/WebApp.ts+++ b/apps/web/tests/fixtures/WebApp.ts@@ -110,6 +110,15 @@ export class WebApp {await expect(this.page).toHaveURL(/\/items(\?.*)?$/);}+ /**+ * Open the Family Sharing page via the account popover.+ */+ public async openFamilySharing(): Promise<void> {+ await this.page.locator('#userMenuButton').click();+ await this.page.locator('#userMenu').getByRole('link', { name: 'Family Sharing' }).click();+ await expect(this.page).toHaveURL(/\/settings\/family-sharing$/);+ }+/*** Wait until the view page of the item with the given name shows.*/diff --git a/apps/web/tests/fixtures/fixtures.ts b/apps/web/tests/fixtures/fixtures.tsindex af87f3e4b..45a6a936c 100644--- a/apps/web/tests/fixtures/fixtures.ts+++ b/apps/web/tests/fixtures/fixtures.ts@@ -1,4 +1,4 @@-import { test as base } from '@playwright/test';+import { test as base, type BrowserContext } from '@playwright/test';import { resolveApiUrl } from '../helpers/api-url';import { createTestUser, generateTestUsername, TEST_DISABLE_PUBLIC_REGISTRATION_HEADER, TEST_PASSWORD, type TestUser } from '../helpers/test-api';@@ -20,6 +20,7 @@ type TestFixtures = {apiUrl: string;publicRegistrationEnabled: boolean;app: WebApp;+ newApp: () => Promise<WebApp>;credentials: TestCredentials;testUser: TestUser;};@@ -43,21 +44,7 @@ export const test = base.extend<TestFixtures>({* The default context, with appsettings.json answered by the test configuration.*/context: async ({ context, apiUrl, publicRegistrationEnabled }, use) => {- await context.route(/\/appsettings(\.Development)?\.json(\?.*)?$/, (route) => route.fulfill({- contentType: 'application/json',- body: JSON.stringify({- ApiUrl: apiUrl,- PrivateEmailDomains: ['example.tld', 'example2.tld'],- HiddenPrivateEmailDomains: [],- SupportEmail: '[email protected]',- PublicRegistrationEnabled: String(publicRegistrationEnabled),- DeploymentMode: 'e2e',- TermsUrl: 'https://example.tld/terms',- }),- }));- if (!publicRegistrationEnabled) {- await context.setExtraHTTPHeaders({ [TEST_DISABLE_PUBLIC_REGISTRATION_HEADER]: 'true' });- }+ await prepareContext(context, apiUrl, publicRegistrationEnabled);await use(context);},@@ -68,6 +55,20 @@ export const test = base.extend<TestFixtures>({await use(new WebApp(page));},+ /**+ * Open the web app in another browser context, as a second client next to `app`.+ */+ newApp: async ({ browser, baseURL, locale, apiUrl, publicRegistrationEnabled }, use) => {+ const contexts: BrowserContext[] = [];+ await use(async () => {+ const context = await browser.newContext({ baseURL, locale });+ contexts.push(context);+ await prepareContext(context, apiUrl, publicRegistrationEnabled);+ return new WebApp(await context.newPage());+ });+ await Promise.all(contexts.map((context) => context.close()));+ },+/*** Fresh credentials for an account the test registers through the UI.*/@@ -85,3 +86,24 @@ export const test = base.extend<TestFixtures>({});export const expect = test.expect;++/**+ * Answer the app's appsettings.json request with the test configuration.+ */+async function prepareContext(context: BrowserContext, apiUrl: string, publicRegistrationEnabled: boolean): Promise<void> {+ await context.route(/\/appsettings(\.Development)?\.json(\?.*)?$/, (route) => route.fulfill({+ contentType: 'application/json',+ body: JSON.stringify({+ ApiUrl: apiUrl,+ PrivateEmailDomains: ['example.tld', 'example2.tld'],+ HiddenPrivateEmailDomains: [],+ SupportEmail: '[email protected]',+ PublicRegistrationEnabled: String(publicRegistrationEnabled),+ DeploymentMode: 'e2e',+ TermsUrl: 'https://example.tld/terms',+ }),+ }));+ if (!publicRegistrationEnabled) {+ await context.setExtraHTTPHeaders({ [TEST_DISABLE_PUBLIC_REGISTRATION_HEADER]: 'true' });+ }+}diff --git a/apps/web/tests/helpers/test-api.ts b/apps/web/tests/helpers/test-api.tsindex 08574eeb8..baad133f9 100644--- a/apps/web/tests/helpers/test-api.ts+++ b/apps/web/tests/helpers/test-api.ts@@ -187,3 +187,27 @@ export async function postTwoFactorAuth(apiUrl: string, token: string, action: 'body: code === undefined ? undefined : JSON.stringify({ code }),});}++/**+ * Create a shared group with the given owner and members via the DEBUG-only test controller.+ * @returns The group id+ */+export async function createSharedGroup(apiUrl: string, name: string, ownerUsername: string, memberUsernames: string[]): Promise<string> {+ const url = `${apiUrl}/v2/Test/shared-groups`;+ const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name, ownerUsername, memberUsernames }) });+ if (!response.ok) {+ throw new Error(`Creating a shared group via ${url} failed with status ${response.status}: ${await response.text()}`);+ }+ return ((await response.json()) as { groupId: string }).groupId;+}++/**+ * Turn a capability on for one account via the DEBUG-only test controller; the API drops its capability cache so it applies on the next request.+ */+export async function enableCapability(apiUrl: string, username: string, key: string): Promise<void> {+ const url = `${apiUrl}/v2/Test/capabilities/by-username/${encodeURIComponent(username)}`;+ const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key, value: 'true' }) });+ if (!response.ok) {+ throw new Error(`Enabling capability "${key}" via ${url} failed with status ${response.status}: ${await response.text()}`);+ }+}diff --git a/apps/web/tests/run-e2e.mjs b/apps/web/tests/run-e2e.mjsindex 043c3a6d8..9b0eaf630 100644--- a/apps/web/tests/run-e2e.mjs+++ b/apps/web/tests/run-e2e.mjs@@ -12,7 +12,8 @@* Test files are numbered by area, in the same ranges as the browser extension suite, so a range selects one area:* 0x app shell (extension only) 1x account and authentication 2x items* 3x sync and merge (extension) 4x email 5x settings- * 6x browser integration (ext.) 8x vault errors 9x vault upgrades+ * 6x browser integration (ext.) 7x sharing 8x vault errors+ * 9x vault upgrades** Numbers become one title filter (--grep), so selections combine as "or". Any other argument goes to Playwright as-is.*/