feat(supabase): MFA, species, rights, admin and catalogue access layer (V1-2.5 D)
mfa.ts (closed kinds, TOTP list incl. unverified, enrol, verify, unenrol, assurance); sheets.ts wrappers for species, working copy, account lookup, M7 reads, versions list, drawing download, own grants, with shape parsers. Unit 148, sandbox sheets-admin 5/5 x2.
This commit is contained in:
1 parent
a79e1f0af7
commit
c9ace9aff2
7 files changed
+1126
-6
No files matched your search
@@ -0,0 +1,124 @@
|
||||
import {
|
||||
MfaFailure,
|
||||
assuranceLevel,
|
||||
classifyMfaError,
|
||||
enrollTotp,
|
||||
listTotpFactors,
|
||||
unenrollFactor,
|
||||
verifyTotp,
|
||||
type FaunosteoClient,
|
||||
} from '../src'
|
||||
|
||||
/**
|
||||
* TOTP wrappers over supabase-js `auth.mfa`: call shapes, the factor list
|
||||
* (unverified factors included) and the closed failure kinds. The same
|
||||
* functions run against real GoTrue in tests/sandbox/sheets-admin.sandbox.ts.
|
||||
*/
|
||||
type Result = { data?: unknown; error?: unknown }
|
||||
|
||||
function stubMfa(results: Record<string, Result> = {}) {
|
||||
const calls: Array<[string, unknown]> = []
|
||||
const method = (name: string) => async (params?: unknown) => {
|
||||
calls.push([name, params])
|
||||
return { data: results[name]?.data ?? null, error: results[name]?.error ?? null }
|
||||
}
|
||||
const client = {
|
||||
auth: {
|
||||
mfa: {
|
||||
listFactors: method('listFactors'),
|
||||
enroll: method('enroll'),
|
||||
challengeAndVerify: method('challengeAndVerify'),
|
||||
unenroll: method('unenroll'),
|
||||
getAuthenticatorAssuranceLevel: method('getAuthenticatorAssuranceLevel'),
|
||||
},
|
||||
},
|
||||
} as unknown as FaunosteoClient
|
||||
return { client, calls }
|
||||
}
|
||||
|
||||
async function kindOf(promise: Promise<unknown>) {
|
||||
try {
|
||||
await promise
|
||||
return 'no failure'
|
||||
} catch (error) {
|
||||
return error instanceof MfaFailure ? error.kind : `other: ${String(error)}`
|
||||
}
|
||||
}
|
||||
|
||||
const factor = (id: string, status: string, type = 'totp', name?: string) => ({
|
||||
id, factor_type: type, status, friendly_name: name, created_at: `2026-11-0${id}T10:00:00Z`, updated_at: 'u',
|
||||
})
|
||||
|
||||
describe('classifyMfaError', () => {
|
||||
it('maps the GoTrue codes to the closed kinds', () => {
|
||||
expect(classifyMfaError({ code: 'insufficient_aal', status: 403 })).toBe('aal2_required')
|
||||
expect(classifyMfaError({ code: 'mfa_verification_failed', status: 422 })).toBe('invalid_code')
|
||||
expect(classifyMfaError({ code: 'mfa_verification_rejected', status: 422 })).toBe('invalid_code')
|
||||
expect(classifyMfaError({ code: 'mfa_factor_not_found', status: 404 })).toBe('factor_not_found')
|
||||
expect(classifyMfaError({ code: 'mfa_challenge_expired', status: 422 })).toBe('challenge_expired')
|
||||
expect(classifyMfaError({ code: 'too_many_enrolled_mfa_factors', status: 422 })).toBe('too_many_factors')
|
||||
expect(classifyMfaError({ code: 'mfa_factor_name_conflict', status: 422 })).toBe('name_taken')
|
||||
expect(classifyMfaError({ code: 'over_request_rate_limit', status: 429 })).toBe('rate_limited')
|
||||
expect(classifyMfaError({ code: 'session_not_found', status: 403 })).toBe('session_expired')
|
||||
expect(classifyMfaError({ code: 'bad_jwt', status: 401 })).toBe('session_expired')
|
||||
})
|
||||
|
||||
it('reads the client error classes, then the status, and fails closed', () => {
|
||||
expect(classifyMfaError({ name: 'AuthSessionMissingError', status: 400 })).toBe('session_expired')
|
||||
expect(classifyMfaError({ name: 'AuthRetryableFetchError', status: 0 })).toBe('network')
|
||||
expect(classifyMfaError(new TypeError('fetch failed'))).toBe('network')
|
||||
expect(classifyMfaError({ status: 429 })).toBe('rate_limited')
|
||||
expect(classifyMfaError({ code: 'mfa_totp_enroll_not_enabled', status: 422 })).toBe('unavailable')
|
||||
expect(classifyMfaError({ code: 'unexpected_failure', status: 500 })).toBe('unavailable')
|
||||
expect(classifyMfaError(undefined)).toBe('unavailable')
|
||||
expect(classifyMfaError(new MfaFailure('invalid_code'))).toBe('invalid_code')
|
||||
})
|
||||
})
|
||||
|
||||
describe('TOTP wrappers', () => {
|
||||
it('lists every TOTP factor, unverified ones included, and no other type', async () => {
|
||||
const all = [factor('1', 'verified', 'totp', 'Phone'), factor('2', 'unverified'), factor('3', 'verified', 'phone')]
|
||||
const { client } = stubMfa({ listFactors: { data: { all, totp: [all[0]] } } })
|
||||
expect(await listTotpFactors(client)).toEqual([
|
||||
{ id: '1', friendlyName: 'Phone', status: 'verified', createdAt: '2026-11-01T10:00:00Z' },
|
||||
{ id: '2', friendlyName: null, status: 'unverified', createdAt: '2026-11-02T10:00:00Z' },
|
||||
])
|
||||
})
|
||||
|
||||
it('enrols a TOTP factor and hands back the QR code, secret and URI', async () => {
|
||||
const totp = { qr_code: 'data:image/svg+xml;utf-8,<svg/>', secret: 'S', uri: 'otpauth://totp/x' }
|
||||
const { client, calls } = stubMfa({ enroll: { data: { id: 'f1', type: 'totp', totp } } })
|
||||
expect(await enrollTotp(client, 'Phone')).toEqual({
|
||||
factorId: 'f1', qrCode: totp.qr_code, secret: 'S', uri: totp.uri,
|
||||
})
|
||||
expect(calls).toEqual([['enroll', { factorType: 'totp', friendlyName: 'Phone' }]])
|
||||
})
|
||||
|
||||
it('verifies with one challenge and removes a factor by id', async () => {
|
||||
const { client, calls } = stubMfa({ challengeAndVerify: { data: {} }, unenroll: { data: { id: 'f1' } } })
|
||||
await verifyTotp(client, 'f1', '123456')
|
||||
await unenrollFactor(client, 'f1')
|
||||
expect(calls).toEqual([
|
||||
['challengeAndVerify', { factorId: 'f1', code: '123456' }],
|
||||
['unenroll', { factorId: 'f1' }],
|
||||
])
|
||||
})
|
||||
|
||||
it('answers the assurance levels, null without a session', async () => {
|
||||
const level = (currentLevel: unknown, nextLevel: unknown) =>
|
||||
stubMfa({ getAuthenticatorAssuranceLevel: { data: { currentLevel, nextLevel, currentAuthenticationMethods: [] } } })
|
||||
.client
|
||||
expect(await assuranceLevel(level('aal1', 'aal2'))).toEqual({ current: 'aal1', next: 'aal2' })
|
||||
expect(await assuranceLevel(level(null, null))).toEqual({ current: null, next: null })
|
||||
expect(await assuranceLevel(level('aal3', 'aal2'))).toEqual({ current: null, next: 'aal2' })
|
||||
})
|
||||
|
||||
it('throws the closed kind of a GoTrue refusal', async () => {
|
||||
const refused = (name: string, code: string) => stubMfa({ [name]: { error: { code, status: 403 } } }).client
|
||||
expect(await kindOf(enrollTotp(refused('enroll', 'insufficient_aal'), 'x'))).toBe('aal2_required')
|
||||
expect(await kindOf(verifyTotp(refused('challengeAndVerify', 'mfa_verification_failed'), 'f', '000000')))
|
||||
.toBe('invalid_code')
|
||||
expect(await kindOf(unenrollFactor(refused('unenroll', 'insufficient_aal'), 'f'))).toBe('aal2_required')
|
||||
expect(await kindOf(listTotpFactors(refused('listFactors', 'session_not_found')))).toBe('session_expired')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,209 @@
|
||||
/**
|
||||
* The V1-2.5 access layer through real supabase-js against the throwaway
|
||||
* stack (real GoTrue v2.197.0, PostgREST, Storage, PostgreSQL): the TOTP
|
||||
* wrappers (enrol, verify to aal2, the aal1 refusals of IDENTITY.md §4.1,
|
||||
* removal), the M7 admin reads at aal2 and their aal1 refusal, species
|
||||
* creation by an editor, the account lookup by the owner, the catalogue
|
||||
* reads. Run through `pnpm db:sandbox test tests/sandbox/sheets-admin.sandbox.ts`;
|
||||
* the accounts and the species it creates are removed afterwards, so it runs
|
||||
* again on the same stack.
|
||||
*/
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { createClient } from '@supabase/supabase-js'
|
||||
import {
|
||||
MfaFailure,
|
||||
SheetFailure,
|
||||
assuranceLevel,
|
||||
createSheetWorkingCopy,
|
||||
createSpecies,
|
||||
downloadSheetDrawing,
|
||||
enrollTotp,
|
||||
getOfficialSheetAdmin,
|
||||
listCatalogGrants,
|
||||
listCatalogSpecies,
|
||||
listOfficialSheetsAdmin,
|
||||
listOwnCatalogGrants,
|
||||
listSheetVersions,
|
||||
listTotpFactors,
|
||||
lookupCatalogAccount,
|
||||
unenrollFactor,
|
||||
updateInactiveSpecies,
|
||||
verifyTotp,
|
||||
type Database,
|
||||
type FaunosteoClient,
|
||||
} from '../../src'
|
||||
import { PASSWORD, confirmedAccount, sql, stack, type Account } from './stack'
|
||||
import { totpCode } from './totp'
|
||||
|
||||
const BASE = 'http://sandbox.faunosteo.invalid'
|
||||
const HISTORICAL = '503dc301-a8b1-50d4-9e44-0919b2fc2916'
|
||||
|
||||
/** The browser client of the app, its requests replayed on the sandbox ports. */
|
||||
function browserClient(): FaunosteoClient {
|
||||
const mapped: typeof fetch = (input, init) => {
|
||||
const url = String(input instanceof Request ? input.url : input)
|
||||
.replace(`${BASE}/auth/v1`, stack.authUrl)
|
||||
.replace(`${BASE}/rest/v1`, stack.restUrl)
|
||||
.replace(`${BASE}/storage/v1`, stack.storageUrl)
|
||||
return fetch(url, init)
|
||||
}
|
||||
return createClient<Database>(BASE, stack.anonKey, {
|
||||
auth: { persistSession: false, autoRefreshToken: false },
|
||||
global: { fetch: mapped },
|
||||
})
|
||||
}
|
||||
|
||||
/** A new password session of the account: always aal1. */
|
||||
async function signedIn(account: Account): Promise<FaunosteoClient> {
|
||||
const client = browserClient()
|
||||
const { error } = await client.auth.signInWithPassword({ email: account.email, password: PASSWORD })
|
||||
if (error) throw error
|
||||
return client
|
||||
}
|
||||
|
||||
/** Enrols and verifies a TOTP factor through the wrappers; the client ends at aal2. */
|
||||
async function stepUp(client: FaunosteoClient, name = 'device') {
|
||||
const enrolment = await enrollTotp(client, name)
|
||||
await verifyTotp(client, enrolment.factorId, totpCode(enrolment.secret))
|
||||
return enrolment
|
||||
}
|
||||
|
||||
async function kindOf(promise: Promise<unknown>) {
|
||||
try {
|
||||
await promise
|
||||
return 'no failure'
|
||||
} catch (error) {
|
||||
if (error instanceof SheetFailure || error instanceof MfaFailure) return error.kind
|
||||
return `other: ${String(error)}`
|
||||
}
|
||||
}
|
||||
|
||||
/** A code of the same length that is not the current one. */
|
||||
const wrongCode = (secret: string) =>
|
||||
totpCode(secret).replace(/.$/, (digit) => String((Number(digit) + 5) % 10))
|
||||
|
||||
const created: string[] = []
|
||||
const species: string[] = []
|
||||
|
||||
async function account(tag: string, role: 'owner' | 'admin' | null = null): Promise<Account> {
|
||||
const a = await confirmedAccount(tag)
|
||||
created.push(a.id)
|
||||
if (role) await sql(`select private.assign_platform_role(null, '${a.id}', '${role}')`)
|
||||
return a
|
||||
}
|
||||
|
||||
afterAll(async () => {
|
||||
if (species.length > 0)
|
||||
await sql(`delete from public.species where id in (${species.map((id) => `'${id}'`).join(', ')})`)
|
||||
if (created.length === 0) return
|
||||
const ids = created.map((id) => `'${id}'`).join(', ')
|
||||
// Grants are never deleted by design (guard trigger): the run's own rows are
|
||||
// removed with the triggers off for this transaction only, then the accounts.
|
||||
await sql(`begin;
|
||||
set local session_replication_role = replica;
|
||||
delete from public.anatomical_catalog_grants where user_id in (${ids});
|
||||
set local session_replication_role = origin;
|
||||
delete from auth.users where id in (${ids});
|
||||
commit;`)
|
||||
})
|
||||
|
||||
describe('TOTP wrappers on real GoTrue', () => {
|
||||
it('enrols, verifies to aal2, refuses the aal1 changes, removes', async () => {
|
||||
const a = await account('admin-mfa')
|
||||
const client = await signedIn(a)
|
||||
expect(await assuranceLevel(client)).toEqual({ current: 'aal1', next: 'aal1' })
|
||||
|
||||
const enrolment = await enrollTotp(client, 'Phone')
|
||||
expect(enrolment.qrCode.startsWith('data:image/svg+xml;utf-8,')).toBe(true)
|
||||
expect(enrolment.uri.startsWith('otpauth://totp/')).toBe(true)
|
||||
// supabase-js keeps unverified factors out of `totp`: the wrapper still lists them.
|
||||
expect(await listTotpFactors(client)).toEqual([
|
||||
expect.objectContaining({ id: enrolment.factorId, friendlyName: 'Phone', status: 'unverified' }),
|
||||
])
|
||||
|
||||
expect(await kindOf(verifyTotp(client, enrolment.factorId, wrongCode(enrolment.secret)))).toBe('invalid_code')
|
||||
await verifyTotp(client, enrolment.factorId, totpCode(enrolment.secret))
|
||||
expect(await assuranceLevel(client)).toEqual({ current: 'aal2', next: 'aal2' })
|
||||
expect((await listTotpFactors(client)).map((f) => f.status)).toEqual(['verified'])
|
||||
|
||||
// A new password session is aal1: no second factor, no removal of the verified one.
|
||||
const aal1 = await signedIn(a)
|
||||
expect(await assuranceLevel(aal1)).toEqual({ current: 'aal1', next: 'aal2' })
|
||||
expect(await kindOf(enrollTotp(aal1, 'Second'))).toBe('aal2_required')
|
||||
expect(await kindOf(unenrollFactor(aal1, enrolment.factorId))).toBe('aal2_required')
|
||||
expect(await kindOf(unenrollFactor(client, randomUUID()))).toBe('factor_not_found')
|
||||
|
||||
await unenrollFactor(client, enrolment.factorId)
|
||||
expect(await listTotpFactors(client)).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('administration reads, species and account lookup', () => {
|
||||
let editor: Account
|
||||
let editorAal2: FaunosteoClient
|
||||
|
||||
beforeAll(async () => {
|
||||
editor = await account('admin-editor', 'admin')
|
||||
await sql(`insert into public.anatomical_catalog_grants (user_id, grant_kind, reason, verification_note, granted_by)
|
||||
values ('${editor.id}', 'sheet_editor', 'sandbox', 'sandbox', '${editor.id}')`)
|
||||
editorAal2 = await signedIn(editor)
|
||||
await stepUp(editorAal2)
|
||||
})
|
||||
|
||||
it('an editor reads the admin list and an overview at aal2, refused at aal1', async () => {
|
||||
const sheets = await listOfficialSheetsAdmin(editorAal2)
|
||||
expect(sheets.find((s) => s.sheet_id === HISTORICAL)).toMatchObject({ historical: true, working_copy: false })
|
||||
const overview = await getOfficialSheetAdmin(editorAal2, HISTORICAL)
|
||||
expect(overview.versions.length).toBeGreaterThan(0)
|
||||
expect(await kindOf(getOfficialSheetAdmin(editorAal2, randomUUID()))).toBe('not_found')
|
||||
|
||||
const aal1 = await signedIn(editor)
|
||||
expect(await kindOf(listOfficialSheetsAdmin(aal1))).toBe('rights.mfa')
|
||||
expect(await kindOf(getOfficialSheetAdmin(aal1, HISTORICAL))).toBe('rights.mfa')
|
||||
// The navigation hint reads the own rows at any level.
|
||||
expect(await listOwnCatalogGrants(aal1, editor.id)).toEqual([
|
||||
{ kind: 'sheet_editor', expires_at: null, revoked_at: null },
|
||||
])
|
||||
})
|
||||
|
||||
it('an editor creates an inactive species and edits it', async () => {
|
||||
const id = `sbx-${randomUUID().slice(0, 8)}`
|
||||
species.push(id)
|
||||
expect(await createSpecies(editorAal2, { id, name_fr: 'Essai', name_en: 'Trial' })).toBe(id)
|
||||
expect(await updateInactiveSpecies(editorAal2, { id, name_fr: 'Essai 2', name_en: 'Trial 2', sort_order: 900 }))
|
||||
.toBe(id)
|
||||
expect((await listCatalogSpecies(editorAal2)).find((s) => s.id === id)).toEqual({
|
||||
id, name_fr: 'Essai 2', name_en: 'Trial 2', sort_order: 900, active: false,
|
||||
})
|
||||
expect(await kindOf(createSpecies(editorAal2, { id, name_fr: 'X', name_en: 'X' }))).toBe('species.exists')
|
||||
})
|
||||
|
||||
it('the working copy and the catalogue reads answer their closed kinds', async () => {
|
||||
const source = await sql(`select id from public.anatomical_sheet_versions where sheet_id = '${HISTORICAL}'
|
||||
order by version_number limit 1`)
|
||||
expect(['working_copy.exists', 'working_copy.assets_missing'])
|
||||
.toContain(await kindOf(createSheetWorkingCopy(editorAal2, source, `wc-${randomUUID().slice(0, 8)}`)))
|
||||
const versions = await listSheetVersions(editorAal2, HISTORICAL)
|
||||
expect(versions.every((v) => v.status === 'published' || v.status === 'deprecated')).toBe(true)
|
||||
expect(await kindOf(downloadSheetDrawing(editorAal2, 'f'.repeat(64)))).toBe('not_found')
|
||||
})
|
||||
|
||||
it('the owner looks an account up at aal2, refused at aal1', async () => {
|
||||
const owner = await account('admin-owner', 'owner')
|
||||
const ownerAal2 = await signedIn(owner)
|
||||
await stepUp(ownerAal2)
|
||||
expect(await lookupCatalogAccount(ownerAal2, editor.email.toUpperCase())).toEqual({
|
||||
user_id: editor.id,
|
||||
display_name: expect.any(String),
|
||||
active: true,
|
||||
email_confirmed: true,
|
||||
verified_totp: true,
|
||||
platform_roles: ['admin'],
|
||||
})
|
||||
expect(await kindOf(lookupCatalogAccount(ownerAal2, `none-${randomUUID()}@sandbox.local`))).toBe('not_found')
|
||||
expect((await listCatalogGrants(ownerAal2)).find((g) => g.user_id === editor.id)).toMatchObject({
|
||||
kind: 'sheet_editor', state: 'active', effective: true,
|
||||
})
|
||||
expect(await kindOf(lookupCatalogAccount(await signedIn(owner), editor.email))).toBe('rights.mfa')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,238 @@
|
||||
import {
|
||||
SheetFailure,
|
||||
activateSpecies,
|
||||
createSheetWorkingCopy,
|
||||
createSpecies,
|
||||
downloadSheetDrawing,
|
||||
getOfficialSheetAdmin,
|
||||
listCatalogGrants,
|
||||
listCatalogSpecies,
|
||||
listOfficialSheetsAdmin,
|
||||
listOwnCatalogGrants,
|
||||
listSheetVersions,
|
||||
lookupCatalogAccount,
|
||||
renameSpecies,
|
||||
updateInactiveSpecies,
|
||||
type FaunosteoClient,
|
||||
} from '../src'
|
||||
|
||||
/**
|
||||
* Call shapes, answer parsers and closed failure kinds of the V1-2.5 sheet
|
||||
* access layer. The argument names are checked by the compiler against the
|
||||
* generated types; the RPC bodies by the sheet pgTAP files under supabase/tests; the
|
||||
* same functions run against real PostgREST, GoTrue and Storage in
|
||||
* tests/sandbox/sheets-admin.sandbox.ts.
|
||||
*/
|
||||
type Answer = { data?: unknown; error?: unknown; status?: number }
|
||||
|
||||
function stubClient(answers: { rpc?: Answer; select?: Answer; download?: Answer } = {}) {
|
||||
const rpcCalls: Array<[string, Record<string, unknown> | undefined]> = []
|
||||
const query: Record<string, unknown> = {}
|
||||
const downloads: Array<[string, string]> = []
|
||||
const settle = (a: Answer = {}) => ({
|
||||
data: a.data ?? null,
|
||||
error: a.error ?? null,
|
||||
status: a.status ?? (a.error ? 400 : 200),
|
||||
})
|
||||
const chain = {
|
||||
select: (cols: string) => ((query.select = cols), chain),
|
||||
eq: (col: string, value: unknown) => ((query[`eq:${col}`] = value), chain),
|
||||
in: (col: string, values: unknown) => ((query[`in:${col}`] = values), chain),
|
||||
order: (col: string, opts: unknown) => ((query[`order:${col}`] = opts), chain),
|
||||
then: (resolve: (value: unknown) => unknown) => resolve(settle(answers.select)),
|
||||
}
|
||||
const client = {
|
||||
from: (table: string) => ((query.table = table), chain),
|
||||
rpc: async (name: string, args?: Record<string, unknown>) => {
|
||||
rpcCalls.push([name, args])
|
||||
return settle(answers.rpc)
|
||||
},
|
||||
storage: {
|
||||
from: (bucket: string) => ({
|
||||
download: async (path: string) => {
|
||||
downloads.push([bucket, path])
|
||||
return { data: answers.download?.data ?? null, error: answers.download?.error ?? null }
|
||||
},
|
||||
}),
|
||||
},
|
||||
} as unknown as FaunosteoClient
|
||||
return { client, rpcCalls, query, downloads }
|
||||
}
|
||||
|
||||
async function kindOf(promise: Promise<unknown>) {
|
||||
try {
|
||||
await promise
|
||||
return 'no failure'
|
||||
} catch (error) {
|
||||
return error instanceof SheetFailure ? error.kind : `other: ${String(error)}`
|
||||
}
|
||||
}
|
||||
|
||||
const SHEET = '22222222-2222-4222-8222-222222222222'
|
||||
const VERSION = '33333333-3333-4333-8333-333333333333'
|
||||
const SHA = 'a'.repeat(64)
|
||||
|
||||
const person = { user_id: SHEET, display_name: 'Marie' }
|
||||
const summary = {
|
||||
sheet_id: SHEET,
|
||||
species_id: 'equine',
|
||||
slug: 'cheval',
|
||||
status: 'active',
|
||||
archived_at: null,
|
||||
created_at: '2026-11-02T10:00:00Z',
|
||||
updated_at: '2026-11-02T10:00:00Z',
|
||||
name: { fr: 'Cheval', en: 'Horse' },
|
||||
historical: true,
|
||||
working_copy: false,
|
||||
working_copy_active: false,
|
||||
latest_version: { version_id: VERSION, version_number: 2, status: 'draft', revision: 3 },
|
||||
current_version: { version_id: VERSION, version_number: 1, published_at: '2026-11-01T10:00:00Z' },
|
||||
draft_version: { version_id: VERSION, version_number: 2, revision: 3 },
|
||||
version_statuses: ['draft', 'published'],
|
||||
open_rounds: 0,
|
||||
latest_round: null,
|
||||
}
|
||||
const overview = {
|
||||
...summary,
|
||||
working_copy_source: null,
|
||||
versions: [{
|
||||
version_id: VERSION, version_number: 1, status: 'published', revision: 1, change_note: null,
|
||||
created_at: '2026-11-01T09:00:00Z', published_at: '2026-11-01T10:00:00Z', deprecated_at: null,
|
||||
source_version_number: null, authors: [person],
|
||||
}],
|
||||
rounds: [{
|
||||
review_id: VERSION, version_id: VERSION, version_number: 1, round: 1, revision: 1, status: 'approved',
|
||||
submitted_by: person, submitted_at: '2026-11-01T09:30:00Z', verified_at: '2026-11-01T09:31:00Z',
|
||||
failure_outcome: null, failure_code: null, decided_by: person, decided_at: '2026-11-01T09:40:00Z',
|
||||
withdrawn_at: null,
|
||||
}],
|
||||
}
|
||||
const grant = {
|
||||
id: VERSION, user_id: SHEET, display_name: 'Marie', email: 'marie@example.org', kind: 'sheet_editor',
|
||||
reason: 'r', verification_note: 'n', granted_by: SHEET, granted_by_name: 'Owner',
|
||||
granted_at: '2026-11-01T09:00:00Z', expires_at: null, revoked_at: null, revoked_by: null,
|
||||
revocation_reason: null, state: 'active', effective: true,
|
||||
}
|
||||
|
||||
describe('sheet admin wrappers: argument mapping', () => {
|
||||
it('names the RPC arguments as the migrations do', async () => {
|
||||
const { client, rpcCalls } = stubClient({ rpc: { data: 'ok' } })
|
||||
await createSpecies(client, { id: 'feline', name_fr: 'Chat', name_en: 'Cat' })
|
||||
await updateInactiveSpecies(client, { id: 'feline', name_fr: 'Chat', name_en: 'Cat', sort_order: 5 })
|
||||
await activateSpecies(client, 'feline')
|
||||
await renameSpecies(client, { id: 'feline', name_fr: 'Félin', name_en: 'Feline' })
|
||||
await createSheetWorkingCopy(client, VERSION, 'cheval-v2')
|
||||
expect(rpcCalls).toEqual([
|
||||
['create_species', { id: 'feline', name_fr: 'Chat', name_en: 'Cat' }],
|
||||
['update_inactive_species', { id: 'feline', name_fr: 'Chat', name_en: 'Cat', sort_order: 5 }],
|
||||
['activate_species', { id: 'feline' }],
|
||||
['rename_species', { id: 'feline', name_fr: 'Félin', name_en: 'Feline' }],
|
||||
['create_sheet_working_copy', { source_version_id: VERSION, slug: 'cheval-v2' }],
|
||||
])
|
||||
})
|
||||
|
||||
it('reads the published and deprecated versions of one sheet, newest first', async () => {
|
||||
const rows = [{ id: VERSION, version_number: 1, status: 'published', published_at: 'x', deprecated_at: null }]
|
||||
const { client, query } = stubClient({ select: { data: rows } })
|
||||
expect(await listSheetVersions(client, SHEET)).toEqual(rows)
|
||||
expect(query).toEqual({
|
||||
table: 'anatomical_sheet_versions',
|
||||
select: 'id, version_number, status, published_at, deprecated_at',
|
||||
[`eq:sheet_id`]: SHEET,
|
||||
[`in:status`]: ['published', 'deprecated'],
|
||||
[`order:version_number`]: { ascending: false },
|
||||
})
|
||||
})
|
||||
|
||||
it("reads the caller's own grant rows for the navigation hint", async () => {
|
||||
const rows = [{ kind: 'catalog_reader', expires_at: null, revoked_at: null }]
|
||||
const { client, query } = stubClient({ select: { data: rows } })
|
||||
expect(await listOwnCatalogGrants(client, SHEET)).toEqual(rows)
|
||||
expect(query).toEqual({
|
||||
table: 'anatomical_catalog_grants',
|
||||
select: 'kind:grant_kind, expires_at, revoked_at',
|
||||
[`eq:user_id`]: SHEET,
|
||||
})
|
||||
})
|
||||
|
||||
it('answers a malformed id as unknown without a request', async () => {
|
||||
const { client, rpcCalls, query } = stubClient()
|
||||
expect(await kindOf(getOfficialSheetAdmin(client, 'nope'))).toBe('not_found')
|
||||
expect(await kindOf(listSheetVersions(client, `${SHEET}'`))).toBe('not_found')
|
||||
expect(rpcCalls).toEqual([])
|
||||
expect(query).toEqual({})
|
||||
})
|
||||
})
|
||||
|
||||
describe('sheet admin wrappers: answers', () => {
|
||||
it('parses the admin list and the overview', async () => {
|
||||
expect(await listOfficialSheetsAdmin(stubClient({ rpc: { data: [summary] } }).client)).toEqual([summary])
|
||||
const { client, rpcCalls } = stubClient({ rpc: { data: overview } })
|
||||
expect(await getOfficialSheetAdmin(client, SHEET)).toEqual(overview)
|
||||
expect(rpcCalls).toEqual([['get_official_sheet_admin', { sheet_id: SHEET }]])
|
||||
})
|
||||
|
||||
it('parses grants, the account lookup and the species', async () => {
|
||||
expect(await listCatalogGrants(stubClient({ rpc: { data: [grant] } }).client)).toEqual([grant])
|
||||
const account = {
|
||||
user_id: SHEET, display_name: 'Marie', active: true, email_confirmed: true, verified_totp: false,
|
||||
platform_roles: ['owner'],
|
||||
}
|
||||
const lookup = stubClient({ rpc: { data: account } })
|
||||
expect(await lookupCatalogAccount(lookup.client, 'marie@example.org')).toEqual(account)
|
||||
expect(lookup.rpcCalls).toEqual([['lookup_catalog_account', { email: 'marie@example.org' }]])
|
||||
const species = [{ id: 'equine', name_fr: 'Cheval', name_en: 'Horse', sort_order: 10, active: true }]
|
||||
expect(await listCatalogSpecies(stubClient({ rpc: { data: species } }).client)).toEqual(species)
|
||||
})
|
||||
|
||||
it('refuses an answer outside the contract as unavailable', async () => {
|
||||
const answer = (data: unknown) => stubClient({ rpc: { data } }).client
|
||||
expect(await kindOf(listOfficialSheetsAdmin(answer({ sheets: [] })))).toBe('unavailable')
|
||||
expect(await kindOf(listOfficialSheetsAdmin(answer([{ ...summary, status: 'gone' }])))).toBe('unavailable')
|
||||
expect(await kindOf(getOfficialSheetAdmin(answer(summary), SHEET))).toBe('unavailable')
|
||||
expect(await kindOf(listCatalogGrants(answer([{ ...grant, state: 'paused' }])))).toBe('unavailable')
|
||||
expect(await kindOf(lookupCatalogAccount(answer(null), 'a@b.c'))).toBe('unavailable')
|
||||
expect(await kindOf(listCatalogSpecies(answer([{ id: 'x' }])))).toBe('unavailable')
|
||||
})
|
||||
|
||||
it('folds the server refusals into their kinds', async () => {
|
||||
const refused = (message: string, code = '42501') =>
|
||||
stubClient({ rpc: { error: { code, message }, status: 403 } }).client
|
||||
expect(await kindOf(listOfficialSheetsAdmin(refused('rights.mfa')))).toBe('rights.mfa')
|
||||
expect(await kindOf(getOfficialSheetAdmin(refused('not_found'), SHEET))).toBe('not_found')
|
||||
expect(await kindOf(lookupCatalogAccount(refused('rights.owner'), 'a@b.c'))).toBe('rights.owner')
|
||||
expect(await kindOf(createSpecies(refused('species.exists', 'P0001'), { id: 'x', name_fr: 'X', name_en: 'X' })))
|
||||
.toBe('species.exists')
|
||||
expect(await kindOf(createSheetWorkingCopy(refused('working_copy.exists', 'P0001'), VERSION, 's')))
|
||||
.toBe('working_copy.exists')
|
||||
const expired = stubClient({ select: { error: { code: 'PGRST301', message: 'JWT expired' }, status: 401 } })
|
||||
expect(await kindOf(listSheetVersions(expired.client, SHEET))).toBe('session_expired')
|
||||
})
|
||||
})
|
||||
|
||||
describe('downloadSheetDrawing', () => {
|
||||
it('downloads <sha256>.svg from the sheet bucket and answers its bytes', async () => {
|
||||
const bytes = new TextEncoder().encode('<svg/>')
|
||||
const { client, downloads } = stubClient({ download: { data: new Blob([bytes]) } })
|
||||
expect(await downloadSheetDrawing(client, SHA)).toEqual(bytes)
|
||||
expect(downloads).toEqual([['anatomical-sheet-assets', `${SHA}.svg`]])
|
||||
})
|
||||
|
||||
it('refuses a malformed hash before any request', async () => {
|
||||
const { client, downloads } = stubClient()
|
||||
for (const sha of ['', 'A'.repeat(64), 'a'.repeat(63), `${'a'.repeat(64)}/x`, '../x'])
|
||||
expect(await kindOf(downloadSheetDrawing(client, sha))).toBe('invalid_input')
|
||||
expect(downloads).toEqual([])
|
||||
})
|
||||
|
||||
it('folds Storage refusals: a missing object and a refused one are the same not_found', async () => {
|
||||
const failing = (error: unknown) => stubClient({ download: { error } }).client
|
||||
expect(await kindOf(downloadSheetDrawing(failing({ name: 'StorageApiError', status: 400, code: 'NoSuchKey' }), SHA)))
|
||||
.toBe('not_found')
|
||||
expect(await kindOf(downloadSheetDrawing(failing({ name: 'StorageApiError', status: 404 }), SHA))).toBe('not_found')
|
||||
expect(await kindOf(downloadSheetDrawing(failing({ name: 'StorageApiError', status: 400, code: 'InvalidJWT' }), SHA)))
|
||||
.toBe('session_expired')
|
||||
expect(await kindOf(downloadSheetDrawing(failing({ name: 'StorageUnknownError' }), SHA))).toBe('network')
|
||||
expect(await kindOf(downloadSheetDrawing(failing({ name: 'StorageApiError', status: 500 }), SHA))).toBe('unavailable')
|
||||
})
|
||||
})
|
||||
@@ -5,13 +5,14 @@ import { migrationsDir } from './db/harness'
|
||||
|
||||
/**
|
||||
* The closed failure kinds of the sheet workflow (V1-2.1). The census reads
|
||||
* every closed code M4 and M5 raise (`raise exception '<code>'`, a lowercase
|
||||
* every closed code M4, M5 and M7 raise (`raise exception '<code>'`, a lowercase
|
||||
* dotted word; free-text messages are not codes) so a code added on the server
|
||||
* can never reach a page as `unavailable` for want of a kind.
|
||||
*/
|
||||
const SHEET_MIGRATIONS = [
|
||||
'20261028100000_sheet_access_hardening.sql',
|
||||
'20261028110000_sheet_review_workflow.sql',
|
||||
'20261102100000_sheet_admin_reads.sql',
|
||||
]
|
||||
|
||||
async function raisedCodes(): Promise<string[]> {
|
||||
|
||||
Reference in new issue
Block a user