Files
bchanot d502dfa923 fix(domain): refuse three non-canonical v3 shapes, R5.5 LOW fixes, R5.6 plan
check_v3_shape at read_report_document v3 and parse_envelope (sheet, practitioner
as non-objects, severity as non-string); Protocol errors final; DEV address must be
an own unicast address. SQL confirm function and DEV keys characterised, no change.
2026-10-24 03:34:38 +02:00

375 lines
12 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())
}
("GET", None) if path.starts_with("/rest/v1/anatomical_sheet_assets") => {
let rows = match &state.row {
None => "[]".to_owned(),
Some((sha, confirmed)) => {
let at = if *confirmed {
"\"2026-10-23T00:00:00Z\""
} else {
"null"
};
format!("[{{\"sha256\":\"{sha}\",\"uploaded_at\":{at}}}]")
}
};
(200, rows.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;
log.iter().filter(|line| line.starts_with("POST")).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);
}