diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ab6f4f2..6c99e39 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -39,6 +39,13 @@ name: "Test library, CLI and documentation", run: "bash scripts/ci/run.sh tests cargo test --locked --all-features", }, + { + # Cargo unifies features, so a downstream crate can switch serde_json to + # arbitrary_precision under this one. The strict readers must then + # refuse rather than emit the private number marker as an object. + name: "Feature-unification control (serde_json arbitrary_precision)", + run: "bash scripts/ci/run.sh feature-unification cargo test --locked --test feature_unification --features serde_json/arbitrary_precision", + }, { name: "Formatting", run: "bash scripts/ci/run.sh format cargo fmt --all -- --check", diff --git a/.gitignore b/.gitignore index 3a67cde..ba2d884 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ # Generated by Cargo /target +/verification/creusot/target # IDE .idea diff --git a/.proven/coverage-exclusions.tsv b/.proven/coverage-exclusions.tsv index 4ffe176..0ea6c4a 100644 --- a/.proven/coverage-exclusions.tsv +++ b/.proven/coverage-exclusions.tsv @@ -4,13 +4,14 @@ # to the sha256 of its source lines (joined with LF): an edit to an excluded # line makes the entry stale and the gate fails until it is re-justified. # path lines sha256 kind reason -src/bin/ijson-jcs.rs 227 86afdf70a95436e883aa7fc5c06a2ab083719054438f1218d15ebdaf287b4bac unreachable implicit else of `if let Some(permissions)`: in fix mode permissions is always Some (check mode returned earlier) -src/bin/ijson-jcs.rs 280 86afdf70a95436e883aa7fc5c06a2ab083719054438f1218d15ebdaf287b4bac unreachable same as line 227, in fix-jsonl +src/bin/ijson-jcs.rs 236 86afdf70a95436e883aa7fc5c06a2ab083719054438f1218d15ebdaf287b4bac unreachable implicit else of `if let Some(permissions)`: in fix mode permissions is always Some (check mode returned earlier) +src/bin/ijson-jcs.rs 289 86afdf70a95436e883aa7fc5c06a2ab083719054438f1218d15ebdaf287b4bac unreachable same as line 236, in fix-jsonl src/ijson.rs 217 2a44168318e224e1f830fe9ab620aa00dd4f7b3fb19ef4399abf59593cf0756d unreachable u64 at or below 2^53-1 is always also an i64, so the first branch takes it src/ijson.rs 221-224 afced9dbdd974f8cf35d6d3aedbcbd87996442c0cac6277c28ebd26722862bfc unreachable serde_json::Number cannot hold a non-finite double (Number::from_f64 refuses NaN and infinities) src/ijson.rs 234 28d86778615f6af47bb1bc4f40face756749768e5111f114cfa234a5060c25af unreachable implicit else after as_f64(): a serde_json::Number is always i64, u64 or f64 src/jcs.rs 125-126 78794b4982c6b480eda0ee4efa87c54898f9b52aba2a31b5a38520c26e9f39ef unreachable u64 at or below 2^53-1 is always also an i64, so the first branch takes it src/jcs.rs 145 eff5313cfd9eb5a1150c6c7f8f74f8ecbdffd415cd5ed94092b960f0ce737aa3 unreachable es_number_to_string is only called with a Number's f64, which is always finite src/jsonld.rs 89-92 402488d41ddef455de57876a02b952263b009c7276aad704a0651f11073670e3 unreachable JCS output is built from UTF-8 strings and ASCII escapes, so from_utf8 cannot fail -src/strict.rs 45-47 10cec3347de43875134bcc80b462ce19cbe071095b3c736c864bd4d4c98ebf0e unreachable Visitor::expecting is only called for a type mismatch; serde_json's deserialize_any always picks the matching visit_* method -src/strict.rs 187 1e7485fbef031241f6cabf64563ef6f5973ecf51e927241b2147bff185decac8 unreachable a comma at nesting depth 0 is impossible in text that has already parsed as JSON +src/strict.rs 225 1e7485fbef031241f6cabf64563ef6f5973ecf51e927241b2147bff185decac8 unreachable a comma at nesting depth 0 is impossible in text that has already parsed as JSON +src/strict.rs 136-140 99e01e0f0c65800de3bfe37613f07f5d577675b64b7bf0e91eef1127af24b764 environment fail-closed refusal taken only when another crate unifies serde_json/arbitrary_precision into the build; tests/feature_unification.rs executes it in that configuration (CI step "Feature-unification control") +src/strict.rs 48-50 10cec3347de43875134bcc80b462ce19cbe071095b3c736c864bd4d4c98ebf0e unreachable Visitor::expecting is only called for a type mismatch; serde_json 1.0.154 deserialize_any always picks a visit_* method this visitor defines. Instrumented on CI runners but not in every local build diff --git a/src/bin/ijson-jcs.rs b/src/bin/ijson-jcs.rs index e5aadb1..f5c9cf0 100644 --- a/src/bin/ijson-jcs.rs +++ b/src/bin/ijson-jcs.rs @@ -65,6 +65,15 @@ EXIT STATUS: 2 invalid/unreadable input, resource limit, write failure, or usage error "; +/// Write one diagnostic line to stderr without panicking. +/// +/// `eprintln!` panics when stderr cannot be written (a full device, a closed +/// pipe), which turned the documented exit 2 into a panic and exit 101. The +/// diagnostic is best-effort; the exit status is the verdict. +fn diagnostic(message: std::fmt::Arguments<'_>) { + let _ = writeln!(io::stderr().lock(), "{message}"); +} + /// Render a parse/validation failure the way this CLI has always printed it. fn describe(error: &IJsonError) -> String { match error @@ -309,7 +318,7 @@ fn stdin_command( Ok(EXIT_OK) } Err(reason) => { - eprintln!("INVALID : {reason}"); + diagnostic(format_args!("INVALID : {reason}")); Ok(EXIT_INVALID) } } @@ -317,7 +326,9 @@ fn stdin_command( /// Print usage failures to stderr; never misclassify them as validation success. fn usage_error(message: &str) -> u8 { - eprintln!("ijson-jcs: {message}\nTry 'ijson-jcs --help' for usage."); + diagnostic(format_args!( + "ijson-jcs: {message}\nTry 'ijson-jcs --help' for usage." + )); EXIT_INVALID } @@ -419,7 +430,7 @@ fn main() -> ExitCode { match run(&args, &mut out).and_then(|code| out.flush().map(|()| code)) { Ok(code) => ExitCode::from(code), Err(error) => { - eprintln!("ijson-jcs: cannot write stdout: {error}"); + diagnostic(format_args!("ijson-jcs: cannot write stdout: {error}")); ExitCode::from(EXIT_INVALID) } } diff --git a/src/strict.rs b/src/strict.rs index 965ce4f..7fb5059 100644 --- a/src/strict.rs +++ b/src/strict.rs @@ -21,6 +21,7 @@ use serde::de::{self, Deserialize, Deserializer, MapAccess, SeqAccess, Visitor}; use serde_json::{Map, Number, Value}; use std::fmt; +use std::sync::OnceLock; use crate::error::ValidationError; use crate::ijson::{SAFE_UINT_MAX, json_pointer_encode}; @@ -83,21 +84,11 @@ impl<'de, const BINARY64: bool> Visitor<'de> for StrictVisitor { Ok(Value::String(v.to_owned())) } - /// Accept a JSON string (owned). - fn visit_string(self, v: String) -> Result { - Ok(Value::String(v)) - } - /// Accept JSON `null`. fn visit_unit(self) -> Result { Ok(Value::Null) } - /// Accept JSON `null` reported as an absent option. - fn visit_none(self) -> Result { - Ok(Value::Null) - } - /// Accept a JSON array, deserializing each element strictly. fn visit_seq>(self, mut seq: A) -> Result { let mut items = Vec::new(); @@ -123,12 +114,40 @@ impl<'de, const BINARY64: bool> Visitor<'de> for StrictVisitor { } } +/// Refuse to parse when serde_json was built with `arbitrary_precision`. +/// +/// Cargo unifies features across a dependency graph, so another crate can turn +/// that feature on for this one. serde_json then hands a non-integer or +/// out-of-range number to `visit_map` as a one-member object keyed +/// `$serde_json::private::Number`, which a generic visitor cannot tell from a +/// real object with that key: `[1.5]` would canonicalise to an object and +/// `1e400` would be accepted. The binary64 number model is this crate's +/// contract, so every strict reader fails closed instead. +fn require_binary64_number_model() -> Result<(), serde_json::Error> { + static NUMBERS_REACH_THE_VISITOR_AS_NUMBERS: OnceLock = OnceLock::new(); + let sound = *NUMBERS_REACH_THE_VISITOR_AS_NUMBERS.get_or_init(|| { + let mut probe = serde_json::Deserializer::from_str("1.5"); + StrictValue::::deserialize(&mut probe) + .is_ok_and(|StrictValue(value)| value.is_number()) + }); + if sound { + Ok(()) + } else { + Err(de::Error::custom( + "serde_json is built with `arbitrary_precision` (enabled elsewhere in this \ + dependency graph); ijson-jcs strict parsing needs the binary64 number model \ + and refuses to parse", + )) + } +} + /// Parse a complete JSON text, rejecting duplicate object keys. /// /// Returns the same `Value` `serde_json::from_str` would, except that an /// object containing the same key twice is an error rather than being /// collapsed to its last member. pub(crate) fn from_str_no_duplicates(input: &str) -> Result { + require_binary64_number_model()?; let mut deserializer = serde_json::Deserializer::from_str(input); let StrictValue(value) = StrictValue::::deserialize(&mut deserializer)?; deserializer.end()?; @@ -138,6 +157,7 @@ pub(crate) fn from_str_no_duplicates(input: &str) -> Result Result { + require_binary64_number_model()?; let mut deserializer = serde_json::Deserializer::from_str(input); let StrictValue(value) = StrictValue::::deserialize(&mut deserializer)?; deserializer.end()?; diff --git a/tests/cli.rs b/tests/cli.rs index 6544da2..bcd2d69 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -440,3 +440,48 @@ fn stdout_write_failures_are_exit_two_not_panics() { assert!(!error.contains("panicked")); } } + +/// An unwritable stderr must not turn a refusal into a panic (exit 101): the +/// diagnostic is best-effort and the documented exit status is still 2. +#[cfg(target_os = "linux")] +#[test] +fn stderr_write_failures_are_exit_two_not_panics() { + let full = || { + Stdio::from( + fs::OpenOptions::new() + .write(true) + .open("/dev/full") + .unwrap(), + ) + }; + // Invalid stdin: the `INVALID ` diagnostic cannot be written. + let mut child = bin() + .arg("canon") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(full()) + .spawn() + .unwrap(); + child + .stdin + .take() + .unwrap() + .write_all(br#"{"a":1,"a":2}"#) + .unwrap(); + let out = child.wait_with_output().unwrap(); + assert_eq!(out.status.code(), Some(2)); + assert!(out.stdout.is_empty()); + + // Usage error: the usage diagnostic cannot be written. + let out = bin().arg("bogus").stderr(full()).output().unwrap(); + assert_eq!(out.status.code(), Some(2)); + + // Both streams unwritable: the stdout failure cannot be reported either. + let out = bin() + .arg("--help") + .stdout(full()) + .stderr(full()) + .output() + .unwrap(); + assert_eq!(out.status.code(), Some(2)); +} diff --git a/tests/feature_unification.rs b/tests/feature_unification.rs new file mode 100644 index 0000000..76a21ba --- /dev/null +++ b/tests/feature_unification.rs @@ -0,0 +1,131 @@ +// SPDX-License-Identifier: MPL-2.0 +// Copyright (c) 2026 Hyperpolymath Estate +// +// Cargo feature unification: another crate in the dependency graph can enable +// serde_json's `arbitrary_precision` for this crate. serde_json then gives a +// generic visitor a non-integer or out-of-range number as a one-member object +// keyed `$serde_json::private::Number`. +// +// Before the guard in `src/strict.rs`, a build with that feature +// canonicalised `[1.5]` to `[{"$serde_json::private::Number":"1.5"}]` and +// accepted `1e400`. These assertions hold in both configurations, so run them +// twice: +// +// cargo test --locked --test feature_unification +// cargo test --locked --test feature_unification \ +// --features serde_json/arbitrary_precision + +use ijson_jcs::{ + JsonMode, canonicalize_bytes, canonicalize_jsonld_document, canonicalize_records, classify, + is_valid_i_json_string, parse_jcs, parse_json, to_jcs_string, +}; +use serde_json::Value; + +const MAGIC: &str = "$serde_json::private::Number"; + +/// Whether this build of serde_json has `arbitrary_precision`, decided from +/// serde_json alone (its own `Value` reader folds the magic object to a number). +fn arbitrary_precision() -> bool { + serde_json::from_str::(&format!(r#"{{"{MAGIC}":"7"}}"#)) + .is_ok_and(|value| value.is_number()) +} + +/// Every strict text entry point, reduced to canonical text or a refusal. +fn strict_readers(text: &str) -> Vec<(&'static str, Option)> { + let utf8 = |bytes: Vec| String::from_utf8(bytes).unwrap(); + let render = |value: Value| to_jcs_string(&value).unwrap(); + vec![ + ( + "parse_json Strict", + parse_json(text, JsonMode::Strict).ok().map(render), + ), + ( + "parse_json Canonical", + parse_json(text, JsonMode::Canonical).ok().map(render), + ), + ("parse_jcs", parse_jcs(text).ok().map(render)), + ( + "canonicalize_bytes", + canonicalize_bytes(text.as_bytes()).ok().map(utf8), + ), + ( + "canonicalize_jsonld_document", + canonicalize_jsonld_document(text.as_bytes()).ok().map(utf8), + ), + ( + "canonicalize_records", + canonicalize_records(format!("{text}\n").as_bytes()) + .ok() + .map(|bytes| utf8(bytes).trim_end().to_owned()), + ), + ] +} + +/// A number never comes out as the private marker object, whatever features +/// the dependency graph unified. +#[test] +fn numbers_never_canonicalise_to_the_private_marker_object() { + for text in [ + "1.5", + "[1.5]", + "-0", + "1.0", + "0.1e1", + "1e-400", + "100000000000000000000.0", + r#"{"a":[2.5,{"b":-1e-7}]}"#, + ] { + for (reader, output) in strict_readers(text) { + if let Some(output) = output { + assert!( + !output.contains(MAGIC), + "{reader} turned the number in {text} into {output}" + ); + } + } + } +} + +/// A number outside the binary64 range is refused by every strict reader. +#[test] +fn out_of_range_numbers_are_refused() { + for text in ["1e400", "-1e400", "[1E999]", r#"{"a":1.8e308}"#] { + for (reader, output) in strict_readers(text) { + assert_eq!(output, None, "{reader} accepted {text}"); + } + assert!(!is_valid_i_json_string(text), "{text}"); + assert!( + classify(text.as_bytes(), Default::default()).is_err(), + "{text}" + ); + } +} + +/// With the binary64 model the readers work; with `arbitrary_precision` +/// unified in they refuse everything rather than guess. +#[test] +fn strict_readers_work_or_fail_closed() { + let cases = [ + ("[1.5]", "[1.5]"), + ("1", "1"), + (r#"{"b":1,"a":2.50}"#, r#"{"a":2.5,"b":1}"#), + // A real object whose key is the marker is ordinary I-JSON. + ( + r#"{"$serde_json::private::Number":"7"}"#, + r#"{"$serde_json::private::Number":"7"}"#, + ), + ]; + for (text, canonical) in cases { + for (reader, output) in strict_readers(text) { + if arbitrary_precision() { + assert_eq!(output, None, "{reader} must fail closed on {text}"); + } else { + assert_eq!(output.as_deref(), Some(canonical), "{reader}: {text}"); + } + } + } + if arbitrary_precision() { + let error = parse_jcs("1").unwrap_err().to_string(); + assert!(error.contains("arbitrary_precision"), "{error}"); + } +}