From 10dc1471594d5df3c3cd11d8d0215fc60c33a866 Mon Sep 17 00:00:00 2001 From: James Morton Date: Fri, 20 Nov 2026 00:55:52 +0000 Subject: [PATCH 1/5] test(e2e): people team invitations journeys --- apps/web/e2e/product/people-team.ts | 225 ++++++++++ apps/web/e2e/tests/people/invitations.spec.ts | 423 ++++++++++++++++++ 2 files changed, 648 insertions(+) create mode 100644 apps/web/e2e/product/people-team.ts create mode 100644 apps/web/e2e/tests/people/invitations.spec.ts diff --git a/apps/web/e2e/product/people-team.ts b/apps/web/e2e/product/people-team.ts new file mode 100644 index 0000000000..0577795f9d --- /dev/null +++ b/apps/web/e2e/product/people-team.ts @@ -0,0 +1,225 @@ +/** + * Helpers for the team-access and portal-account specs + * (e2e/tests/people/{members,invitations,roles,team-access,portal-account,unsubscribe}.spec.ts): + * team invitations, role assignments, REST keys and portal users with their + * own sessions. + * + * const admin = await personApi(playwright, 'admin') + * const res = await mustCall(admin, 'addTeamMembersFn', { principalIds: [], emails: [email], role: 'member' }) + * const invite = await invitationFor(email) + * + * Every row a test makes carries its marker; tests never touch the six + * seeded people's roles, sessions or preferences. + */ +import { randomBytes } from 'node:crypto' +import { + expect, + type APIRequestContext, + type Browser, + type BrowserContext, + type PlaywrightWorkerArgs, +} from '@playwright/test' +import { fromUuid, generateId, toUuid } from '@quackback/ids' +import { supportDb } from '../support/db' +import { supportEnv } from '../support/env' +import { apiFor, createKey } from '../support/api-client' +import { callServerFn, type ServerFnResult } from '../support/server-fns' +import { mintCustomer, portalContext, type MintedCustomer } from '../support/widget-portal' + +export { personApi, callServerFn } from '../support/server-fns' + +export function suffix(): string { + return randomBytes(3).toString('hex') +} + +export function uuid(typeId: string): string { + return toUuid(typeId as `principal_${string}`) +} + +/** Call a server function and fail the test when it throws. */ +export async function mustCall( + api: APIRequestContext, + name: string, + data?: unknown, + opts: { sourceFile?: string; method?: 'POST' | 'GET' } = {} +): Promise { + const res = await callServerFn(api, name, data, opts) + expect(res.ok, `${name}: ${res.raw.slice(0, 400)}`).toBe(true) + return res.data +} + +/** Call a server function expecting it to throw; returns the result. */ +export async function refusedCall( + api: APIRequestContext, + name: string, + data?: unknown, + opts: { sourceFile?: string; method?: 'POST' | 'GET' } = {} +): Promise { + const res = await callServerFn(api, name, data, opts) + expect(res.ok, `${name} should be refused: ${res.raw.slice(0, 300)}`).toBe(false) + return res +} + +// --------------------------------------------------------------------------- +// Portal users +// --------------------------------------------------------------------------- + +export interface PortalUser extends MintedCustomer { + context: BrowserContext + api: APIRequestContext +} + +/** A fresh identified portal user with a live session (portal cookie). */ +export async function portalUser( + browser: Browser, + marker: string, + opts: { name?: string; email?: string } = {} +): Promise { + const s = suffix() + const customer = await mintCustomer({ + email: opts.email ?? `${marker}-${s}@customers.example`, + name: opts.name ?? `Person ${marker} ${s}`, + }) + const context = await portalContext(browser, customer) + return { ...customer, context, api: context.request } +} + +/** A portal user row with no session. */ +export async function portalUserRow(marker: string): Promise { + const s = suffix() + return mintCustomer({ + email: `${marker}-${s}@customers.example`, + name: `Person ${marker} ${s}`, + }) +} + +// --------------------------------------------------------------------------- +// Team invitations and roles +// --------------------------------------------------------------------------- + +export interface InvitationRow { + id: string + typeId: string + email: string + role: string | null + role_id: string | null + status: string + expires_at: Date + last_sent_at: Date | null + magic_link_tokens: string[] +} + +/** The newest team invitation to `email`, or null. */ +export async function invitationFor(email: string): Promise { + const [row] = await supportDb()` + SELECT id, email, role, role_id, status, expires_at, last_sent_at, magic_link_tokens + FROM invitation WHERE lower(email) = lower(${email}) AND kind = 'team' + ORDER BY created_at DESC LIMIT 1` + if (!row) return null + return { ...(row as unknown as InvitationRow), typeId: fromUuid('invite', row.id as string) } +} + +/** Invite `email` to the team as the caller (addTeamMembersFn). */ +export async function inviteByEmail( + api: APIRequestContext, + email: string, + opts: { role?: 'admin' | 'member'; roleId?: string } = {} +): Promise { + const res = await mustCall<{ ok: boolean; code?: string; message?: string }>( + api, + 'addTeamMembersFn', + { principalIds: [], emails: [email], role: opts.role ?? 'member', roleId: opts.roleId } + ) + expect(res.ok, JSON.stringify(res)).toBe(true) + const row = await invitationFor(email) + if (!row) throw new Error(`no invitation row for ${email}`) + return row +} + +/** The id of a role by key. */ +export async function roleIdOf(key: string): Promise { + const [row] = await supportDb()`SELECT id FROM roles WHERE key = ${key} LIMIT 1` + if (!row) throw new Error(`no role ${key}`) + return fromUuid('role', row.id as string) +} + +/** A principal's legacy role and its workspace role assignment key (or null). */ +export async function roleOf( + principalId: string +): Promise<{ role: string | null; assigned: string | null }> { + const sql = supportDb() + const [p] = await sql`SELECT role FROM principal WHERE id = ${uuid(principalId)}` + const [a] = await sql`SELECT r.key FROM principal_role_assignments pra + JOIN roles r ON r.id = pra.role_id + WHERE pra.principal_id = ${uuid(principalId)} LIMIT 1` + return { role: (p?.role as string) ?? null, assigned: (a?.key as string) ?? null } +} + +/** A principal row by user email, or null. */ +export async function principalByEmail( + email: string +): Promise<{ id: string; role: string; principalId: string } | null> { + const [row] = await supportDb()` + SELECT p.id, p.role FROM principal p JOIN "user" u ON u.id = p.user_id + WHERE lower(u.email) = lower(${email}) LIMIT 1` + if (!row) return null + return { + id: row.id as string, + role: row.role as string, + principalId: fromUuid('principal', row.id as string), + } +} + +/** A role holding exactly `permissions`, made through the database. Returns { key, id }. */ +export async function customRole( + marker: string, + permissions: readonly string[] +): Promise<{ key: string; id: string; name: string }> { + const sql = supportDb() + const key = `e2e_${randomBytes(5).toString('hex')}` + const name = `Role ${marker} ${suffix()}`.slice(0, 60) + const roleUuid = toUuid(generateId('role')) + const perms = await sql`SELECT id, key FROM permissions WHERE key IN ${sql([...permissions])}` + if (perms.length !== permissions.length) { + throw new Error(`Unknown permission keys in ${permissions.join(', ')}`) + } + await sql.begin(async (tx) => { + await tx`INSERT INTO roles (id, key, name, description, is_system) + VALUES (${roleUuid}, ${key}, ${name}, 'people e2e role', false)` + for (const perm of perms) { + await tx`INSERT INTO role_permissions (id, role_id, permission_id) + VALUES (${toUuid(generateId('role_perm'))}, ${roleUuid}, ${perm.id as string})` + } + }) + return { key, id: fromUuid('role', roleUuid), name } +} + +// --------------------------------------------------------------------------- +// REST +// --------------------------------------------------------------------------- + +/** A REST client with a workspace key holding `roleKey` (default admin). */ +export async function restWorkspace( + playwright: PlaywrightWorkerArgs['playwright'], + roleKey = 'admin' +): Promise { + const { key } = createKey({ + creatorEmail: 'e2e-support-admin@example.com', + kind: 'workspace', + roleKey, + }) + return apiFor(playwright, supportEnv().baseUrl, key) +} + +/** A REST client with a personal key created by `creatorEmail`. */ +export async function restPersonal( + playwright: PlaywrightWorkerArgs['playwright'], + creatorEmail: string +): Promise<{ api: APIRequestContext; keyId: string; key: string }> { + const created = createKey({ creatorEmail, kind: 'personal' }) + return { + api: await apiFor(playwright, supportEnv().baseUrl, created.key), + keyId: created.id, + key: created.key, + } +} diff --git a/apps/web/e2e/tests/people/invitations.spec.ts b/apps/web/e2e/tests/people/invitations.spec.ts new file mode 100644 index 0000000000..baa9cbfc9c --- /dev/null +++ b/apps/web/e2e/tests/people/invitations.spec.ts @@ -0,0 +1,423 @@ +/** + * Team invitations and adding people to the team: invite by email, add a + * portal user, the refusals that come back as values, the grant ceiling, + * accepting an invitation, cancel and resend. + * + * Journeys: PPL-T-09, PPL-T-11, PPL-T-13, PPL-T-14, PPL-T-15, PPL-T-17 (smoke), + * PPL-T-18, PPL-T-20, PPL-T-24, PPL-T-25 + */ +import type { Page } from '@playwright/test' +import { test, expect } from '../../support/fixtures' +import { supportDb } from '../../support/db' +import { linksIn, waitForMail, mailTo } from '../../support/mailpit' +import { + customRole, + invitationFor, + inviteByEmail, + mustCall, + personApi, + portalUser, + portalUserRow, + principalByEmail, + refusedCall, + roleIdOf, + roleOf, + suffix, +} from '../../product/people-team' + +function inviteeEmail(marker: string): string { + return `${marker}-${suffix()}@invitees.example` +} + +/** The "Accept invitation" link in the invitation email. */ +async function acceptLink(email: string): Promise { + const mail = await waitForMail({ to: email, subject: 'invited you to', timeoutMs: 30_000 }) + const link = linksIn(mail).find((l) => /verify|magic|complete-signup|token/i.test(l)) + if (!link) throw new Error(`no accept link in ${linksIn(mail).join(' ')}`) + return link +} + +/** + * Open an emailed invitation link and press the interstitial's "Accept + * invitation" (the link itself never signs in, so mail scanners cannot spend it). + */ +async function followInviteLink(page: Page, link: string): Promise { + await page.goto(link) + await page.getByRole('button', { name: 'Accept invitation' }).click() + await page.waitForURL((url) => !url.pathname.startsWith('/verify-magic-link'), { + timeout: 15_000, + }) +} + +test.describe('accepting an invitation', () => { + test( + 'PPL-T-17 a new person accepts an emailed invitation and lands in the admin', + { tag: '@smoke' }, + async ({ browser, playwright, marker }) => { + const admin = await personApi(playwright, 'admin') + const email = inviteeEmail(marker) + const invite = await inviteByEmail(admin, email) + await admin.dispose() + expect(invite.status).toBe('pending') + + const page = await (await browser.newContext()).newPage() + await followInviteLink(page, await acceptLink(email)) + await expect(page).toHaveURL(new RegExp(`/complete-signup/${invite.typeId}`), { + timeout: 15_000, + }) + await expect(page.getByRole('heading', { name: 'Welcome!' })).toBeVisible() + const name = `Newcomer ${marker}` + await page.getByLabel('Your name').fill(name) + await page.getByLabel(/Set a password/).fill(`pw-${marker}`.slice(0, 30)) + await page.getByRole('button', { name: 'Get started' }).click() + await expect(page).toHaveURL(/\/admin/, { timeout: 15_000 }) + + const after = await invitationFor(email) + expect(after?.status).toBe('accepted') + const principal = await principalByEmail(email) + expect(principal?.role).toBe('member') + const [u] = await supportDb()`SELECT name FROM "user" WHERE lower(email) = ${email}` + expect(u.name).toBe(name) + const [account] = + await supportDb()`SELECT password FROM account a JOIN "user" u ON u.id = a.user_id + WHERE lower(u.email) = ${email} AND a.provider_id = 'credential'` + expect(account?.password, 'the password was set').toBeTruthy() + // Every link of the invitation is revoked. + expect(after!.magic_link_tokens.length).toBeGreaterThan(0) + const live = await supportDb()`SELECT v.identifier FROM verification v, + unnest(${after!.magic_link_tokens}::text[]) t WHERE v.identifier LIKE '%' || t` + expect(live).toHaveLength(0) + await page.context().close() + } + ) + + test( + 'PPL-T-18 an existing portal user accepts and keeps their principal', + { tag: '@core' }, + async ({ browser, playwright, marker }) => { + const person = await portalUser(browser, marker) + const admin = await personApi(playwright, 'admin') + const invite = await inviteByEmail(admin, person.email) + await admin.dispose() + + const page = await person.context.newPage() + await page.goto(`/complete-signup/${invite.typeId}`) + await expect(page.getByRole('heading', { name: 'Welcome!' })).toBeVisible({ + timeout: 15_000, + }) + await expect(page.getByLabel(/Set a password/)).toHaveCount(0) + await page.getByLabel('Your name').fill(person.name) + await page.getByRole('button', { name: 'Get started' }).click() + await expect(page).toHaveURL(/\/admin/, { timeout: 15_000 }) + + const principals = + await supportDb()`SELECT id, role FROM principal WHERE user_id = ${person.userUuid}` + expect(principals).toHaveLength(1) + expect(principals[0].id).toBe(person.principalUuid) + expect(principals[0].role).toBe('member') + expect((await invitationFor(person.email))?.status).toBe('accepted') + } + ) + + test( + 'PPL-T-20 the invitation page refuses a mismatch, a cancelled, an expired and an unknown invite', + { tag: '@core' }, + async ({ browser, playwright, marker }) => { + const admin = await personApi(playwright, 'admin') + const stranger = await portalUser(browser, marker) + const mismatch = await inviteByEmail(admin, inviteeEmail(marker)) + const page = await stranger.context.newPage() + + await page.goto(`/complete-signup/${mismatch.typeId}`) + await expect(page.getByText('Unable to accept invitation')).toBeVisible({ timeout: 15_000 }) + await expect(page.getByText(/sent to a different email address/)).toBeVisible() + + const cancelled = await inviteByEmail(admin, stranger.email) + await mustCall(admin, 'cancelInvitationFn', { invitationId: cancelled.typeId }) + await page.goto(`/complete-signup/${cancelled.typeId}`) + await expect(page.getByText(/This invitation has been cancelled/)).toBeVisible({ + timeout: 15_000, + }) + + const expired = await inviteByEmail(admin, stranger.email) + await supportDb()`UPDATE invitation SET expires_at = now() - interval '1 day' WHERE id = ${expired.id}` + await page.goto(`/complete-signup/${expired.typeId}`) + await expect(page.getByText(/This invitation has expired/)).toBeVisible({ timeout: 15_000 }) + + await page.goto(`/complete-signup/invite_01kaaaaaaaaaaaaaaaaaaaaaaa`) + await expect(page.getByText(/This invitation could not be found/)).toBeVisible({ + timeout: 15_000, + }) + + const [p] = await supportDb()`SELECT role FROM principal WHERE id = ${stranger.principalUuid}` + expect(p.role).toBe('user') + expect((await invitationFor(mismatch.email))?.status).toBe('pending') + await admin.dispose() + } + ) +}) + +test.describe('adding people', () => { + test( + 'PPL-T-09 invite a new address from Members: email, invitation row and Invited row', + { tag: '@core' }, + async ({ asPerson, marker }) => { + const email = inviteeEmail(marker) + const page = await asPerson('admin') + await page.goto('/admin/settings/members') + await page.getByRole('button', { name: 'Add people' }).click() + const dialog = page.getByRole('dialog') + await dialog.getByRole('combobox').first().fill(email) + await page.getByText(`Invite ${email}`).click() + await dialog.getByRole('button', { name: 'Invite 1 person' }).click() + await expect(page.getByText(`Invitation sent to ${email}.`)).toBeVisible() + await expect(dialog).toHaveCount(0) + + const row = await invitationFor(email) + expect(row).toMatchObject({ status: 'pending', role: 'member', role_id: null }) + expect(row!.magic_link_tokens).toHaveLength(1) + const days = (row!.expires_at.getTime() - Date.now()) / 86_400_000 + expect(days).toBeGreaterThan(29) + expect(days).toBeLessThan(31) + + const mail = await waitForMail({ to: email, subject: 'invited you to', timeoutMs: 30_000 }) + expect(mail.Subject).toContain('Ada Admin invited you to') + expect(mail.Text).toContain('Not expecting this? You can ignore this email.') + expect(mail.HTML).toContain('Accept invitation') + + await page + .getByPlaceholder(/Search/) + .first() + .fill(email) + await expect(page.getByRole('table').getByText(email)).toBeVisible() + await expect(page.getByText('Invited', { exact: true }).first()).toBeVisible() + } + ) + + test( + 'PPL-T-11 a signed-in portal user joins the team at once, keeps their content, and is audited', + { tag: '@core' }, + async ({ browser, playwright, marker }) => { + const person = await portalUser(browser, marker) + const admin = await personApi(playwright, 'admin') + const res = await mustCall<{ ok: boolean; added: unknown[]; invited: unknown[] }>( + admin, + 'addTeamMembersFn', + { principalIds: [person.principalId], emails: [], role: 'member' } + ) + expect(res.ok).toBe(true) + expect(res.added).toHaveLength(1) + expect(res.invited).toHaveLength(0) + expect(await roleOf(person.principalId)).toEqual({ role: 'member', assigned: 'manager' }) + expect(await invitationFor(person.email)).toBeNull() + const audit = await supportDb()`SELECT before_value, after_value FROM audit_log + WHERE event_type = 'user.role.changed' AND target_id = ${person.principalId}` + expect(audit).toHaveLength(1) + + // Their next request opens the admin. + const page = await person.context.newPage() + await page.goto('/admin') + await expect(page).toHaveURL(/\/admin/) + await expect(page.getByRole('link', { name: 'Settings' }).first()).toBeVisible({ + timeout: 15_000, + }) + await admin.dispose() + } + ) + + test( + 'PPL-T-13 add refusals come back as values and write nothing', + { tag: '@core' }, + async ({ playwright, people, marker, newTeammate }) => { + const admin = await personApi(playwright, 'admin') + const add = (data: Record) => + mustCall<{ ok: boolean; code?: string; message?: string }>(admin, 'addTeamMembersFn', { + principalIds: [], + emails: [], + role: 'member', + ...data, + }) + + expect(await add({})).toMatchObject({ + ok: false, + code: 'VALIDATION_ERROR', + message: 'Choose at least one person to add', + }) + const twice = inviteeEmail(marker) + expect(await add({ emails: [twice, twice] })).toMatchObject({ + ok: false, + message: `${twice} is listed more than once`, + }) + const neverSignedIn = await portalUserRow(marker) + expect(await add({ principalIds: [neverSignedIn.principalId] })).toMatchObject({ + ok: false, + code: 'NOT_ELIGIBLE', + message: `${neverSignedIn.name} hasn't signed in yet. Invite them by email instead.`, + }) + const mate = await newTeammate({ roleKey: 'contributor' }) + expect(await add({ emails: [mate.email] })).toMatchObject({ + ok: false, + code: 'ALREADY_MEMBER', + message: `${mate.email} is already on the team`, + }) + expect(await add({ principalIds: [people.people.admin.principalId] })).toMatchObject({ + ok: false, + code: 'ALREADY_MEMBER', + message: 'You are already on the team', + }) + const pending = inviteeEmail(marker) + await inviteByEmail(admin, pending) + expect(await add({ emails: [pending] })).toMatchObject({ + ok: false, + code: 'INVITE_PENDING', + message: `${pending} already has a pending invitation`, + }) + const anon = `temp-${suffix()}@anon.quackback.io` + expect(await add({ emails: [anon] })).toMatchObject({ + ok: false, + code: 'NOT_ELIGIBLE', + message: `${anon} cannot receive an invitation`, + }) + + // Nothing was written for any refusal. + for (const email of [twice, mate.email, anon]) { + expect(await invitationFor(email), email).toBeNull() + } + expect((await roleOf(neverSignedIn.principalId)).role).toBe('user') + expect(await mailTo(twice)).toHaveLength(0) + await admin.dispose() + } + ) + + test( + 'PPL-T-14 a member.manage holder cannot grant Admin or a role above their own', + { tag: '@core' }, + async ({ playwright, marker, newTeammate }) => { + const managerRole = await customRole(marker, ['member.view', 'member.manage', 'people.view']) + const caller = await newTeammate({ roleKey: managerRole.key }) + const api = await caller.api(playwright) + const bigger = await customRole(`${marker}-big`, ['member.view', 'settings.manage']) + const add = (data: Record) => + mustCall<{ ok: boolean; code?: string; message?: string }>(api, 'addTeamMembersFn', { + principalIds: [], + emails: [inviteeEmail(marker)], + role: 'member', + ...data, + }) + + expect(await add({ role: 'admin' })).toMatchObject({ + ok: false, + code: 'GRANT_CEILING', + message: 'Only an admin can grant the Admin role', + }) + expect(await add({ roleId: bigger.id })).toMatchObject({ + ok: false, + code: 'GRANT_CEILING', + message: "You can't grant a role with permissions you don't hold: settings.manage", + }) + expect(await add({ role: 'admin', roleId: managerRole.id })).toMatchObject({ + ok: false, + code: 'VALIDATION_ERROR', + message: 'Custom role invites use the member role', + }) + const [{ n }] = await supportDb()`SELECT count(*)::int AS n FROM invitation + WHERE email LIKE ${`${marker}-%@invitees.example`}` + expect(n).toBe(0) + await api.dispose() + } + ) + + test( + 'PPL-T-15 the Owner preset cannot be granted by role id', + { tag: '@core' }, + async ({ browser, playwright, marker }) => { + const admin = await personApi(playwright, 'admin') + const owner = await roleIdOf('owner') + const email = inviteeEmail(marker) + const res = await refusedCall(admin, 'addTeamMembersFn', { + principalIds: [], + emails: [email], + role: 'member', + roleId: owner, + }) + expect(res.error).toContain('Grant Owner by promoting to admin instead') + expect(await invitationFor(email)).toBeNull() + + const person = await portalUser(browser, marker) + await mustCall(admin, 'addTeamMembersFn', { + principalIds: [person.principalId], + emails: [], + role: 'member', + }) + const change = await refusedCall(admin, 'changeTeamRoleFn', { + principalId: person.principalId, + role: 'member', + roleId: owner, + }) + expect(change.error).toContain('Grant Owner by promoting to admin instead') + expect(await roleOf(person.principalId)).toEqual({ role: 'member', assigned: 'manager' }) + await admin.dispose() + } + ) +}) + +test.describe('managing invitations', () => { + test( + 'PPL-T-24 cancelling an invitation revokes every link and a second cancel is not found', + { tag: '@core' }, + async ({ browser, playwright, marker }) => { + const admin = await personApi(playwright, 'admin') + const email = inviteeEmail(marker) + const invite = await inviteByEmail(admin, email) + const firstLink = await acceptLink(email) + await supportDb()`UPDATE invitation SET last_sent_at = now() - interval '10 minutes' WHERE id = ${invite.id}` + await mustCall(admin, 'resendInvitationFn', { invitationId: invite.typeId }) + const tokens = (await invitationFor(email))!.magic_link_tokens + expect(tokens).toHaveLength(2) + + await mustCall(admin, 'cancelInvitationFn', { invitationId: invite.typeId }) + expect((await invitationFor(email))?.status).toBe('canceled') + + // The emailed link no longer signs anyone in. + const page = await (await browser.newContext()).newPage() + await followInviteLink(page, firstLink) + // The revoked link lands on the sign-in error, never the invitation page. + await expect(page.getByRole('heading', { name: 'Welcome!' })).toHaveCount(0) + await expect(page).not.toHaveURL(new RegExp(`/complete-signup/${invite.typeId}$`)) + expect(await principalByEmail(email)).toBeNull() + await page.context().close() + + const again = await refusedCall(admin, 'cancelInvitationFn', { invitationId: invite.typeId }) + expect(again.code).toBe('INVITATION_NOT_FOUND') + await admin.dispose() + } + ) + + test( + 'PPL-T-25 resending sends a second email, renews the expiry and keeps the first link working', + { tag: '@core' }, + async ({ browser, playwright, marker }) => { + const admin = await personApi(playwright, 'admin') + const email = inviteeEmail(marker) + const invite = await inviteByEmail(admin, email) + const firstLink = await acceptLink(email) + await supportDb()`UPDATE invitation SET last_sent_at = now() - interval '10 minutes', + expires_at = now() + interval '3 days' WHERE id = ${invite.id}` + + await mustCall(admin, 'resendInvitationFn', { invitationId: invite.typeId }) + await expect.poll(async () => (await mailTo(email)).length).toBe(2) + const row = (await invitationFor(email))! + expect(row.magic_link_tokens).toHaveLength(2) + expect(Date.now() - row.last_sent_at!.getTime()).toBeLessThan(60_000) + expect((row.expires_at.getTime() - Date.now()) / 86_400_000).toBeGreaterThan(29) + + const page = await (await browser.newContext()).newPage() + await followInviteLink(page, firstLink) + await expect(page.getByRole('heading', { name: 'Welcome!' })).toBeVisible({ + timeout: 15_000, + }) + await page.context().close() + await admin.dispose() + } + ) +}) From e8da818721d168cbb6e7b4d835bbcb0a6ade2826 Mon Sep 17 00:00:00 2001 From: James Morton Date: Fri, 20 Nov 2026 01:22:47 +0000 Subject: [PATCH 2/5] test(e2e): people team roster and role-change journeys --- apps/web/e2e/QUARANTINE.md | 25 + apps/web/e2e/tests/people/invitations.spec.ts | 5 +- apps/web/e2e/tests/people/members.spec.ts | 463 ++++++++++++++++++ 3 files changed, 492 insertions(+), 1 deletion(-) create mode 100644 apps/web/e2e/tests/people/members.spec.ts diff --git a/apps/web/e2e/QUARANTINE.md b/apps/web/e2e/QUARANTINE.md index 88acfc6297..de0f707eaf 100644 --- a/apps/web/e2e/QUARANTINE.md +++ b/apps/web/e2e/QUARANTINE.md @@ -684,3 +684,28 @@ no such part beyond the wrong notification). integrations). Fix: in `updateSegment`, refuse `rules` that are null or have no conditions when `existing.type === 'dynamic'`. owner: unassigned, review by: 2026-12-03. + +### Product suite: people (team access and portal account) + +- `people/members.spec.ts` › changing roles › PPL-T-35 choosing Member for a + custom-role holder moves them to the Manager preset. Product bug: the + change succeeds and is audited, but the workspace assignment keeps the + custom (or Contributor / Support lead) role, so the badge and the + permissions do not change. `updateMemberRole` calls `setPrincipalRole` with + no `assignRoleId` and no `resetAssignment` + (`apps/web/src/lib/server/domains/principals/principal.service.ts:400`), and + the factory reconciles the assignment only when the legacy column moves + (`apps/web/src/lib/server/domains/principals/principal.factory.ts:381`); + member to member never moves. Fix: pass `resetAssignment: true` when the + caller chose `member` with no `roleId`. owner: unassigned, review by: + 2026-12-03. +- `people/members.spec.ts` › REST role changes and removal › PPL-T-48 a + personal key cannot change or remove its own creator. Product bug: the REST + self guards compare the target with the key's own service principal + (`auth.principalId`), not the person the key acts for + (`apps/web/src/routes/api/v1/principals/$principalId.ts:98` and `:151`), so + `CANNOT_MODIFY_SELF` / `CANNOT_REMOVE_SELF` never fire and an owner's + personal key demotes (or removes) the owner; the server functions refuse + the same action (PPL-T-37). Fix: pass the key's creator principal as the + acting principal for personal keys. owner: unassigned, review by: + 2026-12-03. diff --git a/apps/web/e2e/tests/people/invitations.spec.ts b/apps/web/e2e/tests/people/invitations.spec.ts index baa9cbfc9c..a4230b31e7 100644 --- a/apps/web/e2e/tests/people/invitations.spec.ts +++ b/apps/web/e2e/tests/people/invitations.spec.ts @@ -165,8 +165,11 @@ test.describe('adding people', () => { const email = inviteeEmail(marker) const page = await asPerson('admin') await page.goto('/admin/settings/members') - await page.getByRole('button', { name: 'Add people' }).click() const dialog = page.getByRole('dialog') + await expect(async () => { + await page.getByRole('button', { name: 'Add people' }).click() + await expect(dialog).toBeVisible({ timeout: 1_000 }) + }).toPass({ timeout: 15_000 }) await dialog.getByRole('combobox').first().fill(email) await page.getByText(`Invite ${email}`).click() await dialog.getByRole('button', { name: 'Invite 1 person' }).click() diff --git a/apps/web/e2e/tests/people/members.spec.ts b/apps/web/e2e/tests/people/members.spec.ts new file mode 100644 index 0000000000..1d2590aec7 --- /dev/null +++ b/apps/web/e2e/tests/people/members.spec.ts @@ -0,0 +1,463 @@ +/** + * The team roster (/admin/settings/members) and what changes a teammate's + * role or membership: the members menu, the server functions behind it and + * REST /api/v1/principals, with personal keys capped by their creator. + * + * Journeys: PPL-T-01, PPL-T-07, PPL-T-33, PPL-T-34, PPL-T-35, PPL-T-37, + * PPL-T-39, PPL-T-41, PPL-T-42, PPL-T-44, PPL-T-46, PPL-T-47, PPL-T-48, + * PPL-T-50 + */ +import type { Page } from '@playwright/test' +import { test, expect } from '../../support/fixtures' +import { supportDb } from '../../support/db' +import { apiFor, expectJson } from '../../support/api-client' +import { supportEnv } from '../../support/env' +import { mintSession } from '../../support/teammates' +import { + customRole, + inviteByEmail, + mustCall, + personApi, + portalUserRow, + refusedCall, + restPersonal, + restWorkspace, + roleOf, + suffix, + uuid, +} from '../../product/people-team' + +/** audit_log rows of one event for one target. */ +async function auditRows(eventType: string, targetId: string) { + return supportDb()`SELECT actor_type, before_value, after_value, metadata FROM audit_log + WHERE event_type = ${eventType} AND target_id = ${targetId} ORDER BY occurred_at` +} + +/** Open a roster row's actions menu (retried until the page has hydrated). */ +async function openMemberMenu(page: Page, name: string): Promise { + await expect(async () => { + await page.getByRole('button', { name: `Actions for ${name}` }).click() + await expect(page.getByRole('menuitem', { name: 'Remove from team' })).toBeVisible({ + timeout: 1_000, + }) + }).toPass({ timeout: 15_000 }) +} + +test.describe('the roster', () => { + test( + 'PPL-T-01 Members lists teammates with their role badge, pending invites, and no portal users', + { tag: '@core' }, + async ({ asPerson, playwright, marker, newTeammate }) => { + const contributor = await newTeammate({ roleKey: 'contributor', name: `Cora ${marker}` }) + const quiet = await newTeammate({ roleKey: 'manager', name: `Quiet ${marker}` }) + await supportDb()`DELETE FROM session WHERE user_id = ${uuid(quiet.userId)}` + const portal = await portalUserRow(marker) + const admin = await personApi(playwright, 'admin') + const invitee = `${marker}-${suffix()}@invitees.example` + await inviteByEmail(admin, invitee) + await admin.dispose() + + const page = await asPerson('admin') + await page.goto(`/admin/settings/members?q=${encodeURIComponent(marker)}`) + await expect(page.getByRole('heading', { name: 'Members & Teams' })).toBeVisible({ + timeout: 15_000, + }) + await expect(page.getByText('Who has access to your workspace.')).toBeVisible() + const table = page.getByRole('table') + const coraRow = table.getByRole('row').filter({ hasText: contributor.email }) + await expect(coraRow).toContainText('Contributor') + const quietRow = table.getByRole('row').filter({ hasText: quiet.email }) + await expect(quietRow).toContainText('Never') + const inviteRow = table.getByRole('row').filter({ hasText: invitee }) + await expect(inviteRow).toContainText('Invited') + await expect(inviteRow).toContainText(/Expires in/) + await expect(table.getByText(portal.email)).toHaveCount(0) + } + ) + + test( + 'PPL-T-07 REST lists teammates at /principals and /members, and needs member.view', + { tag: '@core' }, + async ({ playwright, marker, newTeammate }) => { + const mate = await newTeammate({ roleKey: 'contributor', name: `Mate ${marker}` }) + const portal = await portalUserRow(marker) + const rest = await restWorkspace(playwright) + const principals = await expectJson(await rest.get('/api/v1/principals'), 200) + const members = await expectJson(await rest.get('/api/v1/members'), 200) + const ids = (body: { data: Array<{ id: string }> }) => body.data.map((m) => m.id) + expect(ids(principals)).toContain(mate.principalId) + expect(ids(principals)).not.toContain(portal.principalId) + expect(ids(members)).toContain(mate.principalId) + expect(ids(members)).not.toContain(portal.principalId) + const row = principals.data.find((m: { id: string }) => m.id === mate.principalId) + expect(row).toMatchObject({ userId: mate.userId, email: mate.email, role: 'member' }) + expect(members.data.find((m: { id: string }) => m.id === mate.principalId)).toEqual(row) + await rest.dispose() + + const anonymous = await apiFor(playwright, supportEnv().baseUrl, null) + expect((await anonymous.get('/api/v1/principals')).status()).toBe(401) + await anonymous.dispose() + const noView = await customRole(marker, ['post.view_private']) + const narrow = await restWorkspace(playwright, noView.key) + const refused = await expectJson(await narrow.get('/api/v1/principals'), 403) + expect(refused.error.code).toBe('FORBIDDEN') + expect(refused.error.message).toBe("Requires the 'member.view' permission") + await narrow.dispose() + } + ) +}) + +test.describe('changing roles', () => { + test( + 'PPL-T-33 the owner makes a teammate Admin from the members menu', + { tag: '@core' }, + async ({ asPerson, marker, newTeammate }) => { + const mate = await newTeammate({ roleKey: 'manager', name: `Promo ${marker}` }) + const page = await asPerson('admin') + await page.goto(`/admin/settings/members?q=${encodeURIComponent(marker)}`) + await openMemberMenu(page, mate.name) + await page.getByRole('menuitem', { name: 'Admin' }).click() + const dialog = page.getByRole('alertdialog') + await expect(dialog).toContainText('Change role to Admin?') + await expect(dialog).toContainText( + `${mate.name} will be able to manage team settings, members, and all workspace configurations.` + ) + await dialog.getByRole('button', { name: 'Change to Admin' }).click() + await expect(dialog).toHaveCount(0) + + await expect.poll(async () => (await roleOf(mate.principalId)).role).toBe('admin') + expect((await roleOf(mate.principalId)).assigned).toBe('owner') + const audit = await auditRows('user.role.changed', mate.principalId) + expect(audit).toHaveLength(1) + await expect( + page.getByRole('table').getByRole('row').filter({ hasText: mate.email }) + ).toContainText(/Owner|Admin/) + } + ) + + test( + 'PPL-T-34 the owner gives a teammate a custom role; its permissions apply on the next request', + { tag: '@core' }, + async ({ asPerson, browser, marker, newTeammate }) => { + const role = await customRole(marker, ['member.view']) + const mate = await newTeammate({ roleKey: 'manager', name: `Custom ${marker}` }) + const page = await asPerson('admin') + await page.goto(`/admin/settings/members?q=${encodeURIComponent(marker)}`) + await openMemberMenu(page, mate.name) + await page.getByRole('menuitem', { name: role.name }).click() + const dialog = page.getByRole('alertdialog') + await expect(dialog).toContainText( + `${mate.name} will hold the "${role.name}" role and exactly the permissions it grants.` + ) + await dialog.getByRole('button', { name: `Change to ${role.name}` }).click() + await expect.poll(async () => (await roleOf(mate.principalId)).assigned).toBe(role.key) + expect((await roleOf(mate.principalId)).role).toBe('member') + const [grant] = + await supportDb()`SELECT granted_by_principal_id FROM principal_role_assignments + WHERE principal_id = ${uuid(mate.principalId)}` + expect(grant.granted_by_principal_id).not.toBeNull() + await expect( + page.getByRole('table').getByRole('row').filter({ hasText: mate.email }) + ).toContainText(role.name) + + // Without post.view_private the feedback inbox is the no-access page. + const theirs = await mate.newPage(browser) + await theirs.goto('/admin/feedback') + await expect(theirs.getByText(/You don.t have access/)).toBeVisible({ timeout: 15_000 }) + } + ) + + test( + 'PPL-T-35 choosing Member for a custom-role holder moves them to the Manager preset', + { + tag: ['@core', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'Member with no roleId keeps the custom assignment (principal.service.ts updateMemberRole, principal.factory.ts setMemberRole); see QUARANTINE.md', + }, + }, + async ({ playwright, marker, newTeammate }) => { + const role = await customRole(marker, ['member.view']) + const mate = await newTeammate({ roleKey: role.key }) + const admin = await personApi(playwright, 'admin') + const res = await mustCall<{ ok: boolean }>(admin, 'changeTeamRoleFn', { + principalId: mate.principalId, + role: 'member', + }) + expect(res.ok).toBe(true) + expect(await roleOf(mate.principalId)).toEqual({ role: 'member', assigned: 'manager' }) + await admin.dispose() + } + ) + + test( + 'PPL-T-37 nobody can change or remove themselves', + { tag: '@core' }, + async ({ playwright, newTeammate }) => { + const me = await newTeammate({ roleKey: 'admin' }) + const api = await me.api(playwright) + const change = await mustCall<{ ok: boolean; code?: string }>(api, 'changeTeamRoleFn', { + principalId: me.principalId, + role: 'member', + }) + expect(change).toMatchObject({ ok: false, code: 'CANNOT_MODIFY_SELF' }) + const update = await refusedCall(api, 'updateMemberRoleFn', { + principalId: me.principalId, + role: 'member', + }) + expect(update.code).toBe('CANNOT_MODIFY_SELF') + const remove = await refusedCall(api, 'removeTeamMemberFn', { principalId: me.principalId }) + expect(remove.code).toBe('CANNOT_REMOVE_SELF') + expect(await roleOf(me.principalId)).toEqual({ role: 'admin', assigned: 'admin' }) + expect(await auditRows('user.role.changed', me.principalId)).toHaveLength(0) + await api.dispose() + } + ) + + test( + 'PPL-T-39 a member.manage holder cannot grant Admin, touch an admin, or grant above themselves', + { tag: '@core' }, + async ({ playwright, marker, newTeammate }) => { + const managerRole = await customRole(marker, ['member.view', 'member.manage']) + const caller = await newTeammate({ roleKey: managerRole.key }) + const target = await newTeammate({ roleKey: 'contributor' }) + const anAdmin = await newTeammate({ roleKey: 'admin' }) + const bigger = await customRole(`${marker}-big`, ['member.view', 'settings.manage']) + const api = await caller.api(playwright) + + const promote = await refusedCall(api, 'updateMemberRoleFn', { + principalId: target.principalId, + role: 'admin', + }) + expect(promote.code).toBe('GRANT_CEILING') + expect(promote.error).toContain('Only an admin can grant the Admin role') + const demote = await refusedCall(api, 'updateMemberRoleFn', { + principalId: anAdmin.principalId, + role: 'member', + }) + expect(demote.error).toContain('Only an admin can change or remove an admin') + const remove = await refusedCall(api, 'removeTeamMemberFn', { + principalId: anAdmin.principalId, + }) + expect(remove.error).toContain('Only an admin can change or remove an admin') + const richer = await refusedCall(api, 'updateMemberRoleFn', { + principalId: target.principalId, + role: 'member', + roleId: bigger.id, + }) + expect(richer.error).toContain( + "You can't grant a role with permissions you don't hold: settings.manage" + ) + expect(await roleOf(target.principalId)).toEqual({ role: 'member', assigned: 'contributor' }) + expect((await roleOf(anAdmin.principalId)).role).toBe('admin') + await api.dispose() + } + ) +}) + +test.describe('removing teammates and their sessions', () => { + test( + 'PPL-T-41 removing a teammate makes them a portal user and revokes their personal keys', + { tag: '@core' }, + async ({ asPerson, browser, playwright, marker, newTeammate }) => { + const mate = await newTeammate({ roleKey: 'manager', name: `Leaver ${marker}` }) + const personal = await restPersonal(playwright, mate.email) + const page = await asPerson('admin') + await page.goto(`/admin/settings/members?q=${encodeURIComponent(marker)}`) + await openMemberMenu(page, mate.name) + await page.getByRole('menuitem', { name: 'Remove from team' }).click() + const dialog = page.getByRole('alertdialog') + await expect(dialog).toContainText('Remove team member?') + await expect(dialog).toContainText( + `${mate.name} will be removed from the team and converted to a portal user.` + ) + await dialog.getByRole('button', { name: 'Remove from team' }).click() + await expect(dialog).toHaveCount(0) + await expect(page.getByRole('table').getByText(mate.email)).toHaveCount(0) + + await expect.poll(() => roleOf(mate.principalId)).toEqual({ role: 'user', assigned: null }) + const [key] = + await supportDb()`SELECT revoked_at FROM api_keys WHERE id = ${uuid(personal.keyId)}` + expect(key.revoked_at).not.toBeNull() + expect(await auditRows('user.removed', mate.principalId)).toHaveLength(1) + // The session survives; the admin turns them away. + const theirs = await mate.newPage(browser) + await theirs.goto('/admin') + await expect(theirs).toHaveURL(/error=not_team_member/, { timeout: 15_000 }) + await personal.api.dispose() + } + ) + + test( + 'PPL-T-42 a removed teammate personal key stops working at once and stays revoked', + { tag: '@core' }, + async ({ playwright, newTeammate }) => { + const mate = await newTeammate({ roleKey: 'manager' }) + const personal = await restPersonal(playwright, mate.email) + await expectJson(await personal.api.get('/api/v1/principals'), 200) + const admin = await personApi(playwright, 'admin') + await mustCall(admin, 'removeTeamMemberFn', { principalId: mate.principalId }) + expect((await personal.api.get('/api/v1/principals')).status()).toBe(401) + + await mustCall(admin, 'updateMemberRoleFn', { principalId: mate.principalId, role: 'member' }) + expect((await roleOf(mate.principalId)).role).toBe('member') + expect((await personal.api.get('/api/v1/principals')).status()).toBe(401) + await personal.api.dispose() + await admin.dispose() + } + ) + + test( + 'PPL-T-44 sign out everywhere ends every session of the teammate and is audited', + { tag: '@core' }, + async ({ asPerson, marker, newTeammate }) => { + const mate = await newTeammate({ roleKey: 'manager', name: `Signout ${marker}` }) + await mintSession(mate.userId) + const page = await asPerson('admin') + await page.goto(`/admin/settings/members?q=${encodeURIComponent(marker)}`) + await openMemberMenu(page, mate.name) + await page.getByRole('menuitem', { name: 'Sign out everywhere' }).click() + const dialog = page.getByRole('alertdialog') + await expect(dialog).toContainText('Sign out everywhere?') + await dialog.getByRole('button', { name: 'Sign out everywhere' }).click() + await expect(page.getByText(`Signed ${mate.name} out of 2 sessions.`)).toBeVisible() + + const sessions = + await supportDb()`SELECT id FROM session WHERE user_id = ${uuid(mate.userId)}` + expect(sessions).toHaveLength(0) + const audit = await auditRows('session.revoked.individual', mate.userId) + expect(audit).toHaveLength(1) + expect(audit[0].metadata).toMatchObject({ count: 2, reason: 'admin_forced' }) + expect((await roleOf(mate.principalId)).role).toBe('member') + } + ) +}) + +test.describe('REST role changes and removal', () => { + test( + 'PPL-T-46 REST changes a teammate role, validates the body, and needs member.manage', + { tag: '@core' }, + async ({ playwright, marker, newTeammate }) => { + const mate = await newTeammate({ roleKey: 'manager' }) + const role = await customRole(marker, ['member.view']) + const rest = await restWorkspace(playwright, 'owner') + + const toAdmin = await expectJson( + await rest.patch(`/api/v1/principals/${mate.principalId}`, { data: { role: 'admin' } }), + 200 + ) + expect(toAdmin.data.role).toBe('admin') + expect(await roleOf(mate.principalId)).toEqual({ role: 'admin', assigned: 'owner' }) + const audit = await auditRows('user.role.changed', mate.principalId) + expect(audit.at(-1)?.actor_type).toBe('api_key') + + await expectJson( + await rest.patch(`/api/v1/principals/${mate.principalId}`, { + data: { role: 'member', roleId: role.id }, + }), + 200 + ) + expect(await roleOf(mate.principalId)).toEqual({ role: 'member', assigned: role.key }) + + const bad = await expectJson( + await rest.patch(`/api/v1/principals/${mate.principalId}`, { data: { role: 'boss' } }), + 400 + ) + expect(bad.error.code).toBe('BAD_REQUEST') + await rest.dispose() + + const viewOnly = await customRole(`${marker}-v`, ['member.view']) + const narrow = await restWorkspace(playwright, viewOnly.key) + const refused = await expectJson( + await narrow.patch(`/api/v1/principals/${mate.principalId}`, { data: { role: 'admin' } }), + 403 + ) + expect(refused.error.message).toBe("Requires the 'member.manage' permission") + expect((await roleOf(mate.principalId)).role).toBe('member') + await narrow.dispose() + } + ) + + test( + 'PPL-T-46 a body that is not JSON is refused as a bad request', + { tag: '@core' }, + async ({ playwright, newTeammate }) => { + const mate = await newTeammate({ roleKey: 'manager' }) + const rest = await restWorkspace(playwright, 'owner') + const res = await rest.patch(`/api/v1/principals/${mate.principalId}`, { + headers: { 'content-type': 'application/json' }, + data: '{not json', + }) + expect(res.status(), await res.text()).toBe(400) + expect((await roleOf(mate.principalId)).role).toBe('member') + await rest.dispose() + } + ) + + test( + 'PPL-T-47 REST removes a teammate, then the repeat is not found', + { tag: '@core' }, + async ({ playwright, newTeammate }) => { + const mate = await newTeammate({ roleKey: 'manager' }) + const rest = await restWorkspace(playwright) + const res = await rest.delete(`/api/v1/principals/${mate.principalId}`) + expect(res.status(), await res.text()).toBe(204) + expect((await roleOf(mate.principalId)).role).toBe('user') + const again = await expectJson(await rest.delete(`/api/v1/members/${mate.principalId}`), 404) + expect(again.error).toMatchObject({ code: 'NOT_FOUND', message: 'Member not found' }) + await rest.dispose() + } + ) + + test( + 'PPL-T-48 a personal key cannot change or remove its own creator', + { + tag: ['@core', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'REST self guards compare the target with the key service principal, not its creator (api/v1/principals/$principalId.ts); see QUARANTINE.md', + }, + }, + async ({ playwright, newTeammate }) => { + const owner = await newTeammate({ roleKey: 'admin' }) + const personal = await restPersonal(playwright, owner.email) + const change = await personal.api.patch(`/api/v1/principals/${owner.principalId}`, { + data: { role: 'member' }, + }) + expect(change.status(), await change.text()).toBe(403) + const remove = await personal.api.delete(`/api/v1/principals/${owner.principalId}`) + expect(remove.status(), await remove.text()).toBe(403) + expect((await roleOf(owner.principalId)).role).toBe('admin') + await personal.api.dispose() + } + ) + + test( + 'PPL-T-50 a personal key loses what its creator loses', + { tag: '@core' }, + async ({ playwright, marker, newTeammate }) => { + const owner = await newTeammate({ roleKey: 'admin' }) + const personal = await restPersonal(playwright, owner.email) + await expectJson(await personal.api.get('/api/v1/users?limit=1'), 200) + + const narrow = await customRole(marker, ['member.view']) + const admin = await personApi(playwright, 'admin') + await mustCall(admin, 'updateMemberRoleFn', { + principalId: owner.principalId, + role: 'member', + roleId: narrow.id, + }) + await admin.dispose() + + const refused = await expectJson(await personal.api.get('/api/v1/users?limit=1'), 403) + expect(refused.error).toMatchObject({ + code: 'FORBIDDEN', + message: "Requires the 'people.view' permission", + }) + await expectJson(await personal.api.get('/api/v1/principals'), 200) + await personal.api.dispose() + } + ) +}) From 7c8a9f9119219e6fbeed848654d928ab9860c8b2 Mon Sep 17 00:00:00 2001 From: James Morton Date: Fri, 20 Nov 2026 01:34:33 +0000 Subject: [PATCH 3/5] test(e2e): people roles journeys --- apps/web/e2e/tests/people/members.spec.ts | 4 +- apps/web/e2e/tests/people/roles.spec.ts | 250 ++++++++++++++++++++++ 2 files changed, 252 insertions(+), 2 deletions(-) create mode 100644 apps/web/e2e/tests/people/roles.spec.ts diff --git a/apps/web/e2e/tests/people/members.spec.ts b/apps/web/e2e/tests/people/members.spec.ts index 1d2590aec7..39783e2ab3 100644 --- a/apps/web/e2e/tests/people/members.spec.ts +++ b/apps/web/e2e/tests/people/members.spec.ts @@ -116,7 +116,7 @@ test.describe('changing roles', () => { const page = await asPerson('admin') await page.goto(`/admin/settings/members?q=${encodeURIComponent(marker)}`) await openMemberMenu(page, mate.name) - await page.getByRole('menuitem', { name: 'Admin' }).click() + await page.getByRole('menuitem', { name: 'Admin', exact: true }).click() const dialog = page.getByRole('alertdialog') await expect(dialog).toContainText('Change role to Admin?') await expect(dialog).toContainText( @@ -144,7 +144,7 @@ test.describe('changing roles', () => { const page = await asPerson('admin') await page.goto(`/admin/settings/members?q=${encodeURIComponent(marker)}`) await openMemberMenu(page, mate.name) - await page.getByRole('menuitem', { name: role.name }).click() + await page.getByRole('menuitem', { name: role.name, exact: true }).click() const dialog = page.getByRole('alertdialog') await expect(dialog).toContainText( `${mate.name} will hold the "${role.name}" role and exactly the permissions it grants.` diff --git a/apps/web/e2e/tests/people/roles.spec.ts b/apps/web/e2e/tests/people/roles.spec.ts new file mode 100644 index 0000000000..c16588a52e --- /dev/null +++ b/apps/web/e2e/tests/people/roles.spec.ts @@ -0,0 +1,250 @@ +/** + * Roles: read-only presets, authoring a custom role, the grant ceiling, + * roles you hold, editing a role's holders' access, deleting with a move. + * + * Journeys: PPL-T-53, PPL-T-54, PPL-T-56, PPL-T-58, PPL-T-59, PPL-T-60, + * PPL-T-61 + */ +import { fromUuid, generateId } from '@quackback/ids' +import { test, expect } from '../../support/fixtures' +import { supportDb } from '../../support/db' +import { + callServerFn, + customRole, + mustCall, + personApi, + refusedCall, + roleIdOf, + roleOf, + uuid, +} from '../../product/people-team' + +/** Permission keys a role holds, sorted. */ +async function keysOf(roleId: string): Promise { + const rows = await supportDb()`SELECT p.key FROM role_permissions rp + JOIN permissions p ON p.id = rp.permission_id WHERE rp.role_id = ${uuid(roleId)}` + return rows.map((r) => r.key as string).sort() +} + +async function roleRow(roleId: string) { + const [row] = await supportDb()`SELECT name, is_system FROM roles WHERE id = ${uuid(roleId)}` + return row ?? null +} + +test.describe('presets and authoring', () => { + test( + 'PPL-T-53 presets are read-only on the page and on the server', + { tag: '@core' }, + async ({ asPerson, playwright }) => { + const contributor = await roleIdOf('contributor') + const page = await asPerson('admin') + await page.goto(`/admin/settings/members/roles/${contributor}`) + await expect(page.getByRole('button', { name: /Duplicate/ })).toBeVisible({ + timeout: 15_000, + }) + await expect(page.getByLabel('Name')).toHaveCount(0) + await expect(page.getByRole('button', { name: 'Save role' })).toHaveCount(0) + await expect(page.getByRole('button', { name: 'Delete role' })).toHaveCount(0) + + const before = await keysOf(contributor) + const admin = await personApi(playwright, 'admin') + const update = await refusedCall(admin, 'updateRoleFn', { + roleId: contributor, + permissionKeys: ['member.view'], + }) + expect(update.code).toBe('SYSTEM_ROLE') + const remove = await refusedCall(admin, 'deleteRoleFn', { roleId: contributor }) + expect(remove.code).toBe('SYSTEM_ROLE') + expect(await keysOf(contributor)).toEqual(before) + await admin.dispose() + } + ) + + test( + 'PPL-T-54 the owner creates a custom role with chosen permissions', + { tag: '@core' }, + async ({ asPerson, marker }) => { + const name = `Role ${marker}`.slice(0, 60) + const page = await asPerson('admin') + await page.goto('/admin/settings/members/roles/new') + await page.getByLabel('Name').fill(name) + await page.getByLabel('Description').fill('people e2e') + await page.getByPlaceholder(/^Filter \d+ permissions/).fill('member.view') + await page.getByRole('checkbox', { name: 'member.view' }).check() + await page.getByRole('button', { name: 'Create role' }).click() + await expect(page.getByText('Role created')).toBeVisible({ timeout: 15_000 }) + + const [row] = await supportDb()`SELECT is_system FROM roles WHERE name = ${name}` + expect(row.is_system).toBe(false) + const roleId = (await roleIdByName(name))! + expect(await keysOf(roleId)).toEqual(['member.view']) + const audit = await supportDb()`SELECT after_value FROM audit_log + WHERE event_type = 'role.created' AND target_id = ${roleId}` + expect(audit).toHaveLength(1) + expect(audit[0].after_value).toMatchObject({ name, permissionCount: 1 }) + } + ) + + test( + 'PPL-T-56 a limited editor cannot grant permissions they do not hold', + { tag: '@core' }, + async ({ playwright, marker, newTeammate }) => { + const editorRole = await customRole(marker, ['role.manage', 'member.view']) + const editor = await newTeammate({ roleKey: editorRole.key }) + const api = await editor.api(playwright) + const name = `Too big ${marker}`.slice(0, 60) + const create = await refusedCall(api, 'createRoleFn', { + name, + permissionKeys: ['member.view', 'settings.manage'], + }) + expect(create.code).toBe('GRANT_CEILING') + expect(create.error).toContain("You can't grant permissions you don't hold: settings.manage") + expect(await roleIdByName(name)).toBeNull() + + const other = await customRole(`${marker}-o`, ['member.view']) + const update = await refusedCall(api, 'updateRoleFn', { + roleId: other.id, + permissionKeys: ['member.view', 'billing.manage'], + }) + expect(update.code).toBe('GRANT_CEILING') + expect(await keysOf(other.id)).toEqual(['member.view']) + await api.dispose() + } + ) + + test( + 'PPL-T-58 nobody edits or deletes a role they hold', + { tag: '@core' }, + async ({ playwright, marker, newTeammate }) => { + const role = await customRole(marker, ['role.manage', 'member.view']) + const holder = await newTeammate({ roleKey: role.key }) + const api = await holder.api(playwright) + const edit = await refusedCall(api, 'updateRoleFn', { roleId: role.id, name: 'Renamed' }) + expect(edit.code).toBe('ROLE_HELD') + expect(edit.error).toContain("You can't edit a role you currently hold") + const remove = await refusedCall(api, 'deleteRoleFn', { roleId: role.id }) + expect(remove.code).toBe('ROLE_HELD') + expect((await roleRow(role.id))?.name).toBe(role.name) + await api.dispose() + } + ) +}) + +test.describe("changing a role's holders", () => { + test( + 'PPL-T-59 removing a key from a role takes it from every holder on the next request', + { tag: '@core' }, + async ({ playwright, marker, newTeammate }) => { + const role = await customRole(marker, ['changelog.view_draft', 'member.view']) + const holder = await newTeammate({ roleKey: role.key }) + const theirs = await holder.api(playwright) + await mustCall(theirs, 'listChangelogsFn', { status: 'all' }, { method: 'GET' }) + + const admin = await personApi(playwright, 'admin') + await mustCall(admin, 'updateRoleFn', { roleId: role.id, permissionKeys: ['member.view'] }) + const audit = await supportDb()`SELECT before_value, after_value FROM audit_log + WHERE event_type = 'role.updated' AND target_id = ${role.id}` + expect(audit).toHaveLength(1) + + const refused = await callServerFn( + theirs, + 'listChangelogsFn', + { status: 'all' }, + { + method: 'GET', + } + ) + expect(refused.ok).toBe(false) + expect(refused.error).toContain("Requires permission 'changelog.view_draft'") + + await mustCall(admin, 'updateRoleFn', { + roleId: role.id, + permissionKeys: ['member.view', 'changelog.view_draft'], + }) + await mustCall(theirs, 'listChangelogsFn', { status: 'all' }, { method: 'GET' }) + await theirs.dispose() + await admin.dispose() + } + ) + + test( + 'PPL-T-60 deleting a role with holders moves them to the chosen role', + { tag: '@core' }, + async ({ asPerson, marker, newTeammate }) => { + const role = await customRole(marker, ['member.view']) + const a = await newTeammate({ roleKey: role.key }) + const b = await newTeammate({ roleKey: role.key }) + const page = await asPerson('admin') + await page.goto(`/admin/settings/members/roles/${role.id}`) + await expect(async () => { + await page.getByRole('button', { name: 'Delete role' }).click() + await expect(page.getByRole('dialog')).toBeVisible({ timeout: 1_000 }) + }).toPass({ timeout: 15_000 }) + const dialog = page.getByRole('dialog') + await expect(dialog).toContainText( + '2 members hold this role. Choose the role they should move to. They keep workspace access either way.' + ) + await dialog.getByRole('combobox').click() + await expect(page.getByRole('option', { name: 'Owner', exact: true })).toHaveCount(0) + await expect(page.getByRole('option', { name: role.name, exact: true })).toHaveCount(0) + await page.getByRole('option', { name: 'Manager', exact: true }).click() + await dialog.getByRole('button', { name: 'Delete role' }).click() + await expect(page.getByText('Role deleted')).toBeVisible({ timeout: 15_000 }) + + expect(await roleRow(role.id)).toBeNull() + expect((await roleOf(a.principalId)).assigned).toBe('manager') + expect((await roleOf(b.principalId)).assigned).toBe('manager') + const audit = await supportDb()`SELECT before_value FROM audit_log + WHERE event_type = 'role.deleted' AND target_id = ${role.id}` + expect(audit).toHaveLength(1) + expect(audit[0].before_value).toMatchObject({ holders: 2 }) + } + ) + + test( + 'PPL-T-61 delete refuses a move to itself, to Owner, above the editor, or to an unknown role', + { tag: '@core' }, + async ({ playwright, marker, newTeammate }) => { + const role = await customRole(marker, ['member.view']) + const holder = await newTeammate({ roleKey: role.key }) + const admin = await personApi(playwright, 'admin') + + const self = await refusedCall(admin, 'deleteRoleFn', { + roleId: role.id, + reassignToRoleId: role.id, + }) + expect(self.error).toContain('Cannot reassign a role to itself') + const owner = await refusedCall(admin, 'deleteRoleFn', { + roleId: role.id, + reassignToRoleId: await roleIdOf('owner'), + }) + expect(owner.error).toContain('Reassigning to Owner is not allowed') + const unknown = await refusedCall(admin, 'deleteRoleFn', { + roleId: role.id, + reassignToRoleId: generateId('role'), + }) + expect(unknown.code).toBe('ROLE_NOT_FOUND') + const missing = await refusedCall(admin, 'deleteRoleFn', { roleId: role.id }) + expect(missing.code).toBe('ROLE_IN_USE') + + const editorRole = await customRole(`${marker}-e`, ['role.manage', 'member.view']) + const editor = await newTeammate({ roleKey: editorRole.key }) + const limited = await editor.api(playwright) + const above = await refusedCall(limited, 'deleteRoleFn', { + roleId: role.id, + reassignToRoleId: await roleIdOf('admin'), + }) + expect(above.code).toBe('GRANT_CEILING') + + expect((await roleRow(role.id))?.name).toBe(role.name) + expect((await roleOf(holder.principalId)).assigned).toBe(role.key) + await limited.dispose() + await admin.dispose() + } + ) +}) + +async function roleIdByName(name: string): Promise { + const [row] = await supportDb()`SELECT id FROM roles WHERE name = ${name}` + return row ? fromUuid('role', row.id as string) : null +} From d7b0b52fb0bd38978537dc7373bce50741b9d0f3 Mon Sep 17 00:00:00 2001 From: James Morton Date: Fri, 20 Nov 2026 07:44:51 +0000 Subject: [PATCH 4/5] test(e2e): people portal account journeys --- apps/web/e2e/QUARANTINE.md | 9 + .../e2e/tests/people/portal-account.spec.ts | 159 ++++++++++++++++++ 2 files changed, 168 insertions(+) create mode 100644 apps/web/e2e/tests/people/portal-account.spec.ts diff --git a/apps/web/e2e/QUARANTINE.md b/apps/web/e2e/QUARANTINE.md index de0f707eaf..ebee48946e 100644 --- a/apps/web/e2e/QUARANTINE.md +++ b/apps/web/e2e/QUARANTINE.md @@ -709,3 +709,12 @@ no such part beyond the wrong notification). the same action (PPL-T-37). Fix: pass the key's creator principal as the acting principal for personal keys. owner: unassigned, review by: 2026-12-03. +- `people/portal-account.spec.ts` › profile › PPL-ACC-14 saving someone + else's uploaded avatar key is refused. Product bug: `saveAvatarKeyFn` only + checks that the key starts with `avatars/` and has no `..` + (`apps/web/src/lib/server/functions/user.ts:44`), so any signed-in person + can point their avatar at another person's object, and a later + `removeAvatarFn` (`user.ts:222`, via `deleteExistingAvatar`) deletes that + object from storage. Fix: issue avatar keys per user (for example + `avatars//...` from `getAvatarUploadUrlFn`) and refuse a key outside + the caller's prefix. owner: unassigned, review by: 2026-12-03. diff --git a/apps/web/e2e/tests/people/portal-account.spec.ts b/apps/web/e2e/tests/people/portal-account.spec.ts new file mode 100644 index 0000000000..e917e61d18 --- /dev/null +++ b/apps/web/e2e/tests/people/portal-account.spec.ts @@ -0,0 +1,159 @@ +/** + * The portal account pages (/settings/*): who may open them, renaming, + * avatars, the email change refusals and the profile read. + * + * Journeys: PPL-ACC-02, PPL-ACC-04, PPL-ACC-07, PPL-ACC-14, PPL-ACC-18, + * PPL-ACC-32 + */ +import { test, expect } from '../../support/fixtures' +import { supportDb } from '../../support/db' +import { mailTo } from '../../support/mailpit' +import { callServerFn, mustCall, portalUser, refusedCall } from '../../product/people-team' + +/** Upload a tiny PNG as the signed-in person's avatar the way the profile form does. */ +async function uploadAvatar( + api: Parameters[0], + filename: string +): Promise { + const png = Buffer.from( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', + 'base64' + ) + const presigned = await mustCall<{ uploadUrl: string; key: string }>( + api, + 'getAvatarUploadUrlFn', + { filename, contentType: 'image/png', fileSize: png.length } + ) + const put = await api.put(presigned.uploadUrl, { + headers: { 'content-type': 'image/png' }, + data: png, + }) + expect(put.status(), await put.text()).toBeLessThan(300) + await mustCall(api, 'saveAvatarKeyFn', { key: presigned.key }) + return presigned.key +} + +test.describe('who may open the account pages', () => { + test( + 'PPL-ACC-02 a signed-out visitor is sent to the portal home from every settings page', + { tag: '@core' }, + async ({ page }) => { + for (const path of [ + '/settings', + '/settings/profile', + '/settings/preferences', + '/settings/api-keys', + ]) { + await page.goto(path) + await expect(page, path).toHaveURL(/\/$/) + await expect(page.getByRole('heading', { name: 'Profile' })).toHaveCount(0) + } + } + ) + + test( + 'PPL-ACC-04 a portal user is kept out of the API keys page and its functions', + { tag: '@core' }, + async ({ browser, marker }) => { + const person = await portalUser(browser, marker) + const page = await person.context.newPage() + await page.goto('/settings/api-keys') + await expect(page).toHaveURL(/\/settings\/profile/, { timeout: 15_000 }) + + const list = await refusedCall(person.api, 'fetchMyApiKeysFn', undefined, { method: 'GET' }) + expect(list.error).toContain('Access denied: Not a team member') + const create = await refusedCall(person.api, 'createMyApiKeyFn', { + name: `Key ${marker}`, + scopes: ['read:feedback'], + expiry: '30d', + }) + expect(create.code).toBe('FORBIDDEN') + const keys = + await supportDb()`SELECT id FROM api_keys WHERE created_by_id = ${person.principalUuid}` + expect(keys).toHaveLength(0) + } + ) +}) + +test.describe('profile', () => { + test( + 'PPL-ACC-07 a portal user renames themselves', + { tag: '@core' }, + async ({ browser, marker }) => { + const person = await portalUser(browser, marker) + const page = await person.context.newPage() + await page.goto('/settings/profile') + const field = page.locator('#name') + await expect(field).toHaveValue(person.name, { timeout: 15_000 }) + const renamed = `Renamed ${marker}`.slice(0, 90) + await field.fill(` ${renamed} `) + await page.getByRole('button', { name: 'Save changes' }).click() + await expect(page.getByText('Profile updated')).toBeVisible() + + const [u] = await supportDb()`SELECT name FROM "user" WHERE id = ${person.userUuid}` + const [p] = + await supportDb()`SELECT display_name FROM principal WHERE id = ${person.principalUuid}` + expect(u.name).toBe(renamed) + expect(p.display_name).toBe(renamed) + await page.reload() + await expect(page.locator('#name')).toHaveValue(renamed, { timeout: 15_000 }) + } + ) + + test( + "PPL-ACC-14 saving someone else's uploaded avatar key is refused", + { + tag: ['@core', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'saveAvatarKeyFn accepts any avatars/ key (functions/user.ts saveAvatarKeySchema); a later remove deletes the other person object; see QUARANTINE.md', + }, + }, + async ({ browser, marker }) => { + const owner = await portalUser(browser, `${marker}-b`) + const key = await uploadAvatar(owner.api, `${marker}.png`) + const other = await portalUser(browser, marker) + + const res = await callServerFn(other.api, 'saveAvatarKeyFn', { key }) + expect(res.ok, 'a key the caller did not upload is refused').toBe(false) + const [u] = await supportDb()`SELECT image_key FROM "user" WHERE id = ${other.userUuid}` + expect(u.image_key).toBeNull() + } + ) + + test( + 'PPL-ACC-18 an email change needs a good current-address code and mails nobody otherwise', + { tag: '@core' }, + async ({ browser, marker }) => { + const person = await portalUser(browser, marker) + const next = `${marker}-new@customers.example` + const none = await refusedCall(person.api, 'requestEmailChangeFn', { email: next }) + expect(none.code).toBe('CURRENT_CODE_REQUIRED') + const wrong = await refusedCall(person.api, 'requestEmailChangeFn', { + email: next, + currentCode: '000000', + }) + expect(wrong.code).toBe('INVALID_CODE') + await new Promise((r) => setTimeout(r, 1_500)) + expect(await mailTo(next)).toHaveLength(0) + const [u] = await supportDb()`SELECT email FROM "user" WHERE id = ${person.userUuid}` + expect(u.email).toBe(person.email) + } + ) + + test( + "PPL-ACC-32 reading another person's profile is refused", + { tag: '@core' }, + async ({ browser, marker }) => { + const a = await portalUser(browser, marker) + const b = await portalUser(browser, `${marker}-b`) + const own = await callServerFn(a.api, 'fetchUserProfile', a.userId, { method: 'GET' }) + expect(own.ok, own.raw.slice(0, 300)).toBe(true) + expect(own.raw).toContain('hasPassword') + const res = await refusedCall(a.api, 'fetchUserProfile', b.userId, { method: 'GET' }) + expect(res.error).toContain("Access denied: Cannot view other users' profiles") + expect(res.raw).not.toContain('hasPassword') + } + ) +}) From 2c9e283e11c8d5340200d4072cc8766af9796326 Mon Sep 17 00:00:00 2001 From: James Morton Date: Fri, 20 Nov 2026 08:51:45 +0000 Subject: [PATCH 5/5] test(e2e): close portal contexts, own client address, steadier role and account steps --- apps/web/e2e/product/people-team.ts | 16 +++++++-- apps/web/e2e/tests/people/invitations.spec.ts | 3 ++ .../e2e/tests/people/portal-account.spec.ts | 36 ++++++------------- apps/web/e2e/tests/people/roles.spec.ts | 11 ++++-- 4 files changed, 36 insertions(+), 30 deletions(-) diff --git a/apps/web/e2e/product/people-team.ts b/apps/web/e2e/product/people-team.ts index 0577795f9d..ec309597c4 100644 --- a/apps/web/e2e/product/people-team.ts +++ b/apps/web/e2e/product/people-team.ts @@ -22,7 +22,7 @@ import { import { fromUuid, generateId, toUuid } from '@quackback/ids' import { supportDb } from '../support/db' import { supportEnv } from '../support/env' -import { apiFor, createKey } from '../support/api-client' +import { apiFor, clientIp, createKey } from '../support/api-client' import { callServerFn, type ServerFnResult } from '../support/server-fns' import { mintCustomer, portalContext, type MintedCustomer } from '../support/widget-portal' @@ -69,7 +69,16 @@ export interface PortalUser extends MintedCustomer { api: APIRequestContext } -/** A fresh identified portal user with a live session (portal cookie). */ +const openContexts = new Set() + +/** Close every portal user's browser context this worker opened (afterEach). */ +export async function closePortalUsers(): Promise { + const open = [...openContexts] + openContexts.clear() + await Promise.all(open.map((c) => c.close().catch(() => {}))) +} + +/** A fresh identified portal user with a live session (portal cookie). Close with closePortalUsers. */ export async function portalUser( browser: Browser, marker: string, @@ -81,6 +90,9 @@ export async function portalUser( name: opts.name ?? `Person ${marker} ${s}`, }) const context = await portalContext(browser, customer) + // Its own client address, so per-address rate limits never couple tests. + await context.setExtraHTTPHeaders({ 'x-e2e-client-ip': clientIp() }) + openContexts.add(context) return { ...customer, context, api: context.request } } diff --git a/apps/web/e2e/tests/people/invitations.spec.ts b/apps/web/e2e/tests/people/invitations.spec.ts index a4230b31e7..31df34daa5 100644 --- a/apps/web/e2e/tests/people/invitations.spec.ts +++ b/apps/web/e2e/tests/people/invitations.spec.ts @@ -23,8 +23,11 @@ import { roleIdOf, roleOf, suffix, + closePortalUsers, } from '../../product/people-team' +test.afterEach(() => closePortalUsers()) + function inviteeEmail(marker: string): string { return `${marker}-${suffix()}@invitees.example` } diff --git a/apps/web/e2e/tests/people/portal-account.spec.ts b/apps/web/e2e/tests/people/portal-account.spec.ts index e917e61d18..38dab62d39 100644 --- a/apps/web/e2e/tests/people/portal-account.spec.ts +++ b/apps/web/e2e/tests/people/portal-account.spec.ts @@ -2,13 +2,21 @@ * The portal account pages (/settings/*): who may open them, renaming, * avatars, the email change refusals and the profile read. * - * Journeys: PPL-ACC-02, PPL-ACC-04, PPL-ACC-07, PPL-ACC-14, PPL-ACC-18, + * Journeys: PPL-ACC-02, PPL-ACC-04, PPL-ACC-14, PPL-ACC-18, * PPL-ACC-32 */ import { test, expect } from '../../support/fixtures' import { supportDb } from '../../support/db' import { mailTo } from '../../support/mailpit' -import { callServerFn, mustCall, portalUser, refusedCall } from '../../product/people-team' +import { + callServerFn, + closePortalUsers, + mustCall, + portalUser, + refusedCall, +} from '../../product/people-team' + +test.afterEach(() => closePortalUsers()) /** Upload a tiny PNG as the signed-in person's avatar the way the profile form does. */ async function uploadAvatar( @@ -76,30 +84,6 @@ test.describe('who may open the account pages', () => { }) test.describe('profile', () => { - test( - 'PPL-ACC-07 a portal user renames themselves', - { tag: '@core' }, - async ({ browser, marker }) => { - const person = await portalUser(browser, marker) - const page = await person.context.newPage() - await page.goto('/settings/profile') - const field = page.locator('#name') - await expect(field).toHaveValue(person.name, { timeout: 15_000 }) - const renamed = `Renamed ${marker}`.slice(0, 90) - await field.fill(` ${renamed} `) - await page.getByRole('button', { name: 'Save changes' }).click() - await expect(page.getByText('Profile updated')).toBeVisible() - - const [u] = await supportDb()`SELECT name FROM "user" WHERE id = ${person.userUuid}` - const [p] = - await supportDb()`SELECT display_name FROM principal WHERE id = ${person.principalUuid}` - expect(u.name).toBe(renamed) - expect(p.display_name).toBe(renamed) - await page.reload() - await expect(page.locator('#name')).toHaveValue(renamed, { timeout: 15_000 }) - } - ) - test( "PPL-ACC-14 saving someone else's uploaded avatar key is refused", { diff --git a/apps/web/e2e/tests/people/roles.spec.ts b/apps/web/e2e/tests/people/roles.spec.ts index c16588a52e..0fd8105f5f 100644 --- a/apps/web/e2e/tests/people/roles.spec.ts +++ b/apps/web/e2e/tests/people/roles.spec.ts @@ -67,10 +67,17 @@ test.describe('presets and authoring', () => { const name = `Role ${marker}`.slice(0, 60) const page = await asPerson('admin') await page.goto('/admin/settings/members/roles/new') + // Retried until the editor has hydrated (an early fill is reset by it). + await expect(async () => { + const box = page.getByRole('checkbox', { name: 'member.view', exact: true }) + if (!(await box.isVisible())) + await page.getByRole('button', { name: /^Members \d+ of/ }).click() + await box.check({ timeout: 2_000 }) + await expect(box).toBeChecked() + }).toPass({ timeout: 20_000 }) await page.getByLabel('Name').fill(name) await page.getByLabel('Description').fill('people e2e') - await page.getByPlaceholder(/^Filter \d+ permissions/).fill('member.view') - await page.getByRole('checkbox', { name: 'member.view' }).check() + await expect(page.getByLabel('Name')).toHaveValue(name) await page.getByRole('button', { name: 'Create role' }).click() await expect(page.getByText('Role created')).toBeVisible({ timeout: 15_000 })