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.
380 lines
13 KiB
Rust
380 lines
13 KiB
Rust
//! The `upload-sheet-assets` binary against an in-process stub of the local Supabase API
|
|
//! (R5.5): the plan of a run, what is written and what never is, resume after a partial
|
|
//! failure, refusals by category, network errors, and the key never printed. The stub listens
|
|
//! on loopback with a made-up key; the real local stack is exercised by
|
|
//! `scripts/sheet-assets-e2e.sh`, run by the owner.
|
|
#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)]
|
|
|
|
use std::collections::HashMap;
|
|
use std::io::{BufRead, BufReader, Read, Write};
|
|
use std::net::{TcpListener, TcpStream};
|
|
use std::process::{Command, Output};
|
|
use std::sync::{Arc, Mutex};
|
|
|
|
const KEY: &str = "stub-service-key-0123456789";
|
|
const DRAFT: &str = concat!(
|
|
env!("CARGO_MANIFEST_DIR"),
|
|
"/../../supabase/seed/anatomical-sheets/equine/draft"
|
|
);
|
|
const SHA: &str = "0ea5202fa3b95bac167b87c12ee969ab0272e085b60c2d34dbca6202c5f08541";
|
|
|
|
#[derive(Default)]
|
|
struct State {
|
|
objects: HashMap<String, Vec<u8>>,
|
|
/// `None`: no row. `Some((sha256, confirmed))`.
|
|
row: Option<(String, bool)>,
|
|
bucket_status: u16,
|
|
fail_confirm: bool,
|
|
/// Answer every request with bytes that are not HTTP.
|
|
garbage: bool,
|
|
log: Vec<String>,
|
|
}
|
|
|
|
type Shared = Arc<Mutex<State>>;
|
|
|
|
fn horse() -> Vec<u8> {
|
|
std::fs::read(format!("{DRAFT}/assets/horse.svg")).unwrap()
|
|
}
|
|
|
|
fn read_request(stream: &mut TcpStream) -> (String, String, Vec<u8>) {
|
|
let mut reader = BufReader::new(stream.try_clone().unwrap());
|
|
let mut line = String::new();
|
|
reader.read_line(&mut line).unwrap();
|
|
let mut parts = line.split_whitespace();
|
|
let (method, path) = (
|
|
parts.next().unwrap().to_owned(),
|
|
parts.next().unwrap().to_owned(),
|
|
);
|
|
let mut length = 0;
|
|
loop {
|
|
let mut header = String::new();
|
|
reader.read_line(&mut header).unwrap();
|
|
if header.trim().is_empty() {
|
|
break;
|
|
}
|
|
if let Some(value) = header.to_ascii_lowercase().strip_prefix("content-length:") {
|
|
length = value.trim().parse().unwrap();
|
|
}
|
|
}
|
|
let mut body = vec![0; length];
|
|
reader.read_exact(&mut body).unwrap();
|
|
(method, path, body)
|
|
}
|
|
|
|
fn respond(stream: &mut TcpStream, status: u16, body: &[u8]) {
|
|
let head = format!(
|
|
"HTTP/1.1 {status} X\r\nContent-Length: {}\r\nConnection: close\r\nContent-Type: application/json\r\n\r\n",
|
|
body.len()
|
|
);
|
|
stream.write_all(head.as_bytes()).unwrap();
|
|
stream.write_all(body).unwrap();
|
|
}
|
|
|
|
fn route(state: &mut State, method: &str, path: &str, body: Vec<u8>) -> (u16, Vec<u8>) {
|
|
state.log.push(format!("{method} {path}"));
|
|
let object = path.strip_prefix("/storage/v1/object/anatomical-sheet-assets/");
|
|
match (method, object) {
|
|
("GET", None) if path == "/storage/v1/bucket/anatomical-sheet-assets" => (
|
|
state.bucket_status,
|
|
br#"{"name":"anatomical-sheet-assets","public":false}"#.to_vec(),
|
|
),
|
|
("GET", Some(key)) => match state.objects.get(key) {
|
|
Some(bytes) => (200, bytes.clone()),
|
|
None => (400, br#"{"statusCode":"404","error":"not_found"}"#.to_vec()),
|
|
},
|
|
("POST", Some(key)) if state.objects.contains_key(key) => {
|
|
(400, br#"{"statusCode":"409","error":"Duplicate"}"#.to_vec())
|
|
}
|
|
("POST", Some(key)) => {
|
|
state.objects.insert(key.to_owned(), body);
|
|
(200, b"{}".to_vec())
|
|
}
|
|
("POST", None) if path.ends_with("/rpc/get_sheet_asset_state") => {
|
|
// The operator read RPC (V1-2.1 F12): JSON null when no row exists,
|
|
// else an object with sha256 and uploaded_at.
|
|
let reply = match &state.row {
|
|
None => "null".to_owned(),
|
|
Some((sha, confirmed)) => {
|
|
let at = if *confirmed {
|
|
"\"2026-10-23T00:00:00Z\""
|
|
} else {
|
|
"null"
|
|
};
|
|
format!("{{\"sha256\":\"{sha}\",\"uploaded_at\":{at}}}")
|
|
}
|
|
};
|
|
(200, reply.into_bytes())
|
|
}
|
|
("POST", None) if path.ends_with("/rpc/confirm_sheet_asset_upload") => {
|
|
if state.fail_confirm {
|
|
return (500, b"{}".to_vec());
|
|
}
|
|
if let Some((_, confirmed)) = state.row.as_mut() {
|
|
*confirmed = true;
|
|
}
|
|
(200, b"\"id\"".to_vec())
|
|
}
|
|
_ => (404, b"{}".to_vec()),
|
|
}
|
|
}
|
|
|
|
fn serve(state: Shared) -> u16 {
|
|
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
|
let port = listener.local_addr().unwrap().port();
|
|
std::thread::spawn(move || {
|
|
for stream in listener.incoming() {
|
|
let mut stream = stream.unwrap();
|
|
let (method, path, body) = read_request(&mut stream);
|
|
let mut held = state.lock().unwrap();
|
|
if held.garbage {
|
|
held.log.push(format!("{method} {path}"));
|
|
stream.write_all(b"NOT-HTTP garbage\r\n\r\n").unwrap();
|
|
continue;
|
|
}
|
|
let (status, reply) = route(&mut held, &method, &path, body);
|
|
drop(held);
|
|
respond(&mut stream, status, &reply);
|
|
}
|
|
});
|
|
port
|
|
}
|
|
|
|
/// A stub with the seed applied: the row exists, pending, the bucket answers 200.
|
|
fn stub() -> (Shared, String) {
|
|
let state: Shared = Arc::new(Mutex::new(State {
|
|
row: Some((SHA.to_owned(), false)),
|
|
bucket_status: 200,
|
|
..State::default()
|
|
}));
|
|
let port = serve(Arc::clone(&state));
|
|
(state, format!("http://127.0.0.1:{port}"))
|
|
}
|
|
|
|
fn run(url: &str, args: &[&str]) -> Output {
|
|
Command::new(env!("CARGO_BIN_EXE_upload-sheet-assets"))
|
|
.args(args)
|
|
.env_clear()
|
|
.env("SUPABASE_URL", url)
|
|
.env("SUPABASE_SERVICE_ROLE_KEY", KEY)
|
|
.output()
|
|
.unwrap()
|
|
}
|
|
|
|
fn text(output: &Output) -> String {
|
|
format!(
|
|
"{}{}",
|
|
String::from_utf8_lossy(&output.stdout),
|
|
String::from_utf8_lossy(&output.stderr)
|
|
)
|
|
}
|
|
|
|
fn writes(state: &Shared) -> usize {
|
|
let log = &state.lock().unwrap().log;
|
|
// The asset-state RPC is a POST but a read: it never counts as a write.
|
|
log.iter()
|
|
.filter(|line| line.starts_with("POST") && !line.contains("/rpc/get_sheet_asset_state"))
|
|
.count()
|
|
}
|
|
|
|
#[test]
|
|
fn check_reads_and_writes_nothing() {
|
|
let (state, url) = stub();
|
|
let output = run(&url, &["--check", DRAFT]);
|
|
let said = text(&output);
|
|
assert!(output.status.success(), "{said}");
|
|
assert!(said.contains("would upload, confirm"), "{said}");
|
|
assert_eq!(writes(&state), 0);
|
|
assert!(!said.contains(KEY));
|
|
}
|
|
|
|
#[test]
|
|
fn a_run_uploads_verifies_then_confirms_and_a_rerun_does_nothing() {
|
|
let (state, url) = stub();
|
|
let first = run(&url, &[DRAFT]);
|
|
assert!(first.status.success(), "{}", text(&first));
|
|
{
|
|
let held = state.lock().unwrap();
|
|
assert_eq!(held.objects.get(&format!("{SHA}.svg")), Some(&horse()));
|
|
assert_eq!(held.row, Some((SHA.to_owned(), true)));
|
|
}
|
|
let before = writes(&state);
|
|
let again = run(&url, &[DRAFT]);
|
|
let said = text(&again);
|
|
assert!(again.status.success(), "{said}");
|
|
assert!(said.contains("nothing to do"), "{said}");
|
|
assert_eq!(writes(&state), before);
|
|
}
|
|
|
|
#[test]
|
|
fn different_bytes_under_the_key_are_never_overwritten() {
|
|
let (state, url) = stub();
|
|
state
|
|
.lock()
|
|
.unwrap()
|
|
.objects
|
|
.insert(format!("{SHA}.svg"), b"other".to_vec());
|
|
let output = run(&url, &[DRAFT]);
|
|
let said = text(&output);
|
|
assert_eq!(output.status.code(), Some(1), "{said}");
|
|
assert!(
|
|
said.contains("State") && said.contains("other bytes"),
|
|
"{said}"
|
|
);
|
|
assert_eq!(writes(&state), 0);
|
|
assert_eq!(
|
|
state.lock().unwrap().objects[&format!("{SHA}.svg")],
|
|
b"other"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_missing_or_foreign_row_stops_the_run_before_any_write() {
|
|
for row in [None, Some(("f".repeat(64), false))] {
|
|
let (state, url) = stub();
|
|
state.lock().unwrap().row = row;
|
|
let output = run(&url, &[DRAFT]);
|
|
assert_eq!(output.status.code(), Some(1), "{}", text(&output));
|
|
assert_eq!(writes(&state), 0);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn a_refused_key_is_an_access_refusal_and_never_printed() {
|
|
for status in [401, 403] {
|
|
let (state, url) = stub();
|
|
state.lock().unwrap().bucket_status = status;
|
|
let output = run(&url, &[DRAFT]);
|
|
let said = text(&output);
|
|
assert_eq!(output.status.code(), Some(1), "{said}");
|
|
assert!(said.contains("Access") && !said.contains(KEY), "{said}");
|
|
assert_eq!(writes(&state), 0);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn a_failure_after_the_upload_resumes_with_the_confirmation_only() {
|
|
let (state, url) = stub();
|
|
state.lock().unwrap().fail_confirm = true;
|
|
let broken = run(&url, &[DRAFT]);
|
|
assert_eq!(broken.status.code(), Some(3), "{}", text(&broken));
|
|
assert!(
|
|
state
|
|
.lock()
|
|
.unwrap()
|
|
.objects
|
|
.contains_key(&format!("{SHA}.svg"))
|
|
);
|
|
assert_eq!(state.lock().unwrap().row, Some((SHA.to_owned(), false)));
|
|
{
|
|
let mut held = state.lock().unwrap();
|
|
held.fail_confirm = false;
|
|
held.log.clear();
|
|
}
|
|
let resumed = run(&url, &[DRAFT]);
|
|
assert!(resumed.status.success(), "{}", text(&resumed));
|
|
let log = state.lock().unwrap().log.clone();
|
|
assert!(
|
|
log.iter()
|
|
.all(|l| !l.contains("/storage/v1/object") || l.starts_with("GET"))
|
|
);
|
|
assert_eq!(state.lock().unwrap().row, Some((SHA.to_owned(), true)));
|
|
}
|
|
|
|
#[test]
|
|
fn an_unreachable_destination_is_a_network_error_after_bounded_retries() {
|
|
let free = TcpListener::bind("127.0.0.1:0")
|
|
.unwrap()
|
|
.local_addr()
|
|
.unwrap()
|
|
.port();
|
|
let output = run(&format!("http://127.0.0.1:{free}"), &[DRAFT]);
|
|
let said = text(&output);
|
|
assert_eq!(output.status.code(), Some(3), "{said}");
|
|
assert!(said.contains("Network") && !said.contains(KEY), "{said}");
|
|
}
|
|
|
|
#[test]
|
|
fn destinations_that_are_not_a_local_stack_are_refused_before_any_request() {
|
|
for url in [
|
|
"https://127.0.0.1:54321",
|
|
"http://127.0.0.1",
|
|
"http://10.1.2.3:54321",
|
|
"http://example.test:54321",
|
|
"http://user:pw@127.0.0.1:54321",
|
|
"http://127.0.0.1:54321/rest/v1",
|
|
"",
|
|
] {
|
|
let output = run(url, &[DRAFT]);
|
|
let said = text(&output);
|
|
assert_eq!(output.status.code(), Some(1), "{url}: {said}");
|
|
assert!(said.contains("Destination"), "{url}: {said}");
|
|
assert!(!said.contains("pw"), "{url}: {said}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn a_folder_outside_the_seed_is_refused() {
|
|
let (state, url) = stub();
|
|
let outside = concat!(env!("CARGO_MANIFEST_DIR"), "/src");
|
|
let output = run(&url, &["--check", outside]);
|
|
assert_eq!(output.status.code(), Some(1), "{}", text(&output));
|
|
assert!(state.lock().unwrap().log.is_empty());
|
|
}
|
|
|
|
#[test]
|
|
fn a_usage_error_names_the_usage() {
|
|
let (_, url) = stub();
|
|
let output = run(&url, &["--check"]);
|
|
assert_eq!(output.status.code(), Some(1));
|
|
assert!(text(&output).contains("usage"));
|
|
}
|
|
|
|
#[test]
|
|
fn an_oversized_object_is_a_final_state_refusal_not_retried() {
|
|
let (state, url) = stub();
|
|
let huge = vec![b'x'; 16 * 1024 * 1024 + 2];
|
|
state
|
|
.lock()
|
|
.unwrap()
|
|
.objects
|
|
.insert(format!("{SHA}.svg"), huge);
|
|
let output = run(&url, &[DRAFT]);
|
|
let said = text(&output);
|
|
assert_eq!(output.status.code(), Some(1), "{said}");
|
|
assert!(said.contains("State"), "{said}");
|
|
let log = state.lock().unwrap().log.clone();
|
|
assert_eq!(
|
|
log.iter()
|
|
.filter(|l| l.contains("/storage/v1/object/"))
|
|
.count(),
|
|
1
|
|
);
|
|
assert_eq!(writes(&state), 0);
|
|
}
|
|
|
|
#[test]
|
|
fn a_dev_address_that_is_not_this_machine_is_ignored() {
|
|
let output = Command::new(env!("CARGO_BIN_EXE_upload-sheet-assets"))
|
|
.args(["--check", DRAFT])
|
|
.env_clear()
|
|
.env("SUPABASE_URL", "http://10.255.255.254:54321")
|
|
.env("FAUNOSTEO_DEV_HOST", "10.255.255.254")
|
|
.env("SUPABASE_SERVICE_ROLE_KEY", KEY)
|
|
.output()
|
|
.unwrap();
|
|
let said = text(&output);
|
|
assert_eq!(output.status.code(), Some(1), "{said}");
|
|
assert!(said.contains("Destination"), "{said}");
|
|
}
|
|
|
|
#[test]
|
|
fn a_malformed_answer_is_final_and_not_retried() {
|
|
let (state, url) = stub();
|
|
state.lock().unwrap().garbage = true;
|
|
let output = run(&url, &["--check", DRAFT]);
|
|
let said = text(&output);
|
|
assert_eq!(output.status.code(), Some(1), "{said}");
|
|
assert!(said.contains("not retried"), "{said}");
|
|
assert_eq!(state.lock().unwrap().log.len(), 1);
|
|
}
|