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,