test(app): V1-2.5 browser journeys A0, A1, S1, P1 on the sandbox (J)

Owner bootstrap with two factors, step-up, rights; sheet creation; species activation seen by the animal form; catalogue reader with search, zone panel, withdrawn and archived versions; access per right; axe and widths 320-430 / 375 / desktop, FR and EN. Shell suite 108 passed, 6 skipped by design.
This commit is contained in:
bchanot committed 2026-11-02 17:44:14 +01:00
1 parent a897dd8876
commit 4f6c0ba407
4 files changed
+1328

No files matched your search

+716
View File
@@ -0,0 +1,716 @@
import { randomUUID } from 'node:crypto'
import { en } from '@/i18n/en'
import { fr } from '@/i18n/fr'
import type { Dict } from '@/i18n/types'
import type { Locator, Page, TestInfo } from '@playwright/test'
import { sql } from '../../../../packages/supabase/tests/sandbox/stack'
import {
expect,
expectAccessible,
expectNoHorizontalOverflow,
test,
} from '../support/browser'
import {
assignRole,
enrolVerifiedFactor,
enterCode,
seedGrant,
sessionAal,
stepUpAdmin,
stepUpHeading,
} from '../support/admin'
import {
createAccount,
dropLateReplays,
routeToSandbox,
type SandboxAccount,
} from '../support/sandbox'
import { signIn } from '../support/shell'
// V1-2.5 administration on the isolated stack (contract §11.2 A0, A1, S1,
// §5.6, §16.6): the owner's bootstrap from Mon compte, Sécurité (two TOTP
// factors, the step-up a session at aal1 meets, refresh keeping each level),
// rights granted and revoked, a sheet created by an editor, a species created
// inactive then activated, what each right shows. Accounts, roles, earlier
// grants and factors of other people are set up the way the sandbox suites do;
// what a test proves goes through the page. FR and EN, desktop and 375 px.
const LANGUAGES = [
['fr', fr],
['en', en],
] as const
const isPhone = (info: TestInfo) => info.project.name === 'chromium-375'
const tagOf = () => randomUUID().slice(0, 8)
const main = (page: Page) => page.getByRole('main')
const heading = (page: Page, name: string) =>
main(page).getByRole('heading', { level: 1, name })
/** Follows an entry of the shell's navigation: the sidebar, or the drawer on a phone. */
async function navigate(page: Page, dict: Dict, info: TestInfo, key: string) {
if (isPhone(info)) {
await page.getByRole('button', { name: dict['shell.open_menu'] }).click()
await page
.getByRole('dialog', { name: dict['shell.nav_label'] })
.getByRole('navigation')
.getByRole('link', { name: dict[key] })
.click()
} else {
await page
.getByRole('navigation', { name: dict['shell.nav_label'] })
.getByRole('link', { name: dict[key] })
.click()
}
}
/** The shell's sign-out: in the sidebar, or the drawer on a phone (Mon compte has its own). */
async function signOut(page: Page, dict: Dict, info: TestInfo) {
const scope = isPhone(info)
? page.getByRole('dialog', { name: dict['shell.nav_label'] })
: page.getByRole('complementary')
if (isPhone(info))
await page.getByRole('button', { name: dict['shell.open_menu'] }).click()
await scope.getByRole('button', { name: dict['shell.sign_out'] }).click()
await expect(page).toHaveURL(/\/$/)
}
/** The card of an administration area on /app/admin, by its heading id. */
const areaCard = (page: Page, id: string) =>
page.locator(`section[aria-labelledby="${id}"]`)
const factorList = (page: Page, dict: Dict) =>
page
.getByRole('list', { name: dict['mfa.factor.list_label'] })
.getByRole('listitem')
/**
* Adds a factor from Mon compte, Sécurité up to the QR code; resolves with the
* secret shown for manual entry (read from the page, as a person would copy it).
*/
async function startEnrolment(
page: Page,
dict: Dict,
name: string,
): Promise<Locator> {
await page.getByRole('button', { name: dict['mfa.enrol.start'] }).click()
await page.getByLabel(dict['mfa.enrol.name']).fill(name)
await page.getByRole('button', { name: dict['mfa.enrol.continue'] }).click()
return page
.locator('div', {
has: page.getByRole('img', { name: dict['mfa.enrol.qr_alt'] }),
})
.last()
}
async function enrolFromPage(
page: Page,
dict: Dict,
name: string,
): Promise<string> {
const box = await startEnrolment(page, dict, name)
await expect(
box.getByRole('img', { name: dict['mfa.enrol.qr_alt'] }),
).toBeVisible()
const secret = (await box.locator('code').textContent())?.trim() ?? ''
expect(secret).toMatch(/^[A-Z2-7]{16,}$/)
await enterCode(box, dict, secret)
await expect(page.getByText(dict['mfa.enrol.done'])).toBeVisible()
return secret
}
/** Finds an account on the rights screen and grants it `kind` with a reason and a note. */
async function grant(
page: Page,
dict: Dict,
email: string,
kind: string,
note = true,
) {
const panel = page.locator('section[aria-labelledby="grant-title"]')
await panel.getByLabel(dict['admin.access.lookup.email']).fill(email)
await panel
.getByRole('button', { name: dict['admin.access.lookup.submit'] })
.click()
await expect(
panel.getByText(dict['admin.access.account.confirmed']),
).toBeVisible()
await panel
.getByRole('radio', { name: dict[`admin.grant_kind.${kind}`] })
.check()
await panel
.getByLabel(dict['admin.access.form.reason'])
.fill(`Motif e2e ${kind}`)
if (note)
await panel
.getByLabel(dict['admin.access.form.note'])
.fill(`Diplôme vu, e2e ${kind}`)
await panel
.getByRole('button', { name: dict['admin.access.form.submit'] })
.click()
await expect(panel.getByText(dict['admin.access.granted'])).toBeVisible()
}
/** The row of the rights list for this holder and right. */
const grantRow = (page: Page, dict: Dict, email: string, kind: string) =>
page
.getByRole('list', { name: dict['admin.access.list.title'] })
.getByRole('listitem')
.filter({ hasText: email })
.filter({ hasText: dict[`admin.grant_kind.${kind}`] })
/** A confirmed account with a platform role, rights and a verified factor (its secret). */
async function staff(
locale: 'fr' | 'en',
role: 'owner' | 'admin' | null,
grants: Parameters<typeof seedGrant>[1][],
): Promise<{ account: SandboxAccount; secret: string }> {
const account = await createAccount(locale, false)
if (role) await assignRole(account, role)
for (const kind of grants) await seedGrant(account, kind)
return { account, secret: await enrolVerifiedFactor(account) }
}
/** Signs in, opens /app/admin from the navigation and steps up. */
async function openAdmin(
page: Page,
dict: Dict,
info: TestInfo,
account: SandboxAccount,
secret: string,
) {
await signIn(page, account, dict)
await navigate(page, dict, info, 'shell.nav.admin')
await expect(page).toHaveURL(/\/app\/admin$/)
await stepUpAdmin(page, dict, secret)
await expect(heading(page, dict['shell.nav.admin'])).toBeVisible()
}
/** The species select of the animal form (V1-1), loaded. */
async function animalSpeciesOptions(page: Page, dict: Dict): Promise<string[]> {
await page.goto('/app/animals/new')
const select = page.getByRole('combobox', {
name: dict['animals.form.species'],
})
await expect(select.locator('option[value="equine"]')).toHaveCount(1)
return select
.locator('option')
.evaluateAll((options) =>
options.map((option) => (option as HTMLOptionElement).value),
)
}
for (const [locale, dict] of LANGUAGES) {
test.describe(`administration (${locale})`, () => {
test.use({ locale: locale === 'fr' ? 'fr-FR' : 'en-GB' })
test.beforeEach(async ({ context }) => {
await routeToSandbox(context)
})
test.afterEach(async ({ context }) => {
await dropLateReplays(context)
})
test('A0: the owner enrols two factors, steps up, grants itself and a reviewer, revokes', async ({
page,
requests,
}, info) => {
test.skip(
isPhone(info),
'desktop journey (the admin screens at 375 px are covered below)',
)
test.setTimeout(300_000)
const owner = await createAccount(locale, false)
await assignRole(owner, 'owner')
requests.forbid(owner.email, owner.password, owner.displayName)
await signIn(page, owner, dict)
// No factor yet: the entry is there, the page asks for a factor first.
await navigate(page, dict, info, 'shell.nav.admin')
await expect(stepUpHeading(page, dict)).toBeVisible()
await expect(
main(page).getByText(dict['admin.step_up.no_factor']),
).toBeVisible()
await expect(main(page).getByLabel(dict['mfa.code.label'])).toHaveCount(0)
await expectAccessible(page, 'the admin gate without a factor')
await main(page)
.getByRole('link', { name: dict['admin.step_up.to_security'] })
.click()
await expect(page).toHaveURL(/\/app\/account#security-title$/)
await expect(page.getByText(dict['mfa.factor.none'])).toBeVisible()
// First factor from the aal1 session; the QR step passes axe.
const box = await startEnrolment(page, dict, 'Téléphone')
await expect(
box.getByRole('img', { name: dict['mfa.enrol.qr_alt'] }),
).toBeVisible()
await expectAccessible(page, 'the enrolment step with the QR code')
await expectNoHorizontalOverflow(
page,
'the enrolment step with the QR code',
)
const first = (await box.locator('code').textContent())?.trim() ?? ''
expect(first).toMatch(/^[A-Z2-7]{16,}$/)
await enterCode(box, dict, first)
await expect(page.getByText(dict['mfa.enrol.done'])).toBeVisible()
expect(await sessionAal(page)).toBe('aal2')
// A second factor at aal2: no step-up asked.
const second = await enrolFromPage(page, dict, 'Clé de secours')
expect(second).not.toBe(first)
await expect(factorList(page, dict)).toHaveCount(2)
await expect(
factorList(page, dict).filter({ hasText: dict['mfa.factor.verified'] }),
).toHaveCount(2)
await expectAccessible(page, 'Sécurité with two factors')
// A new sign-in is aal1: another factor asks for the step-up, then goes on.
await signOut(page, dict, info)
await signIn(page, owner, dict)
expect(await sessionAal(page)).toBe('aal1')
await page.goto('/app/account')
await page.getByRole('button', { name: dict['mfa.enrol.start'] }).click()
await page.getByLabel(dict['mfa.enrol.name']).fill('Tablette')
await page
.getByRole('button', { name: dict['mfa.enrol.continue'] })
.click()
await expect(page.getByText(dict['mfa.step_up.required'])).toBeVisible()
await expect(
page.getByRole('img', { name: dict['mfa.enrol.qr_alt'] }),
).toHaveCount(0)
await expect(
page.getByLabel(dict['mfa.step_up.factor'], { exact: true }),
).toBeVisible()
await expectAccessible(page, 'the inline step-up of an enrolment')
// Several factors: the code comes from the one chosen.
await page
.getByLabel(dict['mfa.step_up.factor'], { exact: true })
.selectOption({ label: 'Téléphone' })
await enterCode(page.getByRole('main'), dict, first)
await expect(
page.getByRole('img', { name: dict['mfa.enrol.qr_alt'] }),
).toBeVisible()
expect(await sessionAal(page)).toBe('aal2')
// Cancelled: the unverified factor it made is removed.
await page.getByRole('button', { name: dict['common.cancel'] }).click()
await expect(factorList(page, dict)).toHaveCount(2)
// Again at aal1: removing a verified factor asks for the step-up too.
await signOut(page, dict, info)
await signIn(page, owner, dict)
await page.goto('/app/account')
const spare = factorList(page, dict).filter({ hasText: 'Clé de secours' })
await spare
.getByRole('button', { name: dict['mfa.factor.remove'] })
.click()
const confirm = page.getByRole('dialog', {
name: dict['mfa.remove.title'],
})
await confirm
.getByRole('button', { name: dict['mfa.remove.confirm'] })
.click()
await expect(page.getByText(dict['mfa.step_up.required'])).toBeVisible()
// The confirmation closes first (while it is modal, the page behind is inert).
await expect(confirm).toBeHidden()
await expect(factorList(page, dict)).toHaveCount(2)
// Several factors: the code comes from the one chosen.
await page
.getByLabel(dict['mfa.step_up.factor'], { exact: true })
.selectOption({ label: 'Téléphone' })
await enterCode(page.getByRole('main'), dict, first)
await expect(page.getByText(dict['mfa.factor.removed'])).toBeVisible()
await expect(factorList(page, dict)).toHaveCount(1)
// An aal1 session meets the step-up on /app/admin, and a refresh keeps aal1.
await signOut(page, dict, info)
await signIn(page, owner, dict)
await navigate(page, dict, info, 'shell.nav.admin')
await expect(stepUpHeading(page, dict)).toBeVisible()
await expect(heading(page, dict['shell.nav.admin'])).toHaveCount(0)
await page.reload()
await expect(stepUpHeading(page, dict)).toBeVisible()
expect(await sessionAal(page)).toBe('aal1')
await expectAccessible(page, 'the admin step-up')
await stepUpAdmin(page, dict, first)
await expect(heading(page, dict['shell.nav.admin'])).toBeVisible()
// A refresh keeps aal2: no step-up again.
await page.reload()
await expect(heading(page, dict['shell.nav.admin'])).toBeVisible()
await expect(stepUpHeading(page, dict)).toHaveCount(0)
expect(await sessionAal(page)).toBe('aal2')
// The owner grants itself editor and publisher.
await areaCard(page, 'admin-access-title').getByRole('link').click()
await expect(heading(page, dict['admin.access.title'])).toBeVisible()
await grant(page, dict, owner.email, 'sheet_editor')
await grant(page, dict, owner.email, 'sheet_publisher')
for (const kind of ['sheet_editor', 'sheet_publisher'])
await expect(
grantRow(page, dict, owner.email, kind).getByText(
dict['admin.grant_state.active'],
{ exact: true },
),
).toBeVisible()
// A business reviewer: confirmed account with its own verified factor, granted reviewer.
const reviewer = await createAccount(locale, false)
await enrolVerifiedFactor(reviewer)
requests.forbid(reviewer.email, reviewer.password, reviewer.displayName)
await grant(page, dict, reviewer.email, 'sheet_reviewer')
const reviewerRow = grantRow(page, dict, reviewer.email, 'sheet_reviewer')
await expect(
reviewerRow.getByText(dict['admin.grant_state.active'], {
exact: true,
}),
).toBeVisible()
await expect(
reviewerRow.getByText('Diplôme vu, e2e sheet_reviewer'),
).toBeVisible()
await expectAccessible(page, 'the rights screen with grants')
// Revocation with its reason: the row shows it revoked, its reason kept.
await reviewerRow
.getByRole('button', { name: dict['admin.access.revoke.action'] })
.click()
const revoke = page.getByRole('dialog', {
name: dict['admin.access.revoke.title'],
})
await expect(revoke).toBeVisible()
await expectAccessible(page, 'the revocation dialog')
await revoke
.getByLabel(dict['admin.access.revoke.reason'])
.fill('Fin de mission e2e')
await revoke
.getByRole('button', { name: dict['admin.access.revoke.confirm'] })
.click()
await expect(revoke).toBeHidden()
await expect(
page.getByText(dict['admin.access.revoke.done']),
).toBeVisible()
await expect(
reviewerRow.getByText(dict['admin.grant_state.revoked'], {
exact: true,
}),
).toBeVisible()
await expect(reviewerRow.getByText('Fin de mission e2e')).toBeVisible()
await expect(
reviewerRow.getByRole('button', {
name: dict['admin.access.revoke.action'],
}),
).toHaveCount(0)
expect(
await sql(`select count(*) from public.anatomical_catalog_grants
where user_id = '${reviewer.id}' and revoked_at is not null`),
).toBe('1')
})
test('A1: an editor at aal2 creates a sheet on a new inactive species; it opens on draft v1', async ({
page,
requests,
}, info) => {
test.skip(
isPhone(info),
'desktop journey (the admin screens at 375 px are covered below)',
)
const { account, secret } = await staff(locale, 'admin', ['sheet_editor'])
requests.forbid(account.email, account.password, account.displayName)
await openAdmin(page, dict, info, account, secret)
await areaCard(page, 'admin-sheets-title')
.getByRole('link', { name: dict['admin.home.all_sheets'] })
.click()
await expect(heading(page, dict['admin.sheets.title'])).toBeVisible()
await main(page)
.getByRole('link', { name: dict['admin.sheets.new'] })
.click()
await expect(heading(page, dict['admin.sheets.new'])).toBeVisible()
// « Nouvelle espèce » from the form: created inactive, then chosen.
const tag = tagOf()
const speciesId = `e2e_${tag}`
await main(page)
.getByRole('button', { name: dict['admin.species.new'] })
.click()
const dialog = page.getByRole('dialog', {
name: dict['admin.species.dialog.create_title'],
})
await dialog.getByLabel(dict['admin.species.field.id']).fill(speciesId)
await dialog
.getByLabel(dict['admin.species.field.name_fr'])
.fill(`Espèce ${tag}`)
await dialog
.getByLabel(dict['admin.species.field.name_en'])
.fill(`Species ${tag}`)
await dialog.getByRole('button', { name: dict['common.save'] }).click()
await expect(dialog).toBeHidden()
const species = page.getByLabel(dict['admin.sheet_form.species'], {
exact: true,
})
await expect(species).toHaveValue(speciesId)
await expect(species.locator('option:checked')).toHaveText(
dict['admin.sheet_form.species_inactive'].replace(
'{name}',
locale === 'fr' ? `Espèce ${tag}` : `Species ${tag}`,
),
)
expect(
await sql(
`select active from public.species where id = '${speciesId}'`,
),
).toBe('f')
await page
.getByLabel(dict['admin.sheet_form.name_fr'])
.fill(`Fiche e2e ${tag}`)
await page
.getByLabel(dict['admin.sheet_form.name_en'])
.fill(`E2E sheet ${tag}`)
// The slug follows the French name until edited.
await expect(page.getByLabel(dict['admin.sheet_form.slug'])).toHaveValue(
`fiche-e2e-${tag}`,
)
await expectAccessible(page, 'the sheet creation form')
await page
.getByRole('button', { name: dict['admin.sheet_form.submit'] })
.click()
await expect(page).toHaveURL(/\/app\/admin\/sheets\/[0-9a-f-]{36}$/)
const name = locale === 'fr' ? `Fiche e2e ${tag}` : `E2E sheet ${tag}`
await expect(heading(page, name)).toBeVisible()
const versions = main(page)
.getByRole('listitem')
.filter({
hasText: dict['admin.overview.version'].replace('{number}', '1'),
})
await expect(versions).toHaveCount(1)
await expect(
versions.getByText(dict['admin.version_status.draft'], { exact: true }),
).toBeVisible()
await expect(
main(page).getByText(dict['admin.sheets.no_published'], {
exact: false,
}),
).toBeVisible()
expect(
await sql(`select v.status || '/' || v.version_number from public.anatomical_sheets s
join public.anatomical_sheet_versions v on v.sheet_id = s.id
where s.slug = 'fiche-e2e-${tag}' and s.species_id = '${speciesId}'`),
).toBe('draft/1')
await expectAccessible(page, 'the new sheet overview')
})
test('S1: an editor creates an inactive species; the animal form offers it only once the owner activates it', async ({
page,
requests,
}, info) => {
test.skip(
isPhone(info),
'desktop journey (the admin screens at 375 px are covered below)',
)
test.setTimeout(180_000)
const editor = await staff(locale, 'admin', ['sheet_editor'])
const owner = await staff(locale, 'owner', [])
requests.forbid(
editor.account.email,
editor.account.password,
editor.account.displayName,
)
requests.forbid(
owner.account.email,
owner.account.password,
owner.account.displayName,
)
const tag = tagOf()
const speciesId = `e2e_${tag}`
const label = (row: string) => `${row} ${tag}`
const shown = locale === 'fr' ? label('Espèce') : label('Species')
await openAdmin(page, dict, info, editor.account, editor.secret)
await areaCard(page, 'admin-species-title').getByRole('link').click()
await expect(heading(page, dict['admin.species.title'])).toBeVisible()
await main(page)
.getByRole('button', { name: dict['admin.species.new'] })
.click()
const dialog = page.getByRole('dialog', {
name: dict['admin.species.dialog.create_title'],
})
await dialog.getByLabel(dict['admin.species.field.id']).fill(speciesId)
await dialog
.getByLabel(dict['admin.species.field.name_fr'])
.fill(label('Espèce'))
await dialog
.getByLabel(dict['admin.species.field.name_en'])
.fill(label('Species'))
await dialog.getByRole('button', { name: dict['common.save'] }).click()
await expect(page.getByText(dict['admin.species.created'])).toBeVisible()
const row = main(page)
.getByRole('listitem')
.filter({ hasText: speciesId })
await expect(
row.getByText(dict['admin.species.state.inactive'], { exact: true }),
).toBeVisible()
// The editor edits an inactive species; activating is the owner's.
await expect(
row.getByRole('button', {
name: dict['admin.species.edit_named'].replace('{name}', shown),
}),
).toBeVisible()
await expect(
row.getByRole('button', {
name: dict['admin.species.activate.action_named'].replace(
'{name}',
shown,
),
}),
).toHaveCount(0)
expect(await animalSpeciesOptions(page, dict)).not.toContain(speciesId)
await signOut(page, dict, info)
await openAdmin(page, dict, info, owner.account, owner.secret)
await areaCard(page, 'admin-species-title').getByRole('link').click()
const ownerRow = main(page)
.getByRole('listitem')
.filter({ hasText: speciesId })
await ownerRow
.getByRole('button', {
name: dict['admin.species.activate.action_named'].replace(
'{name}',
shown,
),
})
.click()
const activate = page.getByRole('dialog', {
name: dict['admin.species.activate.title'].replace('{name}', shown),
})
await expect(activate).toBeVisible()
await expectAccessible(page, 'the activation confirmation')
await activate
.getByRole('button', { name: dict['admin.species.activate.confirm'] })
.click()
await expect(
page.getByText(dict['admin.species.activate.done']),
).toBeVisible()
await expect(
ownerRow.getByText(dict['admin.species.state.active'], { exact: true }),
).toBeVisible()
expect(await animalSpeciesOptions(page, dict)).toContain(speciesId)
})
test('access per right: a reviewer sees no creation, rights or working copy; an admin without capability no sheets', async ({
page,
requests,
}, info) => {
test.setTimeout(180_000)
const reviewer = await staff(locale, null, ['sheet_reviewer'])
requests.forbid(
reviewer.account.email,
reviewer.account.password,
reviewer.account.displayName,
)
await openAdmin(page, dict, info, reviewer.account, reviewer.secret)
await expect(
main(page).getByText(dict['admin.home.capability.sheet_reviewer'], {
exact: false,
}),
).toBeVisible()
const sheets = areaCard(page, 'admin-sheets-title')
await expect(sheets).toBeVisible()
// No working copy action for a reviewer (editors only), here or on the historical sheet.
await expect(
page.getByRole('button', { name: dict['admin.working_copy.create'] }),
).toHaveCount(0)
await expect(areaCard(page, 'admin-access-title')).toHaveCount(0)
await sheets
.getByRole('link', { name: dict['admin.home.all_sheets'] })
.click()
await expect(heading(page, dict['admin.sheets.title'])).toBeVisible()
await expect(
page.getByRole('link', { name: dict['admin.sheets.new'] }),
).toHaveCount(0)
await page.goto('/app/admin/sheets/503dc301-a8b1-50d4-9e44-0919b2fc2916')
await expect(
main(page).getByText(dict['admin.badge.historical'], { exact: true }),
).toBeVisible()
await expect(
page.getByRole('button', { name: dict['admin.working_copy.create'] }),
).toHaveCount(0)
// The rights screen by its address: refused by the server.
await page.goto('/app/admin/access')
await expect(heading(page, dict['access_denied.title'])).toBeVisible()
await signOut(page, dict, info)
const admin = await staff(locale, 'admin', [])
requests.forbid(
admin.account.email,
admin.account.password,
admin.account.displayName,
)
await signIn(page, admin.account, dict)
// No capability: no entry in the navigation; the page by its address.
await expect(
page.getByRole('link', { name: dict['shell.nav.admin'] }),
).toHaveCount(0)
await page.goto('/app/admin')
await stepUpAdmin(page, dict, admin.secret)
await expect(heading(page, dict['shell.nav.admin'])).toBeVisible()
await expect(
main(page).getByText(dict['admin.home.permissions_none'], {
exact: false,
}),
).toBeVisible()
await expect(areaCard(page, 'admin-species-title')).toBeVisible()
await expect(areaCard(page, 'admin-sheets-title')).toHaveCount(0)
await expect(areaCard(page, 'admin-access-title')).toHaveCount(0)
})
test('admin screens: axe and no sideways scroll on every page, desktop and 375 px', async ({
page,
requests,
}) => {
test.setTimeout(180_000)
const { account, secret } = await staff(locale, 'owner', [
'sheet_editor',
'sheet_publisher',
])
requests.forbid(account.email, account.password, account.displayName)
await signIn(page, account, dict)
await page.goto('/app/admin')
await expectAccessible(page, 'the admin step-up')
await expectNoHorizontalOverflow(page, 'the admin step-up')
await stepUpAdmin(page, dict, secret)
const historical = '503dc301-a8b1-50d4-9e44-0919b2fc2916'
const pages: [string, string][] = [
['/app/admin', dict['shell.nav.admin']],
['/app/admin/species', dict['admin.species.title']],
['/app/admin/access', dict['admin.access.title']],
['/app/admin/sheets', dict['admin.sheets.title']],
['/app/admin/sheets/new', dict['admin.sheets.new']],
[`/app/admin/sheets/${historical}`, ''],
]
const width = page.viewportSize()!.width
for (const [path, title] of pages) {
await page.goto(path)
if (title) await expect(heading(page, title)).toBeVisible()
else
await expect(
main(page).getByRole('heading', { level: 1 }),
).toBeVisible()
await page.waitForLoadState('networkidle')
await expectAccessible(page, `${path} at ${width} px`)
await expectNoHorizontalOverflow(page, `${path} at ${width} px`)
}
// The working copy dialog on the historical sheet (W1 start), opened only.
await page
.getByRole('button', { name: dict['admin.working_copy.create'] })
.first()
.click()
const copy = page.getByRole('dialog', {
name: dict['admin.working_copy.create'],
})
await expect(copy).toBeVisible()
await expectAccessible(page, `the working copy dialog at ${width} px`)
await expectNoHorizontalOverflow(
page,
`the working copy dialog at ${width} px`,
)
})
})
}
+297
View File
@@ -0,0 +1,297 @@
import { randomUUID } from 'node:crypto'
import { en } from '@/i18n/en'
import { fr } from '@/i18n/fr'
import type { Dict } from '@/i18n/types'
import type { Page, TestInfo } from '@playwright/test'
import {
expect,
expectAccessible,
expectNoHorizontalOverflow,
test,
} from '../support/browser'
import { seedGrant } from '../support/admin'
import { seedOfficialSheet, type FixtureSheet } from '../support/catalogue'
import {
createAccount,
dropLateReplays,
routeToSandbox,
} from '../support/sandbox'
import { signIn } from '../support/shell'
// V1-2.5 P1 on the isolated stack (contract §11.2, §16.6 Acceptance): the
// catalogue of official sheets read by a catalogue reader, with sheets
// published, archived and left in draft through SQL fixtures (prior owner
// actions); the refusal of an account without access, the same for an
// existing and an unknown sheet. FR and EN, desktop and 320 to 430 px, axe on
// every state, the whole drawing in the box at opening.
const LANGUAGES = [
['fr', fr],
['en', en],
] as const
const PHONE_WIDTHS = [320, 375, 430]
const isPhone = (info: TestInfo) => info.project.name === 'chromium-375'
const tagOf = () => randomUUID().slice(0, 8)
const heading = (page: Page, name: string) =>
page.getByRole('main').getByRole('heading', { level: 1, name })
/** Follows an entry of the shell's navigation: the sidebar, or the drawer on a phone. */
async function navigate(page: Page, dict: Dict, info: TestInfo, key: string) {
if (isPhone(info)) {
await page.getByRole('button', { name: dict['shell.open_menu'] }).click()
await page
.getByRole('dialog', { name: dict['shell.nav_label'] })
.getByRole('navigation')
.getByRole('link', { name: dict[key] })
.click()
} else {
await page
.getByRole('navigation', { name: dict['shell.nav_label'] })
.getByRole('link', { name: dict[key] })
.click()
}
}
const cards = (page: Page, dict: Dict) =>
page
.getByRole('list', { name: dict['catalogue.results'] })
.getByRole('listitem')
/** Sheet names of a test: unique, so the shared catalogue never mixes runs. */
const namesOf = (tag: string, what: string) => ({
fr: `Cheval ${what} ${tag}`,
en: `Horse ${what} ${tag}`,
})
/** The whole composed drawing sits inside the canvas box (no part cut at opening). */
async function expectWholeDrawing(page: Page, state: string) {
const canvas = page.getByTestId('catalogue-canvas')
const svg = page
.getByTestId('catalogue-canvas-drawing')
.locator('svg')
.first()
await expect(svg).toBeVisible()
const [box, drawing] = [await canvas.boundingBox(), await svg.boundingBox()]
expect(box && drawing, `boxes on ${state}`).toBeTruthy()
const inside =
drawing!.x >= box!.x - 1 &&
drawing!.y >= box!.y - 1 &&
drawing!.x + drawing!.width <= box!.x + box!.width + 1 &&
drawing!.y + drawing!.height <= box!.y + box!.height + 1
expect(
inside,
`drawing ${JSON.stringify(drawing)} inside ${JSON.stringify(box)} on ${state}`,
).toBe(true)
expect(drawing!.width, `drawing width on ${state}`).toBeGreaterThan(
box!.width * 0.5,
)
}
async function searchCatalogue(page: Page, dict: Dict, term: string) {
await page
.getByRole('searchbox', { name: dict['catalogue.search'] })
.fill(term)
}
/** Opens a sheet page and waits for its drawing. */
async function openSheet(page: Page, path: string, name: string) {
await page.goto(path)
await expect(heading(page, name)).toBeVisible()
await expect(
page.getByTestId('catalogue-canvas-drawing').locator('svg').first(),
).toBeVisible()
}
for (const [locale, dict] of LANGUAGES) {
test.describe(`catalogue (${locale})`, () => {
test.use({ locale: locale === 'fr' ? 'fr-FR' : 'en-GB' })
test.beforeEach(async ({ context }) => {
await routeToSandbox(context)
})
test.afterEach(async ({ context }) => {
await dropLateReplays(context)
})
test('P1: a reader searches, opens a sheet, picks a zone, reads a retired version; drafts and archives stay out', async ({
page,
requests,
}, info) => {
test.setTimeout(240_000)
const tag = tagOf()
const listed = await seedOfficialSheet(namesOf(tag, 'publié'), 'listed')
const archived = await seedOfficialSheet(
namesOf(tag, 'archivé'),
'archived',
)
const draft = await seedOfficialSheet(namesOf(tag, 'brouillon'), 'draft')
const name = (sheet: FixtureSheet) => sheet.names[locale]
const reader = await createAccount(locale, false)
await seedGrant(reader, 'catalog_reader')
requests.forbid(reader.email, reader.password, reader.displayName, tag)
await signIn(page, reader, dict)
// The entry follows the reader's own grant; no administration entry.
await expect(
page.getByRole('link', { name: dict['shell.nav.admin'] }),
).toHaveCount(0)
await navigate(page, dict, info, 'shell.nav.anatomy')
await expect(page).toHaveURL(/\/app\/anatomy$/)
await expect(heading(page, dict['shell.nav.anatomy'])).toBeVisible()
await expect(cards(page, dict).first()).toBeVisible()
// Search by name: the published sheet only; the draft and the archived one are never listed.
await searchCatalogue(page, dict, tag)
await expect(cards(page, dict)).toHaveCount(1)
await expect(
cards(page, dict).getByRole('heading', { level: 2 }),
).toHaveText(name(listed))
await searchCatalogue(page, dict, name(draft))
await expect(page.getByText(dict['catalogue.no_results'])).toBeVisible()
await searchCatalogue(page, dict, name(archived))
await expect(page.getByText(dict['catalogue.no_results'])).toBeVisible()
await searchCatalogue(page, dict, tag)
const widths = isPhone(info) ? PHONE_WIDTHS : [page.viewportSize()!.width]
for (const width of widths) {
await page.setViewportSize({ width, height: isPhone(info) ? 667 : 800 })
await expectAccessible(page, `the catalogue list at ${width} px`)
await expectNoHorizontalOverflow(
page,
`the catalogue list at ${width} px`,
)
}
await cards(page, dict)
.getByRole('link', {
name: dict['catalogue.view_sheet'].replace('{name}', name(listed)),
})
.click()
await expect(page).toHaveURL(new RegExp(`/app/anatomy/${listed.id}$`))
await expect(heading(page, name(listed))).toBeVisible()
// The current version is v2, published; no admin link for a reader.
await expect(
page.getByText(dict['catalogue.versions.earlier_one']),
).toBeVisible()
await expect(
page.getByText(dict['catalogue.status.deprecated']),
).toHaveCount(0)
await expect(
page.getByRole('link', { name: dict['catalogue.open_admin'] }),
).toHaveCount(0)
for (const width of widths) {
await page.setViewportSize({ width, height: isPhone(info) ? 667 : 800 })
// Opening at this width: the framing is measured on a fresh page.
await openSheet(page, `/app/anatomy/${listed.id}`, name(listed))
await expectWholeDrawing(page, `the sheet page at ${width} px`)
await expectAccessible(page, `the sheet page at ${width} px`)
await expectNoHorizontalOverflow(page, `the sheet page at ${width} px`)
}
// A zone picked on the drawing, then one from the list: its panel shows.
const zone = page.getByRole('combobox', {
name: dict['catalogue.zone.choose'],
})
// A real click where the marker is painted (several nodes carry the id; the top one takes it).
const point = page
.getByTestId('catalogue-canvas-drawing')
.locator(
'circle[data-anno-id="hind-fetlock"][pointer-events="visiblePainted"]',
)
.first()
await point.evaluate((el) => el.scrollIntoView({ block: 'center' }))
const marker = (await point.boundingBox())!
await page.mouse.click(
marker.x + marker.width / 2,
marker.y + marker.height / 2,
)
await expect(zone).toHaveValue('hind-fetlock')
const picked = (await zone.locator('option:checked').textContent()) ?? ''
await expect(
page.getByRole('heading', {
level: 2,
name: dict['catalogue.zone.title'].replace('{name}', picked),
}),
).toBeVisible()
const other = await zone.locator('option').nth(2).getAttribute('value')
await zone.selectOption(other!)
const otherName =
(await zone.locator('option:checked').textContent()) ?? ''
await expect(
page.getByRole('heading', {
level: 2,
name: dict['catalogue.zone.title'].replace('{name}', otherName),
}),
).toBeVisible()
await expectAccessible(page, 'the sheet page with a zone shown')
// The earlier version, retired, opens from the version line with its mark.
await page
.getByRole('button', { name: dict['catalogue.versions.earlier_one'] })
.click()
await page
.getByRole('list', { name: dict['catalogue.versions.title'] })
.getByRole('link', {
name: new RegExp(
`^${dict['catalogue.version'].replace('{number}', '1')}\\b`,
),
})
.click()
await expect(page).toHaveURL(
new RegExp(`/app/anatomy/${listed.id}/versions/1$`),
)
await expect(heading(page, name(listed))).toBeVisible()
await expect(
page
.getByRole('main')
.locator('header')
.getByText(dict['catalogue.status.deprecated'], { exact: true }),
).toBeVisible()
await expectAccessible(page, 'a retired version')
// The archived sheet opens by its address; the draft-only sheet is refused like any other.
await openSheet(page, `/app/anatomy/${archived.id}`, name(archived))
await page.goto(`/app/anatomy/${draft.id}`)
await expect(heading(page, dict['access_denied.title'])).toBeVisible()
})
test('P1: without catalogue access, no entry and the same refusal for an existing and an unknown sheet', async ({
page,
requests,
}) => {
const tag = tagOf()
const listed = await seedOfficialSheet(namesOf(tag, 'refusé'), 'listed')
const account = await createAccount(locale, false)
requests.forbid(account.email, account.password, account.displayName, tag)
await signIn(page, account, dict)
await expect(
page.getByRole('link', { name: dict['shell.nav.anatomy'] }),
).toHaveCount(0)
await expect(
page.getByRole('link', { name: dict['shell.nav.admin'] }),
).toHaveCount(0)
const pages: string[] = []
for (const path of [
'/app/anatomy',
`/app/anatomy/${listed.id}`,
`/app/anatomy/${randomUUID()}`,
]) {
await page.goto(path)
await expect(heading(page, dict['access_denied.title'])).toBeVisible()
await expect(page.getByText(name(listed))).toHaveCount(0)
pages.push(await page.getByRole('main').innerText())
}
// Nothing tells an existing sheet from an unknown one.
expect(pages[2]).toBe(pages[1])
await expectAccessible(page, 'access denied')
await expectNoHorizontalOverflow(page, 'access denied')
function name(sheet: FixtureSheet) {
return sheet.names[locale]
}
})
})
}
+135
View File
@@ -0,0 +1,135 @@
/**
* V1-2.5 setup of the shell suites: platform roles, catalogue rights and TOTP
* factors of the fictitious accounts, written the way the sandbox suites do
* (packages/supabase/tests/sandbox/{sheet-fixtures,mfa}.ts): roles through the
* operator path, grants as postgres, a factor enrolled and verified on the
* real GoTrue with the account's own password session. What a test proves
* goes through the page; the TOTP secrets stay in the test's memory.
*/
import type { Dict } from '@/i18n/types'
import type { Locator, Page } from '@playwright/test'
import {
enrolTotp,
verifyTotp,
} from '../../../../packages/supabase/tests/sandbox/mfa'
import { sql, stack } from '../../../../packages/supabase/tests/sandbox/stack'
import {
totpCode,
TOTP_STEP_SECONDS,
} from '../../../../packages/supabase/tests/sandbox/totp'
import { expect } from './browser'
import type { SandboxAccount } from './sandbox'
export type GrantKind =
| 'catalog_reader'
| 'sheet_editor'
| 'sheet_reviewer'
| 'sheet_publisher'
/** The bootstrap path of the owner role (no JWT), as `private.assign_platform_role` allows postgres. */
export async function assignRole(
account: SandboxAccount,
role: 'owner' | 'admin',
): Promise<void> {
await sql(
`select private.assign_platform_role(null, '${account.id}', '${role}')`,
)
}
/** A right granted earlier by the owner (a prior action, written as postgres). */
export async function seedGrant(
account: SandboxAccount,
kind: GrantKind,
): Promise<void> {
const note = kind === 'catalog_reader' ? 'null' : "'sandbox'"
await sql(`insert into public.anatomical_catalog_grants (user_id, grant_kind, reason, verification_note, granted_by)
values ('${account.id}', '${kind}', 'sandbox', ${note}, '${account.id}')`)
}
/** A password session of the account on GoTrue: always aal1. */
async function passwordToken(account: SandboxAccount): Promise<string> {
const response = await fetch(`${stack.authUrl}/token?grant_type=password`, {
method: 'POST',
headers: { apikey: stack.anonKey, 'Content-Type': 'application/json' },
body: JSON.stringify({ email: account.email, password: account.password }),
})
const body = (await response.json()) as { access_token?: string }
if (!body.access_token)
throw new Error(`sandbox sign-in: HTTP ${response.status}`)
return body.access_token
}
/**
* A verified TOTP factor enrolled by the account itself through the GoTrue
* API (as its authenticator app would be set up); resolves with its secret.
*/
export async function enrolVerifiedFactor(
account: SandboxAccount,
name = 'Téléphone',
): Promise<string> {
const token = await passwordToken(account)
const enrolment = await enrolTotp(token, name)
if (!enrolment.factor)
throw new Error(`sandbox enrol: HTTP ${enrolment.status}`)
const verified = await verifyTotp(token, enrolment.factor)
if (verified.status !== 200)
throw new Error(`sandbox verify: HTTP ${verified.status}`)
return enrolment.factor.secret
}
/**
* A code the authenticator would show now, never one about to change: a code
* typed in its last seconds may reach GoTrue in the next step.
*/
export async function currentCode(secret: string): Promise<string> {
const step = TOTP_STEP_SECONDS * 1000
const left = step - (Date.now() % step)
if (left < 3000)
await new Promise((resolve) => setTimeout(resolve, left + 200))
return totpCode(secret)
}
/** Types a code from `secret` into the TOTP form inside `scope` and sends it. */
export async function enterCode(
scope: Page | Locator,
dict: Dict,
secret: string,
): Promise<void> {
const field = scope.getByLabel(dict['mfa.code.label'])
const code = await currentCode(secret)
await field.fill(code)
await expect(field).toHaveValue(code)
await scope.getByRole('button', { name: dict['mfa.code.verify'] }).click()
}
/** The assurance level of the session the page holds (the access token's `aal` claim). */
export function sessionAal(page: Page): Promise<string | null> {
return page.evaluate(() => {
const key = Object.keys(localStorage).find((k) =>
/^sb-.*-auth-token$/.test(k),
)
const stored = key ? localStorage.getItem(key) : null
if (!stored) return null
const token = (JSON.parse(stored) as { access_token?: string }).access_token
const payload = token?.split('.')[1]
if (!payload) return null
const json = atob(payload.replace(/-/g, '+').replace(/_/g, '/'))
return (JSON.parse(json) as { aal?: string }).aal ?? null
})
}
/** The step-up page of /app/admin/* (RequireAdmin at aal1, with a verified factor). */
export const stepUpHeading = (page: Page, dict: Dict) =>
page
.getByRole('main')
.getByRole('heading', { level: 1, name: dict['admin.step_up.title'] })
/** Completes the administration step-up; the page behind it then renders. */
export async function stepUpAdmin(page: Page, dict: Dict, secret: string) {
const heading = stepUpHeading(page, dict)
await expect(heading).toBeVisible()
// The gate settles its reads before the code is typed (a re-check remounts the form).
await page.waitForLoadState('networkidle')
await enterCode(page.getByRole('main'), dict, secret)
await expect(heading).toBeHidden()
}
+180
View File
@@ -0,0 +1,180 @@
/**
* Official sheets of the catalogue journeys (contract §16.6 Acceptance: « a
* sheet published on the sandbox through SQL fixtures »): prior owner actions
* written as postgres, never through a path the app has. Each sheet carries
* the curated equine draft (document and its stored-form drawing,
* supabase/seed/anatomical-sheets/equine/draft) under names of its own; the
* drawing goes to the private bucket under its content key, and the
* fingerprint of each published or retired version is the core's own,
* computed in Node by the module the page runs (`preview.state`).
*/
import { createHash, randomUUID } from 'node:crypto'
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
import { pathToFileURL } from 'node:url'
import {
CoreRuntime,
parseOutcome,
type GlueModule,
} from '@faunosteo/core-wasm'
import { sql, stack } from '../../../../packages/supabase/tests/sandbox/stack'
import { literal } from './records'
const REPO = join(__dirname, '../../../..')
const SEED = join(REPO, 'supabase/seed/anatomical-sheets/equine/draft')
// The shipped build of the module (`pnpm wasm:build`), the one the page fetches.
const PKG = join(REPO, 'packages/core-wasm/pkg')
const SEED_ASSET = '7f767f74-3b36-51a7-8465-52dd7e2ead4a'
const BUCKET = 'anatomical-sheet-assets'
/** The seed owner (supabase/seed.sql): the actor a content write records. */
const SEED_OWNER = '10000000-0000-0000-0000-000000000001'
export interface SheetNames {
fr: string
en: string
}
export interface FixtureSheet {
id: string
names: SheetNames
}
/**
* The core in this Node process. `@faunosteo/core-wasm/node` reads its own
* location through `import.meta`, which this CommonJS suite cannot load: the
* same source, from the repository root.
*/
async function loadCore(): Promise<CoreRuntime> {
const runtime = new CoreRuntime({
compile: async () =>
WebAssembly.compile(await readFile(join(PKG, 'faunosteo_wasm_bg.wasm'))),
importGlue: async (instance) =>
(await import(
`${pathToFileURL(join(PKG, 'faunosteo_wasm.js')).href}?instance=${instance}`
)) as GlueModule,
})
if (!(await runtime.ready()))
throw new Error('fixture: the core module did not load')
return runtime
}
let runtime: Promise<CoreRuntime> | null = null
const core = () => (runtime ??= loadCore())
async function seedFiles() {
const [drawing, document] = await Promise.all([
readFile(join(SEED, 'assets/horse.svg')),
readFile(join(SEED, 'document.json'), 'utf8'),
])
return {
drawing,
document,
sha: createHash('sha256').update(drawing).digest('hex'),
}
}
/** The equine draft renamed, its drawing re-pointed at the fixture's asset row. */
function documentFor(text: string, asset: string, names: SheetNames): string {
const document = JSON.parse(text.replaceAll(SEED_ASSET, asset)) as Record<
string,
unknown
>
document.name = names
return JSON.stringify(document)
}
/** The fingerprint the core computes for this document and drawing (as at publication). */
async function fingerprintOf(
document: string,
asset: string,
sha: string,
bytes: Buffer,
) {
const loaded = await core()
const state = loaded.invoke<{ fingerprint: string | null }>((glue) => {
const builder = new glue.PreviewBuilder()
builder.add_drawing(asset, sha, new Uint8Array(bytes))
const preview = builder.build(JSON.stringify({ status: 'draft', document }))
try {
return parseOutcome<{ fingerprint: string | null }>(
preview.call('preview.state', '{}'),
)
} finally {
preview.free()
}
})
if (!state.ok || !state.value.fingerprint)
throw new Error(
`fixture fingerprint: ${state.ok ? 'integrity error' : state.kind}`,
)
return state.value.fingerprint
}
/** The drawing under its content key; an object already there (another fixture) is kept. */
async function storeDrawing(sha: string, bytes: Buffer): Promise<void> {
const response = await fetch(
`${stack.storageUrl}/object/${BUCKET}/${sha}.svg`,
{
method: 'POST',
headers: {
Authorization: `Bearer ${stack.serviceKey}`,
'Content-Type': 'image/svg+xml',
},
body: new Uint8Array(bytes),
},
)
const text = await response.text()
if (!response.ok && !/Duplicate|already exists/i.test(text))
throw new Error(`fixture drawing upload: HTTP ${response.status}`)
}
export type SheetShape =
/** Active, v1 retired and v2 published: listed, v2 current. */
| 'listed'
/** Archived after publishing v1: out of the list, readable by id. */
| 'archived'
/** Active with a draft v1 only: never listed, never readable in the catalogue. */
| 'draft'
/** One official equine sheet in `shape`, its versions as an owner's earlier actions left them. */
export async function seedOfficialSheet(
names: SheetNames,
shape: SheetShape,
): Promise<FixtureSheet> {
const { drawing, document: text, sha } = await seedFiles()
await storeDrawing(sha, drawing)
const id = randomUUID()
const asset = randomUUID()
const [v1, v2] = [randomUUID(), randomUUID()]
const document = documentFor(text, asset, names)
const fingerprint =
shape === 'draft'
? null
: await fingerprintOf(document, asset, sha, drawing)
const slug = `e2e-${id.slice(0, 12)}`
const archived = shape === 'archived'
const content = `${literal(document)}::jsonb`
const versions =
shape === 'listed'
? `('${v1}', '${id}', 1, 'deprecated', 2, ${content}, now() - interval '2 days', now(), ${literal(fingerprint)}),
('${v2}', '${id}', 2, 'published', 2, ${content}, now(), null, ${literal(fingerprint)})`
: shape === 'archived'
? `('${v1}', '${id}', 1, 'published', 2, ${content}, now(), null, ${literal(fingerprint)})`
: `('${v1}', '${id}', 1, 'draft', 2, ${content}, null, null, null)`
const current =
shape === 'listed' ? `'${v2}'` : shape === 'archived' ? `'${v1}'` : 'null'
await sql(`begin;
select set_config('request.jwt.claims', '{"sub":"${SEED_OWNER}"}', true);
insert into public.anatomical_sheets (id, species_id, name, slug, is_official, visibility, status, archived_at)
values ('${id}', 'equine', ${literal(names.fr)}, '${slug}', true, 'private',
'${archived ? 'archived' : 'active'}', ${archived ? 'now()' : 'null'});
insert into public.anatomical_sheet_assets (id, sheet_id, sha256, byte_size, file_name, uploaded_at)
values ('${asset}', '${id}', '${sha}', ${drawing.length}, 'horse.svg', now());
insert into public.anatomical_sheet_versions (id, sheet_id, version_number, status, document_schema_version, content,
published_at, deprecated_at, document_fingerprint)
values ${versions};
update public.anatomical_sheets set current_version_id = ${current},
last_version_number = ${shape === 'listed' ? 2 : 1} where id = '${id}';
commit;`)
return { id, names }
}