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

+12 -112
View File
@@ -1,43 +1,22 @@
//! Conformance of the integrity rules across the three implementations (review III.4):
//! the fixtures under `tests/conformance` carry what the TypeScript rules reported (frozen by
//! `packages/domain/tests/r2-conformance.test.ts`) and the codes the SQL re-check returns.
//! This suite checks the Rust rules against the first and generates the pgTAP file that checks
//! SQL against the second (`supabase/tests/011_sheet_conformance.sql`, never edited by hand:
//! `FAUNOSTEO_WRITE_CONFORMANCE=1 cargo test -p faunosteo-core --test sheet_conformance`).
//! Conformance of the integrity rules (review III.4): the fixtures under
//! `tests/conformance` carry what the TypeScript rules reported (frozen by
//! `packages/domain/tests/r2-conformance.test.ts`). This suite checks the Rust
//! rules against them.
//!
//! V1-2.1 (M5) removed the SQL business mirror (`private.sheet_document_*`): SQL
//! no longer re-checks the document's business rules, the Rust core is the only
//! authority (contract §12.2). The former `the_sql_expectations…` and
//! `the_pgtap_file_is_generated…` tests and the generated
//! `supabase/tests/011_sheet_conformance.sql` went with it; the fixtures' `sql`
//! key is left in place, unused.
#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)]
mod common;
use std::collections::BTreeSet;
use faunosteo_core::domain::js::parse_json;
use faunosteo_core::domain::sheet::{SheetIssueSeverity, check_sheet_document};
use faunosteo_core::domain::sheet::check_sheet_document;
use serde_json::Value;
const SQL_FILE: &str = "supabase/tests/011_sheet_conformance.sql";
const TAG: &str = "$fixture$";
/// The error codes `private.sheet_document_issues` mirrors (codes only, deduplicated).
const MIRRORED: [&str; 17] = [
"view.main.count",
"view.id.duplicate",
"view.parent.missing",
"view.unreachable",
"view.asset.missing",
"annotation.id.duplicate",
"annotation.view.missing",
"annotation.category.missing",
"annotation.opens_view.invalid",
"annotation.finding_zone.missing",
"annotation.region.missing",
"region.code.duplicate",
"category.id.duplicate",
"finding_zone.id.duplicate",
"reference.id.duplicate",
"finding.reference.missing",
"region.count_range.invalid",
];
fn fixtures() -> Vec<(String, Value)> {
let dir = format!("{}/tests/conformance", env!("CARGO_MANIFEST_DIR"));
let mut names: Vec<String> = std::fs::read_dir(&dir)
@@ -55,14 +34,6 @@ fn fixtures() -> Vec<(String, Value)> {
.collect()
}
fn sql_codes(fixture: &Value) -> Vec<String> {
let codes = fixture["sql"].as_array().unwrap();
codes
.iter()
.map(|c| c.as_str().unwrap().to_owned())
.collect()
}
#[test]
fn the_rust_rules_report_what_the_typescript_rules_reported() {
let all = fixtures();
@@ -78,74 +49,3 @@ fn the_rust_rules_report_what_the_typescript_rules_reported() {
assert_eq!(issues, fixture["rust"]["issues"], "{name}");
}
}
#[test]
fn the_sql_expectations_are_the_mirrored_error_codes() {
for (name, fixture) in fixtures() {
if fixture["rust"]["shape_error"] == Value::Bool(true) {
continue;
}
let check = check_sheet_document(fixture["document"].clone()).unwrap();
let mirrored: BTreeSet<String> = check
.issues
.iter()
.filter(|i| i.severity == SheetIssueSeverity::Error)
.filter(|i| MIRRORED.contains(&i.code.as_str()))
.map(|i| i.code.clone())
.collect();
let expected: Vec<String> = mirrored.into_iter().collect();
assert_eq!(sql_codes(&fixture), expected, "{name}");
}
}
fn sql_literal(codes: &[String]) -> String {
format!("'{{{}}}'::text[]", codes.join(","))
}
fn assertion(name: &str, fixture: &Value) -> String {
let document = serde_json::to_string(&fixture["document"]).unwrap();
assert!(
!document.contains(TAG),
"{name}: dollar-quote tag in the document"
);
let description = fixture["description"].as_str().unwrap().replace('\'', "''");
let stem = name.trim_end_matches(".json");
format!(
"select is(\n array(select c from unnest(private.sheet_document_issues({TAG}{document}{TAG}::jsonb)) as c order by c collate \"C\"),\n {},\n 'conformance {stem}: {description}'\n);\n",
sql_literal(&sql_codes(fixture))
)
}
fn generated_sql() -> String {
let all = fixtures();
let mut out = String::from(
"-- GENERATED from crates/core/tests/conformance/*.json by crates/core/tests/sheet_conformance.rs:\n\
-- FAUNOSTEO_WRITE_CONFORMANCE=1 cargo test -p faunosteo-core --test sheet_conformance\n\
-- Never edited by hand: cargo fails when this file differs from the fixtures.\n\
-- The SQL publication re-check returns, for each fixture, the error codes the Rust\n\
-- integrity rules report that SQL mirrors (codes only, sorted), plus its own\n\
-- document.shape and reference.url.scheme on documents the shape tier refuses.\n\
begin;\n",
);
out.push_str(&format!("select plan({});\n\n", all.len()));
for (name, fixture) in &all {
out.push_str(&assertion(name, fixture));
out.push('\n');
}
out.push_str("select * from finish();\nrollback;\n");
out
}
#[test]
fn the_pgtap_file_is_generated_from_the_fixtures() {
let expected = generated_sql();
let path = format!("{}/../../{SQL_FILE}", env!("CARGO_MANIFEST_DIR"));
if std::env::var("FAUNOSTEO_WRITE_CONFORMANCE").as_deref() == Ok("1") {
std::fs::write(&path, &expected).unwrap();
}
let committed = std::fs::read_to_string(&path).unwrap_or_default();
assert!(
committed == expected,
"{SQL_FILE} differs from the fixtures: regenerate it (FAUNOSTEO_WRITE_CONFORMANCE=1)"
);
}