From 0a03218d9dfbfec4689484bebc7953c91c7837cf Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 01:23:25 +0000 Subject: [PATCH] Check member order after sorting instead of trusting the sort Owner ruling of 2026-12-01. write_object_jcs sorts members with slice::sort_by and then requires their keys to be strictly increasing in UTF-16 code-unit order (jcs_core::strictly_increasing, with a Pearlite contract); otherwise it returns CanonicalizationError::MemberOrder. The trusted part of the sort shrinks to its being a permutation. BREAKING: CanonicalizationError gains the variant MemberOrder; the enum is not non_exhaustive. Recorded in the new CHANGELOG.adoc. Members are now collected once as (key bytes, value) pairs, which also removes the per-key map lookup. No verifier has been run; J-6 stays OPEN. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01J4QvDfneftEg71bUadt3v3 --- .proven/coverage-exclusions.tsv | 2 + CHANGELOG.adoc | 17 +++++ src/error.rs | 6 ++ src/jcs.rs | 62 +++++++++++++------ src/jcs_core.rs | 53 ++++++++++++++++ tests/proven_properties.rs | 1 + verification/PROOF-STATUS.adoc | 22 ++++--- verification/creusot/tests/contracts_parse.rs | 2 +- 8 files changed, 136 insertions(+), 29 deletions(-) create mode 100644 CHANGELOG.adoc diff --git a/.proven/coverage-exclusions.tsv b/.proven/coverage-exclusions.tsv index b58e120..44992e2 100644 --- a/.proven/coverage-exclusions.tsv +++ b/.proven/coverage-exclusions.tsv @@ -15,3 +15,5 @@ src/jcs_core.rs 49 8cf9087aa9d19bdaa3e01a4606ae1ec5607e672b8b054df2dac968c575039 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/jcs.rs 209 6b6ccb1f7e6f9f0d6a4e4c6b9bee21a2e9566526c8fa098225283e6548045e30 unreachable the post-sort order check fails only if slice::sort_by returns keys out of order; unit test test_member_order_is_certified_not_trusted executes the refusal +src/jcs_core.rs 100 c00e5a509bf1ff69a5fa4a34e4153692519950f1dcbec7010308105f37fbce82 unreachable reached only when sorted keys are out of order (see src/jcs.rs:209); unit test strictly_increasing_refuses_disorder_and_repeats executes it diff --git a/CHANGELOG.adoc b/CHANGELOG.adoc new file mode 100644 index 0000000..15e549c --- /dev/null +++ b/CHANGELOG.adoc @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: CC-BY-SA-4.0 += ijson-jcs changelog + +== Unreleased (before any 0.1 tag) + +=== Breaking + +* `CanonicalizationError` has a new variant, `MemberOrder`. The enum is not + `#[non_exhaustive]`, so a `match` over it without a wildcard arm stops + compiling. Owner ruling of 2026-12-01. + +=== Changed + +* `to_jcs` no longer trusts the sort for member order. After sorting an + object's members it checks that their keys are strictly increasing in + UTF-16 code-unit order, and returns `CanonicalizationError::MemberOrder` + otherwise. No input is known to produce that error. diff --git a/src/error.rs b/src/error.rs index 1be2f58..d4a8d55 100644 --- a/src/error.rs +++ b/src/error.rs @@ -224,6 +224,12 @@ pub enum CanonicalizationError { /// Output buffer error #[error("Output buffer error")] BufferError, + + /// After sorting, the members of an object were not in strictly + /// increasing UTF-16 code-unit order of their keys. The canonical writer + /// checks this instead of trusting the sort; it is not expected to occur. + #[error("Object members are not in canonical order after sorting (internal check)")] + MemberOrder, } impl CanonicalizationError { diff --git a/src/jcs.rs b/src/jcs.rs index d4a4a26..98a3766 100644 --- a/src/jcs.rs +++ b/src/jcs.rs @@ -168,41 +168,46 @@ fn write_array_jcs(arr: &[Value], out: &mut Vec) -> Result<(), Canonicalizat Ok(()) } -/// Write an object in JCS format with keys sorted by UTF-16 code unit order +/// Write an object in JCS format, members in UTF-16 code-unit order of +/// their keys (RFC 8785 §3.2.3). +/// +/// The order is not taken on trust from the sort: after sorting, the keys +/// are checked to be strictly increasing, and anything else is an error. +/// A strictly increasing sequence under a total order is the one sorted +/// arrangement of its keys, so output written here is in canonical order. fn write_object_jcs( map: &serde_json::Map, out: &mut Vec, ) -> Result<(), CanonicalizationError> { - // Collect keys and sort by UTF-16 code unit order - let mut keys: Vec<&String> = map.keys().collect(); - sort_keys_utf16(&mut keys); + let mut members: Vec<(&[u8], &Value)> = map + .iter() + .map(|(key, value)| (key.as_bytes(), value)) + .collect(); + // The comparison never ties on distinct keys, and the keys of one object + // are distinct, so the result does not depend on the sort being stable. + members.sort_by(|a, b| jcs_core::cmp_utf16(a.0, b.0)); + certify_member_order(&members)?; out.push(b'{'); - for (i, key) in keys.iter().enumerate() { + for (i, (key, value)) in members.iter().enumerate() { if i > 0 { out.push(b','); } - - write_string_jcs(key, out); + jcs_core::write_string_literal(key, out); out.push(b':'); - - // Write the value - write_canonical(&map[*key], out)?; + write_canonical(value, out)?; } out.push(b'}'); Ok(()) } -/// Sort string keys by UTF-16 code unit order as required by JCS (RFC 8785) -/// -/// JCS specifies: "Recursively sort the members of all objects by the -/// UTF-16 code unit order of their keys." -/// -/// This is NOT the same as simple string comparison for non-ASCII keys. -/// The comparison never ties on distinct keys, and the keys of one object -/// are distinct, so the result does not depend on the sort being stable. -fn sort_keys_utf16(keys: &mut [&String]) { - keys.sort_by(|a, b| jcs_core::cmp_utf16(a.as_bytes(), b.as_bytes())); +/// Refuse members whose keys are not strictly increasing in UTF-16 order. +fn certify_member_order(members: &[(&[u8], V)]) -> Result<(), CanonicalizationError> { + if jcs_core::strictly_increasing(members) { + Ok(()) + } else { + Err(CanonicalizationError::MemberOrder) + } } #[cfg(test)] @@ -210,6 +215,23 @@ mod tests { use super::*; use serde_json::json; + /// Must-fail control for the post-sort check: members that are not in + /// strictly increasing UTF-16 order are refused, never written. + #[test] + fn test_member_order_is_certified_not_trusted() { + let null = Value::Null; + let members = |keys: &[&'static str]| -> Vec<(&'static [u8], &Value)> { + keys.iter().map(|key| (key.as_bytes(), &null)).collect() + }; + assert_eq!(certify_member_order(&members(&["a", "b"])), Ok(())); + for disorder in [&["b", "a"][..], &["a", "a"], &["\u{ffe0}", "\u{10000}"]] { + assert_eq!( + certify_member_order(&members(disorder)), + Err(CanonicalizationError::MemberOrder), + "{disorder:?}" + ); + } + } #[test] fn test_keys_sorted_minimal_separators() { let value = json!({"b": 1, "a": {"z": true, "m": [1, 2, "x"]}, "c": null}); diff --git a/src/jcs_core.rs b/src/jcs_core.rs index b379946..05c2be5 100644 --- a/src/jcs_core.rs +++ b/src/jcs_core.rs @@ -79,6 +79,31 @@ pub(crate) fn cmp_utf16(a: &[u8], b: &[u8]) -> Ordering { a.len().cmp(&b.len()) } +/// Whether the keys of `members` are strictly increasing in UTF-16 order. +/// +/// This is the check that makes member order a proved property instead of a +/// trusted one: the caller sorts with the standard library, then refuses to +/// write unless this returns `true`. Strictly increasing also means no key +/// occurs twice. +#[cfg_attr(creusot, check(terminates))] +#[cfg_attr(creusot, ensures(result ==> forall 0 < i && i < members@.len() + ==> key_less((members@[i - 1].0)@, (members@[i].0)@)))] +pub(crate) fn strictly_increasing(members: &[(&[u8], V)]) -> bool { + let mut i = 1; + #[cfg_attr(creusot, variant(members@.len() - i@))] + #[cfg_attr(creusot, invariant(1 <= i@))] + #[cfg_attr(creusot, invariant(forall 0 < j && j < i@ && j < members@.len() + ==> key_less((members@[j - 1].0)@, (members@[j].0)@)))] + while i < members.len() { + match cmp_utf16(members[i - 1].0, members[i].0) { + Ordering::Less => {} + _ => return false, + } + i += 1; + } + true +} + // --------------------------------------------------------------------------- // String escaping (RFC 8785 §3.2.2.2) // --------------------------------------------------------------------------- @@ -462,6 +487,34 @@ mod tests { } } + /// The order check accepts exactly the strictly increasing sequences: + /// it refuses a swap, a repeat, and a UTF-8-ordered pair that is out of + /// UTF-16 order. + #[test] + fn strictly_increasing_refuses_disorder_and_repeats() { + let members = |keys: &[&'static str]| -> Vec<(&'static [u8], ())> { + keys.iter().map(|key| (key.as_bytes(), ())).collect() + }; + for sorted in [ + &[][..], + &["a"], + &["", "a", "ab", "b"], + &["a", "\u{10000}", "\u{ffe0}"], + ] { + assert!(strictly_increasing(&members(sorted)), "{sorted:?}"); + } + for unsorted in [ + &["b", "a"][..], + &["a", "a"], + &["a", "c", "b"], + &["ab", "a"], + // Sorted as UTF-8 bytes, but not as UTF-16 code units. + &["\u{ffe0}", "\u{10000}"], + ] { + assert!(!strictly_increasing(&members(unsorted)), "{unsorted:?}"); + } + } + /// `Equal` is returned for identical byte strings and no others. #[test] fn equal_means_identical() { diff --git a/tests/proven_properties.rs b/tests/proven_properties.rs index 09cc2fc..ae6744f 100644 --- a/tests/proven_properties.rs +++ b/tests/proven_properties.rs @@ -286,6 +286,7 @@ proptest! { CanonicalizationError::StringEncodingError(path.clone()), CanonicalizationError::CyclicReference, CanonicalizationError::BufferError, + CanonicalizationError::MemberOrder, ] { prop_assert!(!other.is_validation_error()); prop_assert!(!other.to_string().is_empty()); diff --git a/verification/PROOF-STATUS.adoc b/verification/PROOF-STATUS.adoc index 05c5ef6..7d405b3 100644 --- a/verification/PROOF-STATUS.adoc +++ b/verification/PROOF-STATUS.adoc @@ -279,13 +279,19 @@ The domain is complete for one character; longer strings follow from the writer being per byte, which is J-4. |J-6 Members are written in strictly increasing `key_less` order -|Not annotated: `write_object_jcs` works on `serde_json::Map` and calls -`slice::sort_by` +|Creusot on `src/jcs_core.rs::strictly_increasing`: when it returns `true`, +every adjacent pair of keys is in `key_less` order. `write_object_jcs` sorts +with `slice::sort_by`, then refuses with `CanonicalizationError::MemberOrder` +unless that check passes (owner ruling of 2026-12-01). The three lines of +`write_object_jcs` that call the check and write in slice order are not in +Creusot's scope (they handle `serde_json::Map`) and are read, not proved |V-5, not written |`OPEN` -|creusot-std 0.15.0 has no contract for `sort_by`. Rests on J-2 and on -A-3. Option put to the owner: check the order after sorting (a proved linear -scan) instead of trusting the sort. +|Not run. The order no longer rests on the sort: A-3 now covers only that the +sorted slice is a permutation of the map's members. `TESTED` evidence: +`strictly_increasing_refuses_disorder_and_repeats`, +`test_member_order_is_certified_not_trusted` (must-fail controls, 9 cases); 2 +planted mutants of the check fail the tests. |J-7 Byte determinism: `to_jcs` output depends only on the value, not on map iteration order @@ -321,8 +327,8 @@ Trust boundaries for this section (policy §1.1): once), `Number::as_i64`, `as_u64`, `as_f64`; and its tokenizer for the reader |`ASSUMED` |A-2 |ryu-js 1.0.x `Buffer::format_finite` returns ECMAScript `Number::toString` for every finite double |`ASSUMED` -|A-3 |Rust std `slice::sort_by` returns a permutation ordered by the -comparator when the comparator is a total order |`ASSUMED` +|A-3 |Rust std `slice::sort_by` returns a permutation of its input (the order is +checked afterwards, see J-6) |`ASSUMED` |A-4 |Rust std `i64::to_string` is the decimal numeral |`ASSUMED` |A-5 |A Rust `str` is well-formed UTF-8 (language invariant) |`ASSUMED` |=== @@ -330,7 +336,7 @@ comparator when the comparator is a total order |`ASSUMED` Receipt for what was executed (2026-12-01, this section's change): * `cargo test --manifest-path verification/creusot/Cargo.toml`: pearlite-syn - 0.15.0 parses all 33 contract terms in `src/jcs_core.rs` and all 4 in + 0.15.0 parses all 37 contract terms in `src/jcs_core.rs` and all 4 in `verification/creusot/src/controls.rs`; three malformed terms are refused. This is a syntax check. It does not type-check the contracts. * `cargo test --locked --lib jcs_core`: 6 differential tests pass; 5 planted diff --git a/verification/creusot/tests/contracts_parse.rs b/verification/creusot/tests/contracts_parse.rs index fd401b7..d0e740c 100644 --- a/verification/creusot/tests/contracts_parse.rs +++ b/verification/creusot/tests/contracts_parse.rs @@ -90,7 +90,7 @@ fn contracts_in(relative: &str) -> Contracts { #[test] fn every_contract_is_well_formed_pearlite() { for (file, expected) in [ - ("../../src/jcs_core.rs", 33), + ("../../src/jcs_core.rs", 37), ("../../src/ijson_core.rs", 7), ("src/controls.rs", 6), ] {