Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .proven/coverage-exclusions.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -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
17 changes: 17 additions & 0 deletions CHANGELOG.adoc
Original file line number Diff line number Diff line change
@@ -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.
6 changes: 6 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
62 changes: 42 additions & 20 deletions src/jcs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,48 +168,70 @@ fn write_array_jcs(arr: &[Value], out: &mut Vec<u8>) -> 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<String, Value>,
out: &mut Vec<u8>,
) -> 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<V>(members: &[(&[u8], V)]) -> Result<(), CanonicalizationError> {
if jcs_core::strictly_increasing(members) {
Ok(())
} else {
Err(CanonicalizationError::MemberOrder)
}
}

#[cfg(test)]
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});
Expand Down
53 changes: 53 additions & 0 deletions src/jcs_core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<i> 0 < i && i < members@.len()
==> key_less((members@[i - 1].0)@, (members@[i].0)@)))]
pub(crate) fn strictly_increasing<V>(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<j> 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)
// ---------------------------------------------------------------------------
Expand Down Expand Up @@ -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() {
Expand Down
1 change: 1 addition & 0 deletions tests/proven_properties.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand Down
22 changes: 14 additions & 8 deletions verification/PROOF-STATUS.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -321,16 +327,16 @@ 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`
|===

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
Expand Down
2 changes: 1 addition & 1 deletion verification/creusot/tests/contracts_parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
] {
Expand Down
Loading