test(supabase): V1-2.1 re-runnable sandbox suite, two-session cases, caps timing
F18 and workspaces no longer leave the seed owner changed. Ten two-session scenarios with a blocking session, seed-owner AR-1 acceptance, shim columns against the image, save/submit/approve/publish timed at the caps.
This commit is contained in:
1 parent
d05f75da84
commit
ef1f4b593f
10 files changed
+930
-65
No files matched your search
@@ -4,8 +4,8 @@
|
||||
* user's own access token, as the browser does. TOTP secrets and tokens stay
|
||||
* in memory and are never printed.
|
||||
*/
|
||||
import { stack } from './stack'
|
||||
import { msToNextStep, totpCode } from './totp'
|
||||
import { stack, type Account } from './stack'
|
||||
import { totpCode } from './totp'
|
||||
|
||||
export interface Factor {
|
||||
id: string
|
||||
@@ -77,20 +77,27 @@ export async function verifyTotp(
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify with a code of a step not used before for this factor: GoTrue refuses
|
||||
* a code it already accepted, so a second verification waits for the next step.
|
||||
*/
|
||||
export async function verifyTotpFreshStep(
|
||||
/** Enrols and verifies a TOTP factor from `token`, returning the new aal2 access token. */
|
||||
export async function stepUp(
|
||||
token: string,
|
||||
factor: Factor,
|
||||
): Promise<MfaResult> {
|
||||
await new Promise((resolve) => setTimeout(resolve, msToNextStep() + 200))
|
||||
return verifyTotp(token, factor)
|
||||
name = 'device',
|
||||
): Promise<string> {
|
||||
const enrol = await enrolTotp(token, name)
|
||||
if (!enrol.factor)
|
||||
throw new Error(`enrol failed: ${JSON.stringify(enrol.body)}`)
|
||||
const verified = await verifyTotp(token, enrol.factor)
|
||||
const aal2 = verified.body.access_token as string
|
||||
if (!aal2) throw new Error(`verify failed: ${JSON.stringify(verified.body)}`)
|
||||
return aal2
|
||||
}
|
||||
|
||||
export function unenrol(token: string, factorId: string): Promise<MfaResult> {
|
||||
return authRequest('DELETE', `/factors/${factorId}`, token)
|
||||
/** A confirmed account signed in, with one verified factor and its aal2 token. */
|
||||
export interface SteppedAccount extends Account {
|
||||
aal2: string
|
||||
}
|
||||
|
||||
export async function steppedUp(account: Account): Promise<SteppedAccount> {
|
||||
return { ...account, aal2: await stepUp(account.token) }
|
||||
}
|
||||
|
||||
/** The claims of an access token (payload only; the signature is not checked here). */
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
/**
|
||||
* V1-2.1 acceptance of AR-1 B on the seed owner (contract §16.2 "a stack
|
||||
* upgraded from the DEV state with an owner holding two verified factors keeps
|
||||
* working at aal2 and is refused at aal1; the same upgrade with an owner
|
||||
* holding none stays usable at aal1 for everything but role and rights
|
||||
* management"), with real GoTrue. Meant for the stack of `pnpm db:sandbox up
|
||||
* upgrade` (the DEV path); it holds on a fresh stack too. The seed owner's
|
||||
* factors and sessions made here are removed afterwards (as postgres), so the
|
||||
* owner is back to no factor and the suite runs again on the same stack.
|
||||
*/
|
||||
import { confirmedAccount, errorCode, rest, rpc, signIn, sql } from './stack'
|
||||
import { claimsOf, enrolTotp, stepUp, verifyTotp } from './mfa'
|
||||
|
||||
const OWNER = '10000000-0000-0000-0000-000000000001'
|
||||
const OWNER_EMAIL = 'owner@faunosteo.local'
|
||||
const OWNER_PASSWORD = 'LocalDev-only-password-1'
|
||||
const FACTOR_PREFIX = 'seed-owner-test'
|
||||
|
||||
const passwordSession = async (): Promise<string> => {
|
||||
const session = await signIn(OWNER_EMAIL, OWNER_PASSWORD)
|
||||
return session.body.access_token as string
|
||||
}
|
||||
const refusal = (result: { status: number; body: unknown }) =>
|
||||
[result.status, (result.body as { message?: string }).message]
|
||||
|
||||
describe('AR-1 B on the seed owner (§16.2)', () => {
|
||||
let target = { id: '' }
|
||||
|
||||
beforeAll(async () => {
|
||||
// Factors left by an interrupted run of this file are removed first.
|
||||
await sql(`delete from auth.mfa_factors where user_id = '${OWNER}' and friendly_name like '${FACTOR_PREFIX}%'`)
|
||||
expect(await sql(`select count(*) from auth.mfa_factors where user_id = '${OWNER}'`)).toBe('0')
|
||||
expect(await sql(`select count(*) from public.profile_roles where user_id = '${OWNER}' and role = 'owner' and revoked_at is null`)).toBe('1')
|
||||
const account = await confirmedAccount('seed-owner-target')
|
||||
await stepUp(account.token)
|
||||
target = account
|
||||
}, 60_000)
|
||||
|
||||
afterAll(async () => {
|
||||
await sql(`delete from auth.mfa_factors where user_id = '${OWNER}' and friendly_name like '${FACTOR_PREFIX}%'`)
|
||||
await sql(`delete from auth.sessions where user_id = '${OWNER}'`)
|
||||
if (target.id) await sql(`delete from auth.users where id = '${target.id}'`)
|
||||
})
|
||||
|
||||
it('without a factor: usable at aal1, refused only for roles and rights', async () => {
|
||||
const token = await passwordSession()
|
||||
expect(claimsOf(token).aal).toBe('aal1')
|
||||
expect((await rest(`/profiles?select=id&id=eq.${OWNER}`, token)).body).toEqual([{ id: OWNER }])
|
||||
expect(((await rest('/workspaces?select=id', token)).body as unknown[]).length).toBe(1)
|
||||
expect(((await rest('/species?select=id', token)).body as unknown[]).length).toBeGreaterThan(0)
|
||||
expect(refusal(await rpc('grant_platform_role', { target_user_id: target.id, role: 'support' }, token)))
|
||||
.toEqual([403, 'mfa_required'])
|
||||
expect(refusal(await rpc('list_catalog_grants', {}, token))).toEqual([403, 'rights.mfa'])
|
||||
expect(refusal(await rpc('grant_catalog_right', { user_id: target.id, kind: 'catalog_reader', reason: 'x' }, token)))
|
||||
.toEqual([403, 'rights.mfa'])
|
||||
}, 60_000)
|
||||
|
||||
it('with two verified factors: works at aal2 and is refused at aal1', async () => {
|
||||
// First factor from the aal1 session (no verified factor yet), second from aal2 (§5.7.1, §5.7.3).
|
||||
const aal1 = await passwordSession()
|
||||
const first = await enrolTotp(aal1, `${FACTOR_PREFIX}-1`)
|
||||
expect(first.status).toBe(200)
|
||||
let aal2 = (await verifyTotp(aal1, first.factor!)).body.access_token as string
|
||||
expect(claimsOf(aal2).aal).toBe('aal2')
|
||||
const second = await enrolTotp(aal2, `${FACTOR_PREFIX}-2`)
|
||||
expect(second.status).toBe(200)
|
||||
aal2 = (await verifyTotp(aal2, second.factor!)).body.access_token as string
|
||||
expect(await sql(`select count(*) from auth.mfa_factors where user_id = '${OWNER}' and status = 'verified'`)).toBe('2')
|
||||
|
||||
const grant = await rpc('grant_platform_role', { target_user_id: target.id, role: 'support' }, aal2)
|
||||
expect(grant.status).toBe(200)
|
||||
expect((await rpc('revoke_platform_role', { target_user_id: target.id, role: 'support', reason: 'test' }, aal2)).status).toBe(200)
|
||||
expect((await rpc('list_catalog_grants', {}, aal2)).status).toBe(200)
|
||||
|
||||
// A new password sign-in starts at aal1: refused, whatever the factors.
|
||||
const again = await passwordSession()
|
||||
expect(claimsOf(again).aal).toBe('aal1')
|
||||
const refused = await rpc('grant_platform_role', { target_user_id: target.id, role: 'support' }, again)
|
||||
expect([refused.status, errorCode(refused), (refused.body as { message?: string }).message]).toEqual([403, '42501', 'mfa_required'])
|
||||
expect(refusal(await rpc('list_catalog_grants', {}, again))).toEqual([403, 'rights.mfa'])
|
||||
// And that aal1 session cannot add a third factor (§5.7.3).
|
||||
expect((await enrolTotp(again, `${FACTOR_PREFIX}-3`)).status).toBe(403)
|
||||
}, 60_000)
|
||||
})
|
||||
@@ -0,0 +1,198 @@
|
||||
/**
|
||||
* Fixtures of the V1-2.1 sheet suites on the throwaway stack (real GoTrue,
|
||||
* PostgREST, Storage and PostgreSQL): accounts at aal2 holding a platform role
|
||||
* and catalogue rights, an official sheet whose drawing goes through the
|
||||
* Storage INSERT policy, the verdict written by a postgres session standing in
|
||||
* for the worker of M6 (contract §12.2), and a blocking session that makes two
|
||||
* calls queue on one lock in a known order (contract §15, two sessions).
|
||||
*/
|
||||
import { createHash, randomUUID } from 'node:crypto'
|
||||
import { confirmedAccount, rpc, sql, stack, type RestResult } from './stack'
|
||||
import { steppedUp, type SteppedAccount } from './mfa'
|
||||
|
||||
export type GrantKind = 'catalog_reader' | 'sheet_editor' | 'sheet_reviewer' | 'sheet_publisher'
|
||||
|
||||
/** A confirmed account at aal2 with an optional platform role and catalogue rights (written as postgres). */
|
||||
export async function holder(
|
||||
tag: string,
|
||||
role: 'owner' | 'admin' | null,
|
||||
grants: GrantKind[],
|
||||
): Promise<SteppedAccount> {
|
||||
const account = await steppedUp(await confirmedAccount(tag))
|
||||
if (role) await sql(`select private.assign_platform_role(null, '${account.id}', '${role}')`)
|
||||
for (const kind of grants)
|
||||
await sql(`insert into public.anatomical_catalog_grants (user_id, grant_kind, reason, verification_note, granted_by)
|
||||
values ('${account.id}', '${kind}', 'sandbox', ${kind === 'catalog_reader' ? 'null' : "'sandbox'"}, '${account.id}')`)
|
||||
return account
|
||||
}
|
||||
|
||||
/** The message (closed code) of a refused call, or null for a success. */
|
||||
export const message = (result: RestResult): string | null =>
|
||||
result.status === 200 ? null : ((result.body as { message?: string }).message ?? result.text)
|
||||
|
||||
/** The body of a successful call; throws with the answer otherwise. */
|
||||
export function ok(result: RestResult): unknown {
|
||||
if (result.status !== 200) throw new Error(`HTTP ${result.status}: ${result.text}`)
|
||||
return result.body
|
||||
}
|
||||
|
||||
/** A one-view, one-zone document whose three status-bearing elements are reviewed. */
|
||||
export function sheetDoc(asset: string | null, description = 'd'): Record<string, unknown> {
|
||||
const name = (fr: string) => ({ fr, en: fr })
|
||||
return {
|
||||
schema_version: 2,
|
||||
species_id: 'equine',
|
||||
name: name('Cheval sandbox'),
|
||||
description: name(description),
|
||||
scope_disclaimer: name('x'),
|
||||
attribution: { authors: ['F'], license: null, notes: null },
|
||||
vertebral_config: { regions: [] },
|
||||
references: [],
|
||||
categories: [{ id: 'c', name: name('C'), color: null }],
|
||||
views: [{ id: 'main', kind: 'main', name: name('V'), svg_asset_id: asset, view_box: null }],
|
||||
annotations: [{
|
||||
id: 'a1', kind: 'point', view_id: 'main', category_id: 'c', laterality: 'unpaired', geometry: null,
|
||||
review_status: 'reviewed', name: name('P'), finding_zone_id: 'z1', vertebral_region_code: null,
|
||||
}],
|
||||
finding_zones: [{
|
||||
id: 'z1', name: name('Z'),
|
||||
categories: [{
|
||||
id: 'cat', kind: 'dysfunction', name: name('D'), review_status: 'reviewed',
|
||||
children: [{ id: 'n1', name: name('N'), review_status: 'reviewed' }],
|
||||
}],
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
/** A distinct small SVG drawing of about `size` bytes. */
|
||||
export function drawing(size = 200): Buffer {
|
||||
const head = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><!-- ${randomUUID()} `
|
||||
const tail = ' --><rect width="10" height="10"/></svg>'
|
||||
return Buffer.from(head + 'x'.repeat(Math.max(0, size - head.length - tail.length)) + tail)
|
||||
}
|
||||
|
||||
export const sha256 = (bytes: Buffer): string => createHash('sha256').update(bytes).digest('hex')
|
||||
|
||||
/** Uploads `bytes` under their content key through the Storage API; the INSERT policy decides. */
|
||||
export async function upload(token: string, bytes: Buffer): Promise<number> {
|
||||
const res = await fetch(`${stack.storageUrl}/object/anatomical-sheet-assets/${sha256(bytes)}.svg`, {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'image/svg+xml' },
|
||||
body: new Uint8Array(bytes),
|
||||
})
|
||||
await res.arrayBuffer()
|
||||
return res.status
|
||||
}
|
||||
|
||||
export interface Sheet {
|
||||
id: string
|
||||
draft: string
|
||||
asset: string
|
||||
sha: string
|
||||
}
|
||||
|
||||
/** An official sheet by `editor`: drawing registered, uploaded and confirmed, draft saved reviewed (revision 1). */
|
||||
export async function officialSheet(editor: SteppedAccount, bytes = drawing()): Promise<Sheet> {
|
||||
const slug = `sb-${randomUUID().slice(0, 12)}`
|
||||
const id = ok(await rpc('create_official_sheet', { slug, document: sheetDoc(null) }, editor.aal2)) as string
|
||||
const draft = await sql(`select id from public.anatomical_sheet_versions where sheet_id = '${id}' and status = 'draft'`)
|
||||
const sha = sha256(bytes)
|
||||
const asset = ok(await rpc('register_sheet_asset',
|
||||
{ sheet_id: id, sha256: sha, byte_size: bytes.length, file_name: 'd.svg' }, editor.aal2)) as string
|
||||
const uploaded = await upload(editor.aal2, bytes)
|
||||
if (uploaded !== 200) throw new Error(`upload: HTTP ${uploaded}`)
|
||||
ok(await rpc('confirm_sheet_asset_upload', { asset_id: asset }, editor.aal2))
|
||||
ok(await rpc('save_sheet_draft',
|
||||
{ version_id: draft, expected_revision: 0, document: sheetDoc(asset), change_note: 'wire' }, editor.aal2))
|
||||
return { id, draft, asset, sha }
|
||||
}
|
||||
|
||||
export const GROUP_KEYS = ['general', 'view:main', 'zone:z1']
|
||||
|
||||
/** The worker's stand-in: a passing verdict on the round, which opens (§6.4). */
|
||||
export async function openRound(review: string, sheet: Sheet): Promise<void> {
|
||||
const verdict = {
|
||||
fingerprint: 'a'.repeat(64),
|
||||
drawings: [{ asset_id: sheet.asset, sha256: sheet.sha }],
|
||||
groups: GROUP_KEYS.map((key) => ({ key, digest: '1'.repeat(64), coverable: true })),
|
||||
}
|
||||
await sql(`update public.anatomical_sheet_reviews set status = 'open', verified_at = now(), verified_with = 'sandbox',
|
||||
verdict = '${JSON.stringify(verdict)}'::jsonb where id = '${review}'`)
|
||||
}
|
||||
|
||||
/** `editor` submits the draft at `revision`, the round opens, `reviewer` acknowledges every group. */
|
||||
export async function openRoundAcknowledged(
|
||||
editor: SteppedAccount,
|
||||
reviewer: SteppedAccount,
|
||||
sheet: Sheet,
|
||||
revision = 1,
|
||||
): Promise<string> {
|
||||
const review = ok(await rpc('submit_sheet_review',
|
||||
{ version_id: sheet.draft, expected_revision: revision, note: 'round' }, editor.aal2)) as string
|
||||
await openRound(review, sheet)
|
||||
for (const key of GROUP_KEYS)
|
||||
ok(await rpc('acknowledge_sheet_review_group',
|
||||
{ review_id: review, group_key: key, group_digest: '1'.repeat(64) }, reviewer.aal2))
|
||||
return review
|
||||
}
|
||||
|
||||
/** As openRoundAcknowledged, then `reviewer` approves. */
|
||||
export async function approvedRound(
|
||||
editor: SteppedAccount,
|
||||
reviewer: SteppedAccount,
|
||||
sheet: Sheet,
|
||||
revision = 1,
|
||||
): Promise<string> {
|
||||
const review = await openRoundAcknowledged(editor, reviewer, sheet, revision)
|
||||
ok(await rpc('decide_sheet_review', { review_id: review, approve: true, note: 'ok' }, reviewer.aal2))
|
||||
return review
|
||||
}
|
||||
|
||||
/** Polls `query` (a boolean select) until it answers true. */
|
||||
async function until(query: string, what: string, timeoutMs = 10_000): Promise<void> {
|
||||
const end = Date.now() + timeoutMs
|
||||
while (Date.now() < end) {
|
||||
if ((await sql(query)) === 't') return
|
||||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||||
}
|
||||
throw new Error(`timeout waiting for ${what}`)
|
||||
}
|
||||
|
||||
/** Once a session named `tag` sleeps (it holds its lock). */
|
||||
export const sessionHolds = (tag: string) =>
|
||||
until(`select exists (select 1 from pg_stat_activity where application_name = '${tag}'
|
||||
and wait_event = 'PgSleep')`, `${tag} to hold its lock`)
|
||||
|
||||
/** Once a session named `tag` waits on a lock. */
|
||||
export const sessionWaits = (tag: string) =>
|
||||
until(`select exists (select 1 from pg_stat_activity where application_name = '${tag}'
|
||||
and wait_event_type = 'Lock')`, `${tag} to wait on a lock`)
|
||||
|
||||
/** Once `n` API calls of `fn` wait on a lock. */
|
||||
export const callsWait = (fn: string, n = 1) =>
|
||||
until(`select count(*) >= ${n} from pg_stat_activity where wait_event_type = 'Lock'
|
||||
and query like '%${fn}%' and application_name not like 'sandbox-%'`, `${n} ${fn} call(s) to queue`)
|
||||
|
||||
/** A postgres session named `tag` running `body` (statements) inside one transaction. */
|
||||
export const session = (tag: string, body: string): Promise<string> =>
|
||||
sql(`set application_name = '${tag}'; begin; ${body}; commit;`)
|
||||
|
||||
export type Call = [fn: string, run: () => Promise<RestResult>]
|
||||
|
||||
/**
|
||||
* Holds `lock` in a blocking session, fires `first` and waits until it queues,
|
||||
* fires `second` and waits until it queues too, then lets the lock go: the two
|
||||
* calls meet the contended lock in that order. Fails if either call does not
|
||||
* queue (the lock it should take is not the one held).
|
||||
*/
|
||||
export async function inOrder(lock: string, first: Call, second: Call): Promise<[RestResult, RestResult]> {
|
||||
const tag = `sandbox-blocker-${randomUUID().slice(0, 8)}`
|
||||
const blocker = session(tag, `${lock}; select pg_sleep(3)`)
|
||||
await sessionHolds(tag)
|
||||
const a = first[1]()
|
||||
await callsWait(first[0])
|
||||
const b = second[1]()
|
||||
await callsWait(second[0], first[0] === second[0] ? 2 : 1)
|
||||
await blocker
|
||||
return Promise.all([a, b])
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
/**
|
||||
* V1-2.1 two-session scenarios on the real stack (contract §15: two saves,
|
||||
* save against submit, publish against withdraw, two publishers, deprecate
|
||||
* against publish, completion against withdrawal), plus archive against
|
||||
* approve (§6.7, audit M1), two deprecations of one sheet (§6.1), two working
|
||||
* copies (§14.3) and revoke against grant (§5.7). Each case holds the lock the
|
||||
* two calls compete for in a blocking session, makes both calls queue behind
|
||||
* it in a known order (checked in pg_stat_activity), lets go, and asserts the
|
||||
* outcome of that serial order; both orders are run where they differ. The
|
||||
* worker of M6 does not exist yet: the verdict and the completion are written
|
||||
* by a postgres session standing in for it (§12.2). Run through
|
||||
* `pnpm db:sandbox test tests/sandbox/sheets-concurrency.sandbox.ts`.
|
||||
*/
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { rpc, sql, stack } from './stack'
|
||||
import type { SteppedAccount } from './mfa'
|
||||
import {
|
||||
approvedRound,
|
||||
holder,
|
||||
inOrder,
|
||||
message,
|
||||
ok,
|
||||
openRound,
|
||||
openRoundAcknowledged,
|
||||
officialSheet,
|
||||
session,
|
||||
sessionHolds,
|
||||
sessionWaits,
|
||||
callsWait,
|
||||
sheetDoc,
|
||||
type Sheet,
|
||||
} from './sheet-fixtures'
|
||||
import { repoRoot } from '../db/harness'
|
||||
|
||||
const HISTORICAL = '503dc301-a8b1-50d4-9e44-0919b2fc2916'
|
||||
|
||||
let E: SteppedAccount
|
||||
let E2: SteppedAccount
|
||||
let V: SteppedAccount
|
||||
|
||||
beforeAll(async () => {
|
||||
E = await holder('cc-editor', 'admin', ['sheet_editor', 'sheet_publisher'])
|
||||
E2 = await holder('cc-editor2', 'admin', ['sheet_editor', 'sheet_publisher'])
|
||||
V = await holder('cc-reviewer', null, ['sheet_reviewer'])
|
||||
}, 120_000)
|
||||
|
||||
const lockVersion = (s: Sheet) => `select 1 from public.anatomical_sheet_versions where id = '${s.draft}' for update`
|
||||
const lockSheet = (id: string) => `select 1 from public.anatomical_sheets where id = '${id}' for update`
|
||||
const save = (who: SteppedAccount, s: Sheet, revision: number, text: string) => () =>
|
||||
rpc('save_sheet_draft', { version_id: s.draft, expected_revision: revision, document: sheetDoc(s.asset, text), change_note: text }, who.aal2)
|
||||
const submit = (who: SteppedAccount, s: Sheet, revision: number) => () =>
|
||||
rpc('submit_sheet_review', { version_id: s.draft, expected_revision: revision, note: 'r' }, who.aal2)
|
||||
const publish = (who: SteppedAccount, review: string) => () => rpc('publish_sheet_version', { review_id: review }, who.aal2)
|
||||
const withdraw = (who: SteppedAccount, review: string) => () => rpc('withdraw_sheet_review', { review_id: review, note: 'w' }, who.aal2)
|
||||
const deprecate = (who: SteppedAccount, version: string) => () =>
|
||||
rpc('deprecate_sheet_version', { version_id: version, reason: 'c' }, who.aal2)
|
||||
const roundStatus = (review: string) => sql(`select status from public.anatomical_sheet_reviews where id = '${review}'`)
|
||||
const versionStatus = (version: string) => sql(`select status from public.anatomical_sheet_versions where id = '${version}'`)
|
||||
const currentOf = (sheet: string) => sql(`select coalesce(current_version_id::text, 'none') from public.anatomical_sheets where id = '${sheet}'`)
|
||||
|
||||
/** A sheet with v1 published through a round and v2 drafted from it, approved (same digests: covered by the base). */
|
||||
async function publishedThenApprovedDraft(): Promise<{ s: Sheet; v1: string; v2: Sheet; r2: string }> {
|
||||
const s = await officialSheet(E)
|
||||
ok(await publish(E, await approvedRound(E, V, s))())
|
||||
const v2draft = ok(await rpc('create_sheet_draft', { sheet_id: s.id, from_version_id: null, change_note: 'v2' }, E.aal2)) as string
|
||||
const v2 = { ...s, draft: v2draft }
|
||||
ok(await save(E, v2, 0, 'v2')())
|
||||
const r2 = ok(await submit(E, v2, 1)()) as string
|
||||
await openRound(r2, v2)
|
||||
ok(await rpc('decide_sheet_review', { review_id: r2, approve: true, note: 'ok' }, V.aal2))
|
||||
return { s, v1: s.draft, v2, r2 }
|
||||
}
|
||||
|
||||
describe('two saves (§6.2)', () => {
|
||||
it('the first save in line wins, the second answers draft_conflict and overwrites nothing', async () => {
|
||||
const s = await officialSheet(E)
|
||||
const [a, b] = await inOrder(lockVersion(s), ['save_sheet_draft', save(E, s, 1, 'first')], ['save_sheet_draft', save(E2, s, 1, 'second')])
|
||||
expect([a.status, message(b)]).toEqual([200, 'draft_conflict'])
|
||||
expect(await sql(`select revision || ' ' || (content -> 'description' ->> 'fr') from public.anatomical_sheet_versions where id = '${s.draft}'`))
|
||||
.toBe('2 first')
|
||||
}, 60_000)
|
||||
})
|
||||
|
||||
describe('save against submit (§6.1, §6.2)', () => {
|
||||
it('save first: the submission of the old revision answers draft_conflict', async () => {
|
||||
const s = await officialSheet(E)
|
||||
const [a, b] = await inOrder(lockVersion(s), ['save_sheet_draft', save(E, s, 1, 'edit')], ['submit_sheet_review', submit(E2, s, 1)])
|
||||
expect([a.status, message(b)]).toEqual([200, 'draft_conflict'])
|
||||
expect(await sql(`select count(*) from public.anatomical_sheet_reviews where version_id = '${s.draft}'`)).toBe('0')
|
||||
}, 60_000)
|
||||
|
||||
it('submit first: the save answers draft.frozen and the round keeps its revision', async () => {
|
||||
const s = await officialSheet(E)
|
||||
const [a, b] = await inOrder(lockVersion(s), ['submit_sheet_review', submit(E, s, 1)], ['save_sheet_draft', save(E2, s, 1, 'late')])
|
||||
expect([a.status, message(b)]).toEqual([200, 'draft.frozen'])
|
||||
expect(await sql(`select r.revision || ' ' || v.revision from public.anatomical_sheet_reviews r
|
||||
join public.anatomical_sheet_versions v on v.id = r.version_id where r.id = '${a.body}'`)).toBe('1 1')
|
||||
}, 60_000)
|
||||
})
|
||||
|
||||
describe('publish against withdraw (§6.1, §6.8)', () => {
|
||||
it('publish first: the round of the published version is never withdrawn', async () => {
|
||||
const s = await officialSheet(E)
|
||||
const r = await approvedRound(E, V, s)
|
||||
const [a, b] = await inOrder(lockVersion(s), ['publish_sheet_version', publish(E, r)], ['withdraw_sheet_review', withdraw(E2, r)])
|
||||
expect([a.status, message(b)]).toEqual([200, 'draft.not_a_draft'])
|
||||
expect([await versionStatus(s.draft), await roundStatus(r)]).toEqual(['published', 'approved'])
|
||||
}, 60_000)
|
||||
|
||||
it('withdraw first: the publication finds no approved round', async () => {
|
||||
const s = await officialSheet(E)
|
||||
const r = await approvedRound(E, V, s)
|
||||
const [a, b] = await inOrder(lockVersion(s), ['withdraw_sheet_review', withdraw(E2, r)], ['publish_sheet_version', publish(E, r)])
|
||||
expect([a.status, message(b)]).toEqual([200, 'publish.review.missing'])
|
||||
expect([await versionStatus(s.draft), await roundStatus(r)]).toEqual(['draft', 'withdrawn'])
|
||||
}, 60_000)
|
||||
})
|
||||
|
||||
describe('two publishers (§6.8)', () => {
|
||||
it('one publication only: the second publisher answers draft.not_a_draft', async () => {
|
||||
const s = await officialSheet(E)
|
||||
const r = await approvedRound(E, V, s)
|
||||
const [a, b] = await inOrder(lockSheet(s.id), ['publish_sheet_version', publish(E, r)], ['publish_sheet_version', publish(E2, r)])
|
||||
expect([a.status, message(b)]).toEqual([200, 'draft.not_a_draft'])
|
||||
expect(await sql(`select published_by || ' ' || (select count(*) from audit.audit_logs
|
||||
where action = 'anatomical_sheet_version.published' and resource_id = '${s.draft}')
|
||||
from public.anatomical_sheet_versions where id = '${s.draft}'`)).toBe(`${E.id} 1`)
|
||||
}, 60_000)
|
||||
})
|
||||
|
||||
describe('deprecate against publish (§6.9)', () => {
|
||||
it('deprecate first: the new version becomes current', async () => {
|
||||
const { s, v1, v2, r2 } = await publishedThenApprovedDraft()
|
||||
const [a, b] = await inOrder(lockSheet(s.id), ['deprecate_sheet_version', deprecate(E, v1)], ['publish_sheet_version', publish(E2, r2)])
|
||||
expect([a.status, b.status]).toEqual([200, 200])
|
||||
expect([await currentOf(s.id), await versionStatus(v1), await versionStatus(v2.draft)]).toEqual([v2.draft, 'deprecated', 'published'])
|
||||
}, 120_000)
|
||||
|
||||
it('publish first: the deprecation of the old version keeps the new one current', async () => {
|
||||
const { s, v1, v2, r2 } = await publishedThenApprovedDraft()
|
||||
const [a, b] = await inOrder(lockSheet(s.id), ['publish_sheet_version', publish(E2, r2)], ['deprecate_sheet_version', deprecate(E, v1)])
|
||||
expect([a.status, b.status]).toEqual([200, 200])
|
||||
expect([await currentOf(s.id), await versionStatus(v1), await versionStatus(v2.draft)]).toEqual([v2.draft, 'deprecated', 'published'])
|
||||
}, 120_000)
|
||||
})
|
||||
|
||||
describe('two deprecations of one sheet (§6.1, §6.9)', () => {
|
||||
it('serialised on the sheet: the current version never names a deprecated one', async () => {
|
||||
const { s, v1, r2 } = await publishedThenApprovedDraft()
|
||||
const v2 = (await sql(`select version_id from public.anatomical_sheet_reviews where id = '${r2}'`))
|
||||
ok(await publish(E, r2)())
|
||||
const [a, b] = await inOrder(lockSheet(s.id), ['deprecate_sheet_version', deprecate(E, v2)], ['deprecate_sheet_version', deprecate(E2, v1)])
|
||||
expect([a.status, b.status]).toEqual([200, 200])
|
||||
expect([await currentOf(s.id), await versionStatus(v1), await versionStatus(v2)]).toEqual(['none', 'deprecated', 'deprecated'])
|
||||
}, 120_000)
|
||||
})
|
||||
|
||||
describe('completion against withdrawal (§6.4, §6.5)', () => {
|
||||
// The completion the worker will run (M6): lock the round while it is
|
||||
// verifying, write the verdict and open it; a round no longer verifying is
|
||||
// left alone. Returns 'updated' when it wrote.
|
||||
const completion = (review: string, s: Sheet, pause: string) => `
|
||||
select id from public.anatomical_sheet_reviews where id = '${review}' and status = 'verifying' for update;
|
||||
${pause};
|
||||
update public.anatomical_sheet_reviews set status = 'open', verified_at = now(), verified_with = 'stand-in',
|
||||
verdict = '${JSON.stringify({ fingerprint: 'a'.repeat(64), drawings: [{ asset_id: s.asset, sha256: s.sha }], groups: [] })}'::jsonb
|
||||
where id = '${review}' and status = 'verifying' returning 'updated'`
|
||||
|
||||
it('completion first: the withdrawal waits, then withdraws the opened round; the draft unfreezes', async () => {
|
||||
const s = await officialSheet(E)
|
||||
const r = ok(await submit(E, s, 1)()) as string
|
||||
const tag = `sandbox-worker-${randomUUID().slice(0, 8)}`
|
||||
const worker = session(tag, completion(r, s, 'select pg_sleep(2)'))
|
||||
await sessionHolds(tag)
|
||||
const w = withdraw(E2, r)()
|
||||
await callsWait('withdraw_sheet_review')
|
||||
expect(await worker).toContain('updated')
|
||||
expect((await w).status).toBe(200)
|
||||
expect([await roundStatus(r), await sql(`select verdict is not null from public.anatomical_sheet_reviews where id = '${r}'`)])
|
||||
.toEqual(['withdrawn', 't'])
|
||||
expect((await save(E, s, 1, 'after')()).status).toBe(200)
|
||||
}, 60_000)
|
||||
|
||||
it('withdrawal first: the completion finds no verifying round and writes nothing', async () => {
|
||||
const s = await officialSheet(E)
|
||||
const r = ok(await submit(E, s, 1)()) as string
|
||||
const blockerTag = `sandbox-blocker-${randomUUID().slice(0, 8)}`
|
||||
const blocker = session(blockerTag, `select 1 from public.anatomical_sheet_reviews where id = '${r}' for update; select pg_sleep(3)`)
|
||||
await sessionHolds(blockerTag)
|
||||
const w = withdraw(E2, r)()
|
||||
await callsWait('withdraw_sheet_review')
|
||||
const tag = `sandbox-worker-${randomUUID().slice(0, 8)}`
|
||||
const worker = session(tag, completion(r, s, 'select 1'))
|
||||
await sessionWaits(tag)
|
||||
await blocker
|
||||
expect((await w).status).toBe(200)
|
||||
expect(await worker).not.toContain('updated')
|
||||
expect([await roundStatus(r), await sql(`select verdict is null from public.anatomical_sheet_reviews where id = '${r}'`)])
|
||||
.toEqual(['withdrawn', 't'])
|
||||
expect((await save(E, s, 1, 'after')()).status).toBe(200)
|
||||
}, 60_000)
|
||||
})
|
||||
|
||||
describe('archive against approve (§6.7, audit M1)', () => {
|
||||
it('archive first: the approval answers sheet.inactive and the round stays open', async () => {
|
||||
const s = await officialSheet(E)
|
||||
const r = await openRoundAcknowledged(E, V, s)
|
||||
const [a, b] = await inOrder(lockSheet(s.id),
|
||||
['archive_anatomical_sheet', () => rpc('archive_anatomical_sheet', { sheet_id: s.id }, E.aal2)],
|
||||
['decide_sheet_review', () => rpc('decide_sheet_review', { review_id: r, approve: true, note: 'ok' }, V.aal2)])
|
||||
expect([a.status, message(b)]).toEqual([200, 'sheet.inactive'])
|
||||
expect(await roundStatus(r)).toBe('open')
|
||||
}, 60_000)
|
||||
|
||||
it('approve first: the approval happened on an active sheet, the archive follows', async () => {
|
||||
const s = await officialSheet(E)
|
||||
const r = await openRoundAcknowledged(E, V, s)
|
||||
const [a, b] = await inOrder(lockSheet(s.id),
|
||||
['decide_sheet_review', () => rpc('decide_sheet_review', { review_id: r, approve: true, note: 'ok' }, V.aal2)],
|
||||
['archive_anatomical_sheet', () => rpc('archive_anatomical_sheet', { sheet_id: s.id }, E.aal2)])
|
||||
expect([a.status, b.status]).toEqual([200, 200])
|
||||
expect(await roundStatus(r)).toBe('approved')
|
||||
}, 60_000)
|
||||
})
|
||||
|
||||
describe('two working copies of the historical sheet (§14.3)', () => {
|
||||
let setAside: string[] = []
|
||||
const created: string[] = []
|
||||
|
||||
beforeAll(async () => {
|
||||
// The historical drawing confirmed by the operator path, as on DEV (§9.5):
|
||||
// the object written with the service key, the row confirmed by the
|
||||
// service role. Done once per stack; a confirmed row is left as it is.
|
||||
const row = (await sql(`select id || ' ' || sha256 || ' ' || (uploaded_at is null)::text from public.anatomical_sheet_assets
|
||||
where sheet_id = '${HISTORICAL}'`)).split(' ')
|
||||
if (row[2] === 'true') {
|
||||
const bytes = await readFile(join(repoRoot, 'supabase/seed/anatomical-sheets/equine/draft/assets/horse.svg'))
|
||||
const res = await fetch(`${stack.storageUrl}/object/anatomical-sheet-assets/${row[1]}.svg`, {
|
||||
method: 'POST', headers: { Authorization: `Bearer ${stack.serviceKey}`, 'Content-Type': 'image/svg+xml' }, body: new Uint8Array(bytes),
|
||||
})
|
||||
expect([200, 409]).toContain(res.status)
|
||||
ok(await rpc('confirm_sheet_asset_upload', { asset_id: row[0] }, stack.serviceKey))
|
||||
}
|
||||
// A copy left active by an earlier run is set aside and put back after.
|
||||
setAside = (await sql(`update public.anatomical_sheets set status = 'archived', archived_at = now()
|
||||
where status = 'active' and private.is_historical_working_copy(id) returning id`))
|
||||
.split('\n').filter(Boolean)
|
||||
}, 60_000)
|
||||
|
||||
afterAll(async () => {
|
||||
for (const id of created) await rpc('archive_anatomical_sheet', { sheet_id: id }, E.aal2)
|
||||
if (setAside.length > 0)
|
||||
await sql(`update public.anatomical_sheets set status = 'active', archived_at = null
|
||||
where id in (${setAside.map((id) => `'${id}'`).join(', ')})`)
|
||||
})
|
||||
|
||||
it('serialised on the historical sheet row: one copy, the other answers working_copy.exists', async () => {
|
||||
const source = await sql(`select id from public.anatomical_sheet_versions where sheet_id = '${HISTORICAL}'`)
|
||||
const copy = (who: SteppedAccount) => () =>
|
||||
rpc('create_sheet_working_copy', { source_version_id: source, slug: `wc-${randomUUID().slice(0, 12)}` }, who.aal2)
|
||||
const [a, b] = await inOrder(`select 1 from public.anatomical_sheets where id = '${HISTORICAL}' for no key update`,
|
||||
['create_sheet_working_copy', copy(E)], ['create_sheet_working_copy', copy(E2)])
|
||||
if (a.status === 200) created.push(a.body as string)
|
||||
if (b.status === 200) created.push(b.body as string)
|
||||
expect([a.status, message(b)]).toEqual([200, 'working_copy.exists'])
|
||||
}, 60_000)
|
||||
})
|
||||
|
||||
describe('revoke against grant of platform roles (§5.7, F18)', () => {
|
||||
const lock = `select pg_advisory_xact_lock(hashtextextended('faunosteo.platform_roles', 0))`
|
||||
let accounts: SteppedAccount[] = []
|
||||
|
||||
afterAll(async () => {
|
||||
if (accounts.length > 0) await sql(`delete from auth.users where id in (${accounts.map((a) => `'${a.id}'`).join(', ')})`)
|
||||
})
|
||||
|
||||
it('revoke first: the revoked owner can no longer grant', async () => {
|
||||
const a = await holder('rg-a', 'owner', [])
|
||||
const b = await holder('rg-b', 'owner', [])
|
||||
const c = await holder('rg-c', null, [])
|
||||
accounts = accounts.concat([a, b, c])
|
||||
const [revoke, grant] = await inOrder(lock,
|
||||
['revoke_platform_role', () => rpc('revoke_platform_role', { target_user_id: b.id, role: 'owner', reason: 'race' }, a.aal2)],
|
||||
['grant_platform_role', () => rpc('grant_platform_role', { target_user_id: c.id, role: 'support' }, b.aal2)])
|
||||
expect([revoke.status, grant.status, message(grant)]).toEqual([200, 403, 'forbidden'])
|
||||
expect(await sql(`select count(*) from public.profile_roles where user_id = '${c.id}' and revoked_at is null`)).toBe('0')
|
||||
}, 60_000)
|
||||
|
||||
it('grant first: the grant was made by an owner, then the revocation applies', async () => {
|
||||
const a = await holder('rg-a', 'owner', [])
|
||||
const b = await holder('rg-b', 'owner', [])
|
||||
const c = await holder('rg-c', null, [])
|
||||
accounts = accounts.concat([a, b, c])
|
||||
const [grant, revoke] = await inOrder(lock,
|
||||
['grant_platform_role', () => rpc('grant_platform_role', { target_user_id: c.id, role: 'support' }, b.aal2)],
|
||||
['revoke_platform_role', () => rpc('revoke_platform_role', { target_user_id: b.id, role: 'owner', reason: 'race' }, a.aal2)])
|
||||
expect([grant.status, revoke.status]).toEqual([200, 200])
|
||||
expect(await sql(`select string_agg(role::text, ',') from public.profile_roles where user_id = '${c.id}' and revoked_at is null`))
|
||||
.toBe('support')
|
||||
}, 60_000)
|
||||
})
|
||||
@@ -0,0 +1,214 @@
|
||||
/**
|
||||
* V1-2.1 timing at the caps on the real stack (contract §15: "save, submit and
|
||||
* publish under 2 s each", measured in V1-2.1, fixed at the V1-2.3
|
||||
* checkpoint), after the independent audit (M4).
|
||||
*
|
||||
* The core's at-caps fixture belongs to V1-2.2, which has not started. This
|
||||
* suite builds an equivalent document for what SQL does with one: the
|
||||
* structural guards, the 2 MiB serialised size, the status walk at approval
|
||||
* and publication, the group coverage, the drawing checks. It reaches every
|
||||
* cap those depend on: 64 views (one main, three with their own drawing, the
|
||||
* rest crops), 1 024 annotations, 8 192 finding nodes counting categories
|
||||
* (1 024 zones, each a category and a chain of seven nodes: depth 8), four
|
||||
* drawings near 2 MiB, labels sized so the document is as close to 2 MiB as
|
||||
* the stricter of PostgreSQL's two measures allows (its text, which the save
|
||||
* guard reads, and its stored jsonb, which the table CHECK reads), every status
|
||||
* `reviewed`, a verdict of 1 089 groups (general, 64 views, 1 024 zones). The
|
||||
* core never parses it (SQL holds no business rule, §12.2), so it says nothing
|
||||
* about the verifier's 120 s budget, which V1-2.3 measures.
|
||||
*
|
||||
* Every call is timed over HTTP as the page would make it (PostgREST, real
|
||||
* GoTrue aal2 token). Run through `pnpm db:sandbox test tests/sandbox/sheets-perf.sandbox.ts`.
|
||||
*/
|
||||
import { performance } from 'node:perf_hooks'
|
||||
import { rpc, sql } from './stack'
|
||||
import type { SteppedAccount } from './mfa'
|
||||
import { drawing, holder, ok, sha256, upload } from './sheet-fixtures'
|
||||
|
||||
const BUDGET_MS = 2000
|
||||
const DOC_CAP = 2_097_152
|
||||
const VIEWS = 64
|
||||
const ANNOTATIONS = 1024
|
||||
const ZONES = 1024
|
||||
const CHAIN = 7
|
||||
|
||||
/** The at-caps document; `variant` changes one text so each save differs. */
|
||||
function capsDocument(assets: string[], labelLength: number, variant: number): Record<string, unknown> {
|
||||
const text = (base: string) => (base + ' ').padEnd(labelLength, 'x')
|
||||
const name = (base: string) => ({ fr: text(`${base} fr`), en: text(`${base} en`) })
|
||||
const views = Array.from({ length: VIEWS }, (_, i) =>
|
||||
i === 0
|
||||
? { id: 'main', kind: 'main', name: name('main'), svg_asset_id: assets[0], view_box: null }
|
||||
: i < 4
|
||||
? { id: `v${i}`, kind: 'detail', parent_view_id: 'main', name: name(`v${i}`), svg_asset_id: assets[i], view_box: null }
|
||||
: { id: `v${i}`, kind: 'detail', parent_view_id: 'main', name: name(`v${i}`), svg_asset_id: null,
|
||||
view_box: { min_x: i, min_y: i, width: 100, height: 80 } })
|
||||
const node = (zone: number, level: number): Record<string, unknown> => ({
|
||||
id: `n${level}`, name: name(`z${zone} n${level}`), review_status: 'reviewed', requires_vet_referral: level === CHAIN,
|
||||
reference_ids: level === 1 ? ['r0'] : [],
|
||||
...(level < CHAIN ? { children: [node(zone, level + 1)] } : {}),
|
||||
})
|
||||
return {
|
||||
schema_version: 2,
|
||||
species_id: 'equine',
|
||||
name: name(`caps ${variant}`),
|
||||
description: name('caps document'),
|
||||
scope_disclaimer: { fr: 'x'.repeat(500), en: 'y'.repeat(480) },
|
||||
attribution: { authors: ['Sandbox'], license: null, notes: null },
|
||||
vertebral_config: { regions: ['C', 'T', 'L', 'S', 'Cd'].map((code, i) => ({ code, name: name(code), count: 5 + i })) },
|
||||
references: Array.from({ length: 64 }, (_, i) => ({ id: `r${i}`, type: 'manual', citation: text(`reference ${i}`), url: null, doi: null })),
|
||||
categories: Array.from({ length: 8 }, (_, i) => ({ id: `c${i}`, name: name(`c${i}`), color: '#123456' })),
|
||||
views,
|
||||
annotations: Array.from({ length: ANNOTATIONS }, (_, i) => ({
|
||||
id: `a${i}`, kind: i % 4 === 0 ? 'zone' : 'point', view_id: views[i % VIEWS].id, category_id: `c${i % 8}`,
|
||||
laterality: 'unpaired',
|
||||
geometry: i % 4 === 0
|
||||
? { type: 'polygon', points: [[i, 1], [i + 5, 2], [i + 9, 7], [i + 3, 9]] }
|
||||
: { type: 'circle', cx: i, cy: i, r: 5 },
|
||||
review_status: 'reviewed', name: name(`a${i}`), finding_zone_id: `z${i % ZONES}`, vertebral_region_code: null,
|
||||
})),
|
||||
finding_zones: Array.from({ length: ZONES }, (_, z) => ({
|
||||
id: `z${z}`, name: name(`z${z}`),
|
||||
categories: [{ id: 'cat', kind: 'dysfunction', name: name(`z${z} cat`), review_status: 'reviewed', children: [node(z, 1)] }],
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The two sizes PostgreSQL gives the document: its text (`octet_length`, the
|
||||
* contract's measure) and its stored jsonb (`pg_column_size`, the table's
|
||||
* CHECK). A document of many small objects is larger as jsonb, so that one binds.
|
||||
*/
|
||||
const pgSizes = async (doc: Record<string, unknown>) => {
|
||||
const [text, jsonb] = (await sql(`select octet_length(d::text) || ' ' || pg_column_size(d)
|
||||
from (select $caps$${JSON.stringify(doc)}$caps$::jsonb d) x`)).split(' ').map(Number)
|
||||
return { text, jsonb }
|
||||
}
|
||||
|
||||
/** The largest label length whose document stays under both measures (with 4 KiB for the variants). */
|
||||
async function calibrate(assets: string[]): Promise<number> {
|
||||
let low = 1
|
||||
let high = 200
|
||||
while (low < high) {
|
||||
const mid = Math.ceil((low + high) / 2)
|
||||
const size = await pgSizes(capsDocument(assets, mid, 0))
|
||||
if (Math.max(size.text, size.jsonb) <= DOC_CAP - 4096) low = mid
|
||||
else high = mid - 1
|
||||
}
|
||||
return low
|
||||
}
|
||||
|
||||
async function timed(call: () => Promise<{ status: number; text: string }>): Promise<number> {
|
||||
const start = performance.now()
|
||||
const result = await call()
|
||||
const ms = performance.now() - start
|
||||
if (result.status !== 200) throw new Error(`HTTP ${result.status}: ${result.text.slice(0, 300)}`)
|
||||
return ms
|
||||
}
|
||||
|
||||
const stats = (samples: number[]) => {
|
||||
const sorted = [...samples].sort((a, b) => a - b)
|
||||
return {
|
||||
n: sorted.length,
|
||||
min: Math.round(sorted[0]),
|
||||
median: Math.round(sorted[Math.floor(sorted.length / 2)]),
|
||||
max: Math.round(sorted[sorted.length - 1]),
|
||||
}
|
||||
}
|
||||
|
||||
describe('timing at the caps (§15)', () => {
|
||||
let E: SteppedAccount
|
||||
let V: SteppedAccount
|
||||
const samples: Record<string, number[]> = { save: [], submit: [], approve: [], publish: [] }
|
||||
|
||||
beforeAll(async () => {
|
||||
E = await holder('perf-editor', 'admin', ['sheet_editor', 'sheet_publisher'])
|
||||
V = await holder('perf-reviewer', null, ['sheet_reviewer'])
|
||||
}, 120_000)
|
||||
|
||||
it('saves, submits, approves and publishes an at-caps document within the budget', async () => {
|
||||
// The sheet and its four drawings near 2 MiB, uploaded through the INSERT policy.
|
||||
const sheet = ok(await rpc('create_official_sheet',
|
||||
{ slug: `perf-${Date.now().toString(36)}`, document: { ...capsDocument([null, null, null, null] as unknown as string[], 8, 0) } },
|
||||
E.aal2)) as string
|
||||
const draft = await sql(`select id from public.anatomical_sheet_versions where sheet_id = '${sheet}' and status = 'draft'`)
|
||||
const assets: string[] = []
|
||||
const shas: string[] = []
|
||||
for (let i = 0; i < 4; i++) {
|
||||
const bytes = drawing(2_000_000)
|
||||
const asset = ok(await rpc('register_sheet_asset',
|
||||
{ sheet_id: sheet, sha256: sha256(bytes), byte_size: bytes.length, file_name: `d${i}.svg` }, E.aal2)) as string
|
||||
expect(await upload(E.aal2, bytes)).toBe(200)
|
||||
ok(await rpc('confirm_sheet_asset_upload', { asset_id: asset }, E.aal2))
|
||||
assets.push(asset)
|
||||
shas.push(sha256(bytes))
|
||||
}
|
||||
const labelLength = await calibrate(assets)
|
||||
const docSize = await pgSizes(capsDocument(assets, labelLength, 1))
|
||||
let revision = Number(await sql(`select revision from public.anatomical_sheet_versions where id = '${draft}'`))
|
||||
let version = draft
|
||||
let variant = 0
|
||||
|
||||
const save = async () => {
|
||||
variant += 1
|
||||
samples.save.push(await timed(() => rpc('save_sheet_draft',
|
||||
{ version_id: version, expected_revision: revision, document: capsDocument(assets, labelLength, variant), change_note: 'caps' }, E.aal2)))
|
||||
revision += 1
|
||||
}
|
||||
const submit = async () => {
|
||||
const start = performance.now()
|
||||
const result = await rpc('submit_sheet_review', { version_id: version, expected_revision: revision, note: 'caps' }, E.aal2)
|
||||
samples.submit.push(performance.now() - start)
|
||||
return ok(result) as string
|
||||
}
|
||||
// The verdict of the worker's stand-in: 1 089 groups, the four drawings.
|
||||
const groups = ['general', ...Array.from({ length: VIEWS }, (_, i) => (i === 0 ? 'view:main' : `view:v${i}`)),
|
||||
...Array.from({ length: ZONES }, (_, z) => `zone:z${z}`)]
|
||||
const open = (review: string) => sql(`update public.anatomical_sheet_reviews set status = 'open', verified_at = now(),
|
||||
verified_with = 'sandbox', verdict = '${JSON.stringify({
|
||||
fingerprint: 'a'.repeat(64),
|
||||
drawings: assets.map((asset_id, i) => ({ asset_id, sha256: shas[i] })),
|
||||
groups: groups.map((key) => ({ key, digest: sha256(Buffer.from(key)), coverable: true })),
|
||||
})}'::jsonb where id = '${review}'`)
|
||||
const approveAndPublish = async (review: string) => {
|
||||
samples.approve.push(await timed(() => rpc('decide_sheet_review', { review_id: review, approve: true, note: 'caps' }, V.aal2)))
|
||||
samples.publish.push(await timed(() => rpc('publish_sheet_version', { review_id: review }, E.aal2)))
|
||||
}
|
||||
|
||||
// Cycle 1, no base: five saves, three submissions (two withdrawn), every
|
||||
// group acknowledged by the reviewer, approval, publication.
|
||||
for (let i = 0; i < 5; i++) await save()
|
||||
for (let i = 0; i < 2; i++) ok(await rpc('withdraw_sheet_review', { review_id: await submit(), note: 'again' }, E.aal2))
|
||||
const first = await submit()
|
||||
await open(first)
|
||||
await sql(`insert into public.anatomical_sheet_review_acknowledgments (review_id, group_key, group_digest, reviewer)
|
||||
select '${first}', g ->> 'key', g ->> 'digest', '${V.id}'
|
||||
from public.anatomical_sheet_reviews r, jsonb_array_elements(r.verdict -> 'groups') g where r.id = '${first}'`)
|
||||
await approveAndPublish(first)
|
||||
|
||||
// Cycles 2 and 3: a new draft on the published base, one save, one
|
||||
// submission, the same digests (covered by the base), approval, publication.
|
||||
for (let cycle = 0; cycle < 2; cycle++) {
|
||||
version = ok(await rpc('create_sheet_draft', { sheet_id: sheet, from_version_id: null, change_note: 'next' }, E.aal2)) as string
|
||||
revision = 0
|
||||
await save()
|
||||
const review = await submit()
|
||||
await open(review)
|
||||
await approveAndPublish(review)
|
||||
}
|
||||
ok(await rpc('archive_anatomical_sheet', { sheet_id: sheet }, E.aal2))
|
||||
|
||||
const report = {
|
||||
document: { textBytes: docSize.text, jsonbBytes: docSize.jsonb, cap: DOC_CAP, labelLength, views: VIEWS, annotations: ANNOTATIONS,
|
||||
findingNodes: ZONES * (CHAIN + 1), depth: CHAIN + 1, groups: groups.length, drawings: 4, drawingBytes: 2_000_000 },
|
||||
budgetMs: BUDGET_MS,
|
||||
save: stats(samples.save), submit: stats(samples.submit), approve: stats(samples.approve), publish: stats(samples.publish),
|
||||
}
|
||||
console.info(`AT-CAPS TIMING ${JSON.stringify(report)}`)
|
||||
expect(Math.max(docSize.text, docSize.jsonb)).toBeGreaterThan(DOC_CAP - 64 * 1024)
|
||||
expect(Math.max(docSize.text, docSize.jsonb)).toBeLessThanOrEqual(DOC_CAP)
|
||||
for (const op of ['save', 'submit', 'publish'])
|
||||
expect(Math.max(...samples[op]), `${op} at the caps`).toBeLessThan(BUDGET_MS)
|
||||
}, 600_000)
|
||||
})
|
||||
|
||||
@@ -6,17 +6,7 @@
|
||||
* `pnpm db:sandbox test tests/sandbox/sheets.sandbox.ts`.
|
||||
*/
|
||||
import { confirmedAccount, rpc, sql, errorCode, type Account } from './stack'
|
||||
import { enrolTotp, verifyTotp, claimsOf } from './mfa'
|
||||
|
||||
/** Enrols and verifies a TOTP factor, returning a fresh aal2 access token. */
|
||||
async function stepUp(account: Account): Promise<string> {
|
||||
const enrol = await enrolTotp(account.token, 'device')
|
||||
if (!enrol.factor) throw new Error(`enrol failed: ${JSON.stringify(enrol.body)}`)
|
||||
const verified = await verifyTotp(account.token, enrol.factor)
|
||||
const token = verified.body.access_token as string
|
||||
if (!token) throw new Error(`verify failed: ${JSON.stringify(verified.body)}`)
|
||||
return token
|
||||
}
|
||||
import { claimsOf, stepUp } from './mfa'
|
||||
|
||||
describe('AR-1 B on real GoTrue', () => {
|
||||
let owner: Account
|
||||
@@ -29,8 +19,8 @@ describe('AR-1 B on real GoTrue', () => {
|
||||
// Bootstrap the owner role through the operator path (no JWT).
|
||||
await sql(`select private.assign_platform_role(null, '${owner.id}', 'owner')`)
|
||||
// The target holds a verified factor (a grant needs one).
|
||||
await stepUp(target)
|
||||
ownerAal2 = await stepUp(owner)
|
||||
await stepUp(target.token)
|
||||
ownerAal2 = await stepUp(owner.token)
|
||||
}, 120_000)
|
||||
|
||||
it('refuses a platform role change from the aal1 session', async () => {
|
||||
@@ -63,29 +53,37 @@ describe('last-owner race (F18)', () => {
|
||||
it('two concurrent revocations of two owners leave one owner', async () => {
|
||||
const a = await confirmedAccount('f18-a')
|
||||
const b = await confirmedAccount('f18-b')
|
||||
const aAal2 = await stepUp(a)
|
||||
const bAal2 = await stepUp(b)
|
||||
const aAal2 = await stepUp(a.token)
|
||||
const bAal2 = await stepUp(b.token)
|
||||
await sql(`select private.assign_platform_role(null, '${a.id}', 'owner')`)
|
||||
await sql(`select private.assign_platform_role(null, '${b.id}', 'owner')`)
|
||||
// Neutralise every other owner so a and b are the only two.
|
||||
await sql(`update public.profile_roles set revoked_at = now(), revoke_reason = 'f18 test'
|
||||
where role = 'owner' and revoked_at is null and user_id not in ('${a.id}', '${b.id}')`)
|
||||
expect(await sql(`select count(*) from public.profile_roles where role = 'owner' and revoked_at is null`)).toBe('2')
|
||||
// Every other owner (the seed owner included) is set aside for the race and
|
||||
// put back afterwards, whatever the outcome, so the suite runs again on the
|
||||
// same stack (V1-2.1 audit M5).
|
||||
const setAside = (await sql(`update public.profile_roles set revoked_at = now(), revoke_reason = 'f18 test'
|
||||
where role = 'owner' and revoked_at is null and user_id not in ('${a.id}', '${b.id}')
|
||||
returning id`)).split('\n').filter(Boolean)
|
||||
try {
|
||||
expect(await sql(`select count(*) from public.profile_roles where role = 'owner' and revoked_at is null`)).toBe('2')
|
||||
|
||||
// Each revokes the other, concurrently.
|
||||
const [ra, rb] = await Promise.all([
|
||||
rpc('revoke_platform_role', { target_user_id: b.id, role: 'owner', reason: 'race a' }, aAal2),
|
||||
rpc('revoke_platform_role', { target_user_id: a.id, role: 'owner', reason: 'race b' }, bAal2),
|
||||
])
|
||||
const statuses = [ra.status, rb.status]
|
||||
// The invariant that F18 broke: the two cannot both pass and leave zero
|
||||
// owners. Exactly one succeeds; the other is refused (last_owner when it
|
||||
// reaches the guard, or forbidden when it lost its own ownership first);
|
||||
// one owner always remains.
|
||||
expect(statuses.filter((s) => s === 200), JSON.stringify([ra.body, rb.body])).toHaveLength(1)
|
||||
expect(statuses.filter((s) => s !== 200)).toHaveLength(1)
|
||||
expect(await sql(`select count(*) from public.profile_roles where role = 'owner' and revoked_at is null`)).toBe('1')
|
||||
|
||||
await sql(`delete from auth.users where id in ('${a.id}', '${b.id}')`)
|
||||
// Each revokes the other, concurrently.
|
||||
const [ra, rb] = await Promise.all([
|
||||
rpc('revoke_platform_role', { target_user_id: b.id, role: 'owner', reason: 'race a' }, aAal2),
|
||||
rpc('revoke_platform_role', { target_user_id: a.id, role: 'owner', reason: 'race b' }, bAal2),
|
||||
])
|
||||
const statuses = [ra.status, rb.status]
|
||||
// The invariant that F18 broke: the two cannot both pass and leave zero
|
||||
// owners. Exactly one succeeds; the other is refused (last_owner when it
|
||||
// reaches the guard, or forbidden when it lost its own ownership first);
|
||||
// one owner always remains.
|
||||
expect(statuses.filter((s) => s === 200), JSON.stringify([ra.body, rb.body])).toHaveLength(1)
|
||||
expect(statuses.filter((s) => s !== 200)).toHaveLength(1)
|
||||
expect(await sql(`select count(*) from public.profile_roles where role = 'owner' and revoked_at is null`)).toBe('1')
|
||||
} finally {
|
||||
await sql(`delete from auth.users where id in ('${a.id}', '${b.id}')`)
|
||||
if (setAside.length > 0)
|
||||
await sql(`update public.profile_roles set revoked_at = null, revoked_by = null, revoke_reason = null
|
||||
where id in (${setAside.map((id) => `'${id}'`).join(', ')})`)
|
||||
}
|
||||
}, 120_000)
|
||||
})
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* The PGlite shim's stand-ins for `auth.sessions` and `auth.mfa_factors`
|
||||
* (packages/supabase/tests/db/supabase-shim.sql) against the pinned GoTrue
|
||||
* image of the sandbox (contract §15: "columns checked against the pinned
|
||||
* image"). Every shim column exists on the image with the same type and
|
||||
* nullability, every NOT NULL column of the image without a default is in the
|
||||
* shim, and the three enums carry the same labels. So the aal2 checks that
|
||||
* pgTAP runs on PGlite read the same shape as on the real stack.
|
||||
*/
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { PGlite } from '@electric-sql/pglite'
|
||||
import { sql } from './stack'
|
||||
|
||||
const TABLES = ['sessions', 'mfa_factors']
|
||||
const ENUMS = ['aal_level', 'factor_type', 'factor_status']
|
||||
const COLUMNS = `select table_name || '.' || column_name || ':' || udt_name || ':' || is_nullable
|
||||
|| ':' || (column_default is not null) as line
|
||||
from information_schema.columns
|
||||
where table_schema = 'auth' and table_name in ('sessions', 'mfa_factors')
|
||||
order by table_name, column_name`
|
||||
const LABELS = `select t.typname || ':' || string_agg(e.enumlabel, ',' order by e.enumsortorder) as line
|
||||
from pg_type t join pg_enum e on e.enumtypid = t.oid join pg_namespace n on n.oid = t.typnamespace
|
||||
where n.nspname = 'auth' and t.typname in ('aal_level', 'factor_type', 'factor_status')
|
||||
group by t.typname order by t.typname`
|
||||
|
||||
type Column = { key: string; type: string; nullable: string; hasDefault: string }
|
||||
const parse = (line: string): Column => {
|
||||
const [key, type, nullable, hasDefault] = line.split(':')
|
||||
return { key, type, nullable, hasDefault }
|
||||
}
|
||||
|
||||
describe('PGlite shim against the pinned image', () => {
|
||||
let shim: PGlite
|
||||
|
||||
beforeAll(async () => {
|
||||
shim = await PGlite.create()
|
||||
await shim.exec(await readFile(fileURLToPath(new URL('../db/supabase-shim.sql', import.meta.url)), 'utf8'))
|
||||
}, 60_000)
|
||||
|
||||
afterAll(async () => {
|
||||
await shim?.close()
|
||||
})
|
||||
|
||||
const shimLines = async (query: string) => (await shim.query<{ line: string }>(query)).rows.map((r) => r.line)
|
||||
|
||||
it('every shim column matches the image, and the image needs no column the shim lacks', async () => {
|
||||
const image = (await sql(COLUMNS)).split('\n').filter(Boolean).map(parse)
|
||||
const own = (await shimLines(COLUMNS)).map(parse)
|
||||
expect(own.length).toBeGreaterThan(0)
|
||||
const imageByKey = new Map(image.map((c) => [c.key, c]))
|
||||
for (const c of own) {
|
||||
expect(imageByKey.get(c.key), `${c.key} on the image`).toBeDefined()
|
||||
expect([c.key, imageByKey.get(c.key)!.type, imageByKey.get(c.key)!.nullable]).toEqual([c.key, c.type, c.nullable])
|
||||
}
|
||||
const ownKeys = new Set(own.map((c) => c.key))
|
||||
const required = image.filter((c) => c.nullable === 'NO' && c.hasDefault === 'false').map((c) => c.key)
|
||||
expect(required.filter((key) => !ownKeys.has(key))).toEqual([])
|
||||
expect(TABLES.every((t) => own.some((c) => c.key.startsWith(`${t}.`)))).toBe(true)
|
||||
})
|
||||
|
||||
it('the three enums carry the image labels', async () => {
|
||||
const image = (await sql(LABELS)).split('\n').filter(Boolean)
|
||||
const own = await shimLines(LABELS)
|
||||
expect(own).toEqual(image)
|
||||
expect(own.map((line) => line.split(':')[0])).toEqual([...ENUMS].sort())
|
||||
})
|
||||
})
|
||||
@@ -19,6 +19,7 @@ export const stack = {
|
||||
container: need('SANDBOX_DB_CONTAINER'),
|
||||
authUrl: need('SANDBOX_AUTH_URL'),
|
||||
restUrl: need('SANDBOX_REST_URL'),
|
||||
storageUrl: need('SANDBOX_STORAGE_URL'),
|
||||
mailUrl: need('SANDBOX_MAIL_URL'),
|
||||
anonKey: need('SANDBOX_ANON_KEY'),
|
||||
serviceKey: need('SANDBOX_SERVICE_KEY'),
|
||||
|
||||
@@ -38,8 +38,3 @@ export function totpCode(secret: string, at = Date.now()): string {
|
||||
return value.toString().padStart(6, '0')
|
||||
}
|
||||
|
||||
/** Milliseconds until the next step starts (a fresh code). */
|
||||
export function msToNextStep(at = Date.now()): number {
|
||||
const step = TOTP_STEP_SECONDS * 1000
|
||||
return step - (at % step)
|
||||
}
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
sqlOutcome,
|
||||
stack,
|
||||
} from './stack'
|
||||
import { enrolTotp, verifyTotp } from './mfa'
|
||||
import { stepUp } from './mfa'
|
||||
import {
|
||||
uniqueEmail,
|
||||
type Account,
|
||||
@@ -197,18 +197,14 @@ describe('reads and refusals per role', () => {
|
||||
})
|
||||
|
||||
it('stores an oversized correlation header as null and keeps a short token', async () => {
|
||||
// AR-1 B: the role RPCs need a live aal2 session and a factored target, so
|
||||
// the seed owner steps up and b enrols a factor before the grant.
|
||||
const owner = await signIn(
|
||||
'owner@faunosteo.local',
|
||||
'LocalDev-only-password-1',
|
||||
)
|
||||
const ownerToken = owner.body.access_token as string
|
||||
const ownerEnrol = await enrolTotp(ownerToken, 'owner device')
|
||||
const token = (await verifyTotp(ownerToken, ownerEnrol.factor!)).body
|
||||
.access_token as string
|
||||
const bEnrol = await enrolTotp(b.token, 'b device')
|
||||
await verifyTotp(b.token, bEnrol.factor!)
|
||||
// AR-1 B: the role RPCs need a live aal2 session and a factored target. An
|
||||
// owner of this test's own (factor first, role last, as §5.7.1 orders it)
|
||||
// grants the role, so the seed owner is never touched and the suite runs
|
||||
// again on the same stack.
|
||||
const owner = await confirmedAccount('ws-owner')
|
||||
const token = await stepUp(owner.token, 'owner device')
|
||||
await sql(`select private.assign_platform_role(null, '${owner.id}', 'owner')`)
|
||||
await stepUp(b.token, 'b device')
|
||||
const grant = await rpc(
|
||||
'grant_platform_role',
|
||||
{ target_user_id: b.id, role: 'support' },
|
||||
@@ -230,6 +226,7 @@ describe('reads and refusals per role', () => {
|
||||
await sql(`select string_agg(coalesce(correlation_id, 'NULL'), '|' order by occurred_at, action)
|
||||
from audit.audit_logs where target_user_id = '${b.id}'`),
|
||||
).toBe('NULL|req-sandbox-01')
|
||||
await sql(`delete from auth.users where id = '${owner.id}'`)
|
||||
})
|
||||
|
||||
it('deletes an empty account through GoTrue admin with its workspace', async () => {
|
||||
|
||||
Reference in new issue
Block a user