feat(supabase): V1-2.1 M4/M5 secure sheet access and review workflow

M4 20261028100000_sheet_access_hardening + M5 20261028110000_sheet_review_workflow
(applied together; no unprotected window). Implements contract §5-§14.

- Catalogue rights table + owner RPCs; has_mfa / has_aal2_session (live
  auth.sessions check); grant_active vs caller_has split; catalogue reader
  predicate; can_edit_sheet on the sheet_editor capability (F14).
- AR-1 B: aal2 required on every platform role change, target verified factor,
  race-free last-owner guard (F18/F19); service_role loses table privileges on
  the catalogue + profiles/profile_roles and EXECUTE on the role RPCs (F12/F17).
- Reviewed lifecycle: version provenance + review columns, content/freeze/
  author triggers, rounds/comments/acknowledgments, save/submit/withdraw/
  comment/acknowledge/decide, atomic publish_sheet_version(review_id) on the
  stored verdict, deprecate/archive/restore, species RPCs, equine working copy,
  uploads with the storage check (F7) + editor INSERT policy + 2 MiB bucket.
  F1-F3,F5,F6,F8,F9,F13,F15,F16 closed. Verdict is a fixture until M6 (V1-2.3).
- O22: SQL business mirror removed, declared status check kept; pgTAP 011 and
  the Rust generator's SQL parts deleted, ledger retargeted.
- Access layer sheets.ts (closed SheetFailure kinds); old client publish gate
  deleted; types regenerated; upload tool reads via get_sheet_asset_state.

Tested on the throwaway sandbox only; DEV untouched. pgTAP 850 (real stack) /
122 (PGlite) green; real-GoTrue AR-1 B + F18 race green; fresh install and
M3->M5 upgrade green; V1-1 regression green; rust:check, typecheck, lint,
build, types drift clean. BDR-084, LRN-095.
This commit is contained in:
bchanot committed 2026-10-28 15:52:49 +01:00
1 parent 9c13bae4bc
commit 77e5fa4cf5
33 files changed
+4613 -1617

No files matched your search

@@ -1,113 +0,0 @@
import { nodeCoreRuntime } from '@faunosteo/core-wasm/node'
import type { CoreRuntime } from '@faunosteo/core-wasm'
import { publishSheetVersion, SheetPublishError } from '../src'
import type { FaunosteoClient, SheetCheckOutcome, SheetValidator } from '../src'
/** The real core's `sheet.check` (R2): the gate is never tested against a stub verdict. */
let core: CoreRuntime
beforeAll(async () => {
core = await nodeCoreRuntime()
})
const validate: SheetValidator = (content) =>
core.call('sheet.check', JSON.stringify(content)) as SheetCheckOutcome
/**
* Stub of the two client calls publishSheetVersion makes. The real RPC is
* covered by supabase/tests/005_anatomical_sheets.sql; here the point is the
* order of the gate: no RPC call unless the document is publishable.
*/
function stubClient(content: unknown) {
const rpcCalls: unknown[] = []
const client = {
from: () => ({
select: () => ({
eq: () => ({
single: async () => ({ data: { content }, error: null }),
}),
}),
}),
rpc: async (name: string, args: unknown) => {
rpcCalls.push([name, args])
return { data: 'published-id', error: null }
},
}
return { client: client as unknown as FaunosteoClient, rpcCalls }
}
const publishable = {
schema_version: 2,
species_id: 'equine',
name: { fr: 'Test', en: 'Test' },
description: {},
scope_disclaimer: {},
attribution: { authors: [], license: null, notes: null },
vertebral_config: { regions: [] },
references: [],
categories: [],
views: [
{
id: 'view-main',
kind: 'main',
name: { fr: 'Vue', en: 'View' },
svg_asset_id: '11111111-1111-4111-8111-111111111111',
view_box: null,
},
],
annotations: [],
finding_zones: [],
}
describe('publishSheetVersion', () => {
it('refuses publication when the validator cannot run (fail closed)', async () => {
const { client, rpcCalls } = stubClient(publishable)
const unavailable: SheetValidator = () => ({
ok: false,
kind: 'core_unavailable',
})
await expect(
publishSheetVersion(client, 'v1', unavailable),
).rejects.toMatchObject({ kind: 'validator_unavailable' })
expect(rpcCalls).toEqual([])
})
it('calls the RPC once the document passes shape and integrity checks', async () => {
const { client, rpcCalls } = stubClient(publishable)
await expect(publishSheetVersion(client, 'v1', validate)).resolves.toBe(
'published-id',
)
expect(rpcCalls).toEqual([['publish_sheet_version', { version_id: 'v1' }]])
})
it('refuses a document with integrity errors before any RPC', async () => {
const { client, rpcCalls } = stubClient({
...publishable,
views: [{ ...publishable.views[0], svg_asset_id: null }],
})
await expect(publishSheetVersion(client, 'v1', validate)).rejects.toThrow(
/view\.asset\.missing/,
)
expect(rpcCalls).toEqual([])
})
it('refuses a document that does not match the schema', async () => {
const { client, rpcCalls } = stubClient({ schema_version: 1 })
await expect(
publishSheetVersion(client, 'v1', validate),
).rejects.toBeInstanceOf(SheetPublishError)
await expect(
publishSheetVersion(client, 'v1', validate),
).rejects.toMatchObject({ kind: 'invalid_shape' })
expect(rpcCalls).toEqual([])
})
it('refuses a document carrying a lone surrogate as content, before any RPC (L1)', async () => {
const { client, rpcCalls } = stubClient({
...publishable,
name: { fr: 'Vue \ud800', en: 'View' },
})
await expect(
publishSheetVersion(client, 'v1', validate),
).rejects.toMatchObject({ kind: 'invalid_shape' })
expect(rpcCalls).toEqual([])
})
})
+75 -12
View File
@@ -55,6 +55,19 @@ const expectedColumns = {
'updated_at',
'workspace_id',
],
anatomical_catalog_grants: [
'expires_at',
'grant_kind',
'granted_at',
'granted_by',
'id',
'reason',
'revocation_reason',
'revoked_at',
'revoked_by',
'user_id',
'verification_note',
],
anatomical_sheet_assets: [
'byte_size',
'content_type',
@@ -66,18 +79,58 @@ const expectedColumns = {
'sheet_id',
'uploaded_at',
],
anatomical_sheet_review_acknowledgments: [
'created_at',
'group_digest',
'group_key',
'id',
'review_id',
'reviewer',
],
anatomical_sheet_review_comments: ['author', 'body', 'created_at', 'group_key', 'id', 'review_id'],
anatomical_sheet_reviews: [
'attempts',
'authors',
'created_at',
'decided_at',
'decided_by',
'decision_note',
'failure_code',
'failure_outcome',
'id',
'lease_token',
'locked_at',
'revision',
'round',
'status',
'submission_note',
'submitted_at',
'submitted_by',
'verdict',
'verified_at',
'verified_with',
'version_id',
'withdrawal_note',
'withdrawn_at',
'withdrawn_by',
],
anatomical_sheet_versions: [
'authors',
'change_note',
'content',
'created_at',
'created_by',
'deprecated_at',
'deprecated_by',
'document_fingerprint',
'document_schema_version',
'id',
'published_at',
'published_by',
'published_review_id',
'revision',
'sheet_id',
'source_version_id',
'status',
'updated_at',
'version_number',
@@ -100,6 +153,7 @@ const expectedColumns = {
'status',
'updated_at',
'visibility',
'working_copy_source_version_id',
],
assets: [
'attempts',
@@ -197,15 +251,26 @@ const expectedFunctionArgs = {
complete_avatar_job: ['asset_id', 'byte_size', 'lock_token', 'sha256'],
confirm_asset_upload: ['asset_id'],
confirm_sheet_asset_upload: ['asset_id'],
create_anatomical_sheet: [
'description',
'document',
'name',
'official',
'slug',
'species_id',
'visibility',
],
acknowledge_sheet_review_group: ['group_digest', 'group_key', 'review_id'],
activate_species: ['id'],
comment_sheet_review: ['body', 'group_key', 'review_id'],
create_official_sheet: ['document', 'slug'],
create_species: ['id', 'name_en', 'name_fr', 'sort_order'],
create_sheet_working_copy: ['slug', 'source_version_id'],
decide_sheet_review: ['approve', 'note', 'review_id'],
get_sheet_asset_state: ['asset_id'],
get_sheet_version: ['version_id'],
grant_catalog_right: ['expires_at', 'kind', 'reason', 'user_id', 'verification_note'],
list_catalog_grants: [],
list_catalog_species: [],
list_official_catalog: [],
lookup_catalog_account: ['email'],
rename_species: ['id', 'name_en', 'name_fr'],
revoke_catalog_right: ['grant_id', 'reason'],
save_sheet_draft: ['change_note', 'document', 'expected_revision', 'version_id'],
submit_sheet_review: ['expected_revision', 'note', 'version_id'],
update_inactive_species: ['id', 'name_en', 'name_fr', 'sort_order'],
withdraw_sheet_review: ['note', 'review_id'],
create_animal: [
'birth_date',
'birth_year',
@@ -247,11 +312,10 @@ const expectedFunctionArgs = {
deprecate_sheet_version: ['reason', 'version_id'],
end_animal_client_relation: ['ended_on', 'expected_revision', 'relation_id'],
expire_pending_uploads: ['max_age_seconds'],
fork_anatomical_sheet: ['name', 'slug', 'source_version_id', 'visibility'],
grant_platform_role: ['role', 'target_user_id'],
list_client_animals: ['after_id', 'after_sort', 'client_id', 'page_size'],
mark_quarantine_purged: ['asset_id'],
publish_sheet_version: ['version_id'],
publish_sheet_version: ['review_id'],
register_sheet_asset: ['byte_size', 'file_name', 'sha256', 'sheet_id'],
reject_avatar_job: ['asset_id', 'lock_token', 'reason'],
remove_avatar: [],
@@ -276,7 +340,6 @@ const expectedFunctionArgs = {
],
set_animal_archived: ['animal_id', 'archived'],
set_client_archived: ['archived', 'client_id'],
set_sheet_visibility: ['sheet_id', 'visibility'],
update_animal: [
'animal_id',
'birth_date',
@@ -26,6 +26,34 @@ create table auth.users (
updated_at timestamptz default now()
);
-- MFA state read by the V1-2 assurance checks (private.has_aal2_session,
-- private.has_verified_totp). Types, names and NOT NULL columns as in GoTrue
-- v2.197.0 (checked on the pinned image by tests/sandbox/mfa.sandbox.ts);
-- the columns the migrations never read are left out.
create type auth.aal_level as enum ('aal1', 'aal2', 'aal3');
create type auth.factor_type as enum ('totp', 'webauthn', 'phone', 'recovery_code');
create type auth.factor_status as enum ('unverified', 'verified');
create table auth.sessions (
id uuid primary key,
user_id uuid not null references auth.users (id) on delete cascade,
created_at timestamptz,
updated_at timestamptz,
factor_id uuid,
aal auth.aal_level,
not_after timestamptz
);
create table auth.mfa_factors (
id uuid primary key,
user_id uuid not null references auth.users (id) on delete cascade,
friendly_name text,
factor_type auth.factor_type not null,
status auth.factor_status not null,
created_at timestamptz not null,
updated_at timestamptz not null
);
create or replace function auth.uid()
returns uuid
language sql
+103
View File
@@ -0,0 +1,103 @@
/**
* GoTrue MFA calls of the sandbox (real GoTrue v2.197.0): enrol a TOTP factor,
* challenge and verify it to reach `aal2`, remove it. Every call carries the
* 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'
export interface Factor {
id: string
secret: string
}
export interface MfaResult {
status: number
body: Record<string, unknown>
}
async function authRequest(
method: string,
path: string,
token: string,
body?: unknown,
): Promise<MfaResult> {
const res = await fetch(stack.authUrl + path, {
method,
headers: {
apikey: stack.anonKey,
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: body === undefined ? undefined : JSON.stringify(body),
})
const text = await res.text()
let parsed: Record<string, unknown> = {}
try {
parsed = JSON.parse(text) as Record<string, unknown>
} catch {
// not JSON: keep an empty body
}
return { status: res.status, body: parsed }
}
/** POST /factors: a new unverified TOTP factor (the secret is shown once). */
export async function enrolTotp(
token: string,
name: string,
): Promise<{ status: number; factor: Factor | null; body: MfaResult['body'] }> {
const res = await authRequest('POST', '/factors', token, {
factor_type: 'totp',
friendly_name: name,
})
const totp = res.body.totp as { secret?: string } | undefined
const factor =
res.status === 200 && typeof res.body.id === 'string' && totp?.secret
? { id: res.body.id, secret: totp.secret }
: null
return { status: res.status, factor, body: res.body }
}
/** Challenge then verify with the current code; resolves with the new session (aal2 on success). */
export async function verifyTotp(
token: string,
factor: Factor,
): Promise<MfaResult> {
const challenge = await authRequest(
'POST',
`/factors/${factor.id}/challenge`,
token,
{},
)
if (challenge.status !== 200) return challenge
return authRequest('POST', `/factors/${factor.id}/verify`, token, {
challenge_id: challenge.body.id,
code: totpCode(factor.secret),
})
}
/**
* 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(
token: string,
factor: Factor,
): Promise<MfaResult> {
await new Promise((resolve) => setTimeout(resolve, msToNextStep() + 200))
return verifyTotp(token, factor)
}
export function unenrol(token: string, factorId: string): Promise<MfaResult> {
return authRequest('DELETE', `/factors/${factorId}`, token)
}
/** The claims of an access token (payload only; the signature is not checked here). */
export function claimsOf(token: string): Record<string, unknown> {
const payload = token.split('.')[1] ?? ''
return JSON.parse(Buffer.from(payload, 'base64url').toString('utf8')) as Record<
string,
unknown
>
}
@@ -0,0 +1,91 @@
/**
* V1-2.1 on the throwaway stack with REAL GoTrue and PostgreSQL: the AR-1 B
* path proven with real TOTP factors and real sessions (pgTAP uses fabricated
* auth rows), and the last-owner race under two concurrent transactions (F18).
* Contract docs/development/V1-2_ANATOMICAL_SHEETS.md §5.7, §15. Run through
* `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
}
describe('AR-1 B on real GoTrue', () => {
let owner: Account
let ownerAal2: string
let target: Account
beforeAll(async () => {
owner = await confirmedAccount('ar1-owner')
target = await confirmedAccount('ar1-target')
// 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)
}, 120_000)
it('refuses a platform role change from the aal1 session', async () => {
const res = await rpc('grant_platform_role', { target_user_id: target.id, role: 'support' }, owner.token)
expect(claimsOf(owner.token).aal).toBe('aal1')
expect([res.status, errorCode(res)]).toEqual([403, '42501'])
expect((res.body as { message?: string }).message).toBe('mfa_required')
})
it('allows the change from a live aal2 session, then reads it back', async () => {
expect(claimsOf(ownerAal2).aal).toBe('aal2')
const res = await rpc('grant_platform_role', { target_user_id: target.id, role: 'support' }, ownerAal2)
expect(res.status).toBe(200)
expect(await sql(`select count(*) from public.profile_roles where user_id = '${target.id}' and role = 'support' and revoked_at is null`)).toBe('1')
})
it('refuses a grant to an account with no verified factor', async () => {
const noFactor = await confirmedAccount('ar1-nofactor')
const res = await rpc('grant_platform_role', { target_user_id: noFactor.id, role: 'moderator' }, ownerAal2)
expect([res.status, (res.body as { message?: string }).message]).toEqual([400, 'target_factor_missing'])
await sql(`delete from auth.users where id = '${noFactor.id}'`)
})
afterAll(async () => {
for (const a of [owner, target]) if (a?.id) await sql(`delete from auth.users where id = '${a.id}'`).catch(() => {})
})
})
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)
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')
// 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}')`)
}, 120_000)
})
+45
View File
@@ -0,0 +1,45 @@
/**
* RFC 6238 TOTP codes for the sandbox MFA tests (contract
* docs/development/V1-2_ANATOMICAL_SHEETS.md §15): HMAC-SHA1, 30 s steps,
* 6 digits, the parameters GoTrue v2.197.0 uses. Node `crypto` only, no
* dependency. The secret stays in the test's memory: never printed, logged or
* written anywhere.
*/
import { createHmac } from 'node:crypto'
const BASE32 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
export const TOTP_STEP_SECONDS = 30
function base32Decode(text: string): Buffer {
const clean = text.replace(/=+$/, '').toUpperCase()
const bytes: number[] = []
let buffer = 0
let bits = 0
for (const char of clean) {
const value = BASE32.indexOf(char)
if (value < 0) throw new Error('totp: secret is not base32')
buffer = (buffer << 5) | value
bits += 5
if (bits >= 8) {
bits -= 8
bytes.push((buffer >> bits) & 0xff)
}
}
return Buffer.from(bytes)
}
/** The 6-digit code of `secret` for the step holding `at` (ms since epoch). */
export function totpCode(secret: string, at = Date.now()): string {
const counter = Buffer.alloc(8)
counter.writeBigUInt64BE(BigInt(Math.floor(at / 1000 / TOTP_STEP_SECONDS)))
const mac = createHmac('sha1', base32Decode(secret)).update(counter).digest()
const offset = mac[mac.length - 1] & 0x0f
const value = (mac.readUInt32BE(offset) & 0x7fffffff) % 1_000_000
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)
}
@@ -18,6 +18,9 @@ import {
sql,
sqlOutcome,
stack,
} from './stack'
import { enrolTotp, verifyTotp } from './mfa'
import {
uniqueEmail,
type Account,
} from './stack'
@@ -194,11 +197,18 @@ 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 token = owner.body.access_token as string
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!)
const grant = await rpc(
'grant_platform_role',
{ target_user_id: b.id, role: 'support' },