Files
faunosteo/packages/supabase/tests/sandbox/sheets.sandbox.ts
T
bchanot 77e5fa4cf5 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.
2026-10-28 15:52:49 +01:00

92 lines
4.6 KiB
TypeScript

/**
* 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)
})