Files
faunosteo/packages/supabase/tests/sheets-admin.test.ts
T
bchanot c9ace9aff2 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.
2026-11-02 16:31:50 +01:00

239 lines
11 KiB
TypeScript

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')
})
})