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.
This commit is contained in:
bchanot committed 2026-10-24 03:34:38 +02:00
1 parent 13db5539a3
commit d502dfa923
11 files changed
+369 -37

No files matched your search

@@ -107,11 +107,18 @@ fn required_env(name: &str) -> Result<String, UploadError> {
.ok_or_else(|| refuse(UploadKind::Destination, format!("{name} is required")))
}
/// The DEV address counts only if it is one of this machine's own addresses (a socket can be
/// bound to it); otherwise it is ignored and only loopback stays allowed.
/// The DEV address counts only if it is one of this machine's own unicast addresses: a socket
/// binds to it, and connecting it to that address (no packet is sent) keeps it as the local
/// end. A subnet broadcast binds but refuses the connect (no `SO_BROADCAST`). Otherwise the
/// DEV address is ignored and only loopback stays allowed.
fn own_address(host: &str) -> bool {
host.parse::<std::net::IpAddr>()
.is_ok_and(|ip| std::net::UdpSocket::bind((ip, 0)).is_ok())
let Ok(ip) = host.parse::<std::net::IpAddr>() else {
return false;
};
let Ok(socket) = std::net::UdpSocket::bind((ip, 0)) else {
return false;
};
socket.connect((ip, 9)).is_ok() && socket.local_addr().is_ok_and(|a| a.ip() == ip)
}
fn connect() -> Result<Storage, UploadError> {
@@ -221,3 +228,41 @@ fn main() {
}
}
}
#[cfg(test)]
mod tests {
use super::own_address;
/// `inet` and `brd` addresses of this host, as `ip -4 -o addr` prints them.
fn host_addresses() -> (Vec<String>, Vec<String>) {
let listing = std::process::Command::new("ip")
.args(["-4", "-o", "addr"])
.output()
.map(|output| String::from_utf8_lossy(&output.stdout).into_owned())
.unwrap_or_default();
let field = |line: &str, name: &str| {
let mut words = line.split_whitespace();
words.find(|w| *w == name)?;
Some(words.next()?.split('/').next()?.to_owned())
};
let lines: Vec<&str> = listing.lines().collect();
let unicast = lines.iter().filter_map(|l| field(l, "inet")).collect();
let broadcast = lines.iter().filter_map(|l| field(l, "brd")).collect();
(unicast, broadcast)
}
#[test]
fn only_an_own_unicast_address_counts_as_the_dev_address() {
assert!(own_address("127.0.0.1"));
for refused in ["255.255.255.255", "203.0.113.7", "not-an-ip", ""] {
assert!(!own_address(refused), "{refused}");
}
let (unicast, broadcast) = host_addresses();
for address in &unicast {
assert!(own_address(address), "{address}");
}
for address in &broadcast {
assert!(!own_address(address), "broadcast {address}");
}
}
}
@@ -193,13 +193,13 @@ fn is_transient(error: &ureq::Error) -> bool {
| ureq::Error::Timeout(_)
| ureq::Error::HostNotFound
| ureq::Error::ConnectionFailed
| ureq::Error::Protocol(_)
)
}
/// Not retried: a body over its cap is a destination holding something it should not (an
/// object larger than any drawing), anything else a request the tool cannot build (a key with
/// characters a header refuses). The key itself is never part of the message.
/// object larger than any drawing); anything else is a request the tool cannot build or an
/// answer it cannot read (a key a header refuses, a malformed HTTP answer: `Protocol`), the
/// same on every attempt. The key itself is never part of the message.
fn final_error(error: &ureq::Error) -> UploadError {
match error {
ureq::Error::BodyExceedsLimit(limit) => refuse(
+3 -1
View File
@@ -12,7 +12,7 @@ use ts_rs::TS;
use super::envelope::{ENVELOPE_VERSION, EnvelopeVersion1, EnvelopeWrapper, ReportArchiveEnvelope};
use super::snapshot::SheetSnapshot;
use super::snapshot_rules::{SnapshotRejection, assert_snapshot};
use crate::domain::report::read::{ReadFailure, read_report_document, version_of};
use crate::domain::report::read::{ReadFailure, check_v3_shape, read_report_document, version_of};
use crate::domain::report::{Report, ReportMigrationMap};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
@@ -121,5 +121,7 @@ fn snapshot_matches(snapshot: &SheetSnapshot, report: &Report) -> bool {
/// `ReportArchiveEnvelopeSchema.parse`: the shape of a whole envelope (the snapshot's shape
/// only, no caps nor integrity), as the session keeps it.
pub fn parse_envelope(data: &Value) -> Result<ReportArchiveEnvelope, serde_json::Error> {
let report = data.get("report").unwrap_or(&Value::Null);
check_v3_shape(report).map_err(serde::de::Error::custom)?;
ReportArchiveEnvelope::deserialize(data)
}
+22
View File
@@ -49,6 +49,27 @@ pub fn version_of(data: &Value) -> Option<f64> {
data.as_object()?.get("version")?.as_f64()
}
/// The shapes Zod refused and serde's derives accept (owner go 2026-10-24, RUST.md §11.18):
/// `sheet` and `practitioner` written as positional arrays, a `severity` written as a one-key
/// map. Checked on the raw value before the typed read; nothing else is widened or narrowed.
pub fn check_v3_shape(data: &Value) -> Result<(), String> {
for key in ["sheet", "practitioner"] {
if data.get(key).is_some_and(|value| !value.is_object()) {
return Err(format!("{key}: expected an object"));
}
}
let observations = data.get("observations").and_then(Value::as_array);
for (index, observation) in observations.into_iter().flatten().enumerate() {
let severity = observation.get("severity");
if severity.is_some_and(|value| !value.is_string()) {
return Err(format!(
"observations[{index}].severity: expected a string or null"
));
}
}
Ok(())
}
/// Reads a report document of version 2 or 3 and returns it as v3.
pub fn read_report_document(
data: &Value,
@@ -56,6 +77,7 @@ pub fn read_report_document(
) -> Result<MigrationOutcome, ReadFailure> {
let version = version_of(data);
if version == Some(3.0) {
check_v3_shape(data).map_err(ReadFailure::Invalid)?;
let report = Report::deserialize(data).map_err(ReadFailure::invalid)?;
return Ok(MigrationOutcome {
report,
@@ -1,14 +1,15 @@
//! Characterisation, not a requirement (owner 2026-10-23, R5.5 brief §7): the serde derives of
//! the R2 contracts read a struct from a positional array and a unit enum from a one-key map,
//! where the frozen Zod reader refused both. These cases pin today's Rust verdict so that any
//! change to the gated readers is visible; they are to be turned around, not extended, if the
//! owner decides a strict deserialisation (`docs/development/RUST.md` §11.16).
//! The serde tolerance of the R2 report contract (RUST.md §11.16): serde's derives read a struct
//! from a positional array and a unit enum from a one-key map, where the frozen Zod reader
//! refused both. Owner go 2026-10-24: the three v3 shapes found are refused at the readers'
//! entry (`check_v3_shape`), with a controlled `ReadFailure::Invalid`; the canonical forms and
//! the non-strict unknown fields are read as before (RUST.md §11.18).
#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)]
mod common;
use faunosteo_core::domain::report::Report;
use serde::Deserialize;
use faunosteo_core::domain::archive::parse_envelope;
use faunosteo_core::domain::report::read::check_v3_shape;
use faunosteo_core::domain::report::{ReadFailure, ReportMigrationMap, read_report_document};
use serde_json::{Value, json};
fn demo() -> Value {
@@ -18,41 +19,90 @@ fn demo() -> Value {
.unwrap()
}
fn read(value: &Value) -> Result<Report, serde_json::Error> {
Report::deserialize(value)
fn map() -> ReportMigrationMap {
let (source, _) = common::zod_oracle("migration-map.draft.json");
serde_json::from_str(&source).unwrap()
}
fn read(value: &Value) -> Result<(), ReadFailure> {
read_report_document(value, &map()).map(|_| ())
}
fn sheet_as_array() -> Value {
let mut report = demo();
let parts = [
report["sheet"]["sheetId"].clone(),
Value::Null,
report["sheet"]["documentSha256"].clone(),
];
report["sheet"] = json!(parts);
report
}
fn practitioner_as_array() -> Value {
let mut report = demo();
let p = report["practitioner"].clone();
report["practitioner"] = json!([p["name"], p["cabinet"], p["contact"], p["siret"]]);
report
}
fn severity_as_map() -> Value {
let mut report = demo();
report["observations"][0]["severity"] = json!({ "mild": null });
report
}
fn refused_with(value: &Value, what: &str) {
match read(value) {
Err(ReadFailure::Invalid(message)) => assert!(message.starts_with(what), "{message}"),
other => panic!("{what}: {other:?}"),
}
}
#[test]
fn the_canonical_report_is_read() {
assert!(read(&demo()).is_ok());
assert!(check_v3_shape(&demo()).is_ok());
}
#[test]
fn a_struct_written_as_a_positional_array_is_accepted_where_zod_refused() {
let mut sheet = demo();
let parts = [
sheet["sheet"]["sheetId"].clone(),
Value::Null,
sheet["sheet"]["documentSha256"].clone(),
];
sheet["sheet"] = json!(parts);
let mut practitioner = demo();
let p = practitioner["practitioner"].clone();
practitioner["practitioner"] = json!([p["name"], p["cabinet"], p["contact"], p["siret"]]);
assert!(read(&sheet).is_ok());
assert!(read(&practitioner).is_ok());
fn a_struct_written_as_a_positional_array_is_refused() {
refused_with(&sheet_as_array(), "sheet: expected an object");
refused_with(&practitioner_as_array(), "practitioner: expected an object");
}
#[test]
fn a_unit_enum_written_as_a_one_key_map_is_accepted_where_zod_refused() {
let mut report = demo();
report["observations"][0]["severity"] = json!({ "mild": null });
assert!(read(&report).is_ok());
fn a_unit_enum_written_as_a_one_key_map_is_refused() {
refused_with(
&severity_as_map(),
"observations[0].severity: expected a string",
);
}
#[test]
fn an_unknown_field_is_accepted_as_the_non_strict_zod_objects_did() {
fn an_absent_severity_and_an_unknown_field_are_read_as_before() {
let mut report = demo();
report["observations"][0]
.as_object_mut()
.unwrap()
.remove("severity");
report["extra"] = json!(1);
assert!(read(&report).is_ok());
// `severity` is optional, never nullable: null stays refused, as Zod refused it.
report["observations"][0]["severity"] = Value::Null;
refused_with(&report, "observations[0].severity: expected a string");
}
#[test]
fn the_envelope_entry_refuses_the_same_shapes() {
let envelope: Value = serde_json::from_str(&common::repo_file(
"apps/app/tests/fixtures/goldens/r2/envelope.demo.fr.nologos.json",
))
.unwrap();
assert!(parse_envelope(&envelope).is_ok());
for bad in [sheet_as_array(), practitioner_as_array(), severity_as_map()] {
let mut wrapped = envelope.clone();
wrapped["report"] = bad;
assert!(parse_envelope(&wrapped).is_err());
}
}
+21 -1
View File
@@ -25,6 +25,8 @@ struct State {
row: Option<(String, bool)>,
bucket_status: u16,
fail_confirm: bool,
/// Answer every request with bytes that are not HTTP.
garbage: bool,
log: Vec<String>,
}
@@ -121,7 +123,14 @@ fn serve(state: Shared) -> u16 {
for stream in listener.incoming() {
let mut stream = stream.unwrap();
let (method, path, body) = read_request(&mut stream);
let (status, reply) = route(&mut state.lock().unwrap(), &method, &path, body);
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);
}
});
@@ -352,3 +361,14 @@ fn a_dev_address_that_is_not_this_machine_is_ignored() {
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);
}