Buckets:

download
raw
10.1 kB
# Copyright 2026 Terrene Foundation
# SPDX-License-Identifier: Apache-2.0
"""Canonical JSON utilities for cross-SDK parity validation.
Per SPEC-09 S8.2, Python's ``json.loads()`` silently uses last-wins for
duplicate keys, creating a parser differential with Rust's ``serde_json``
which rejects duplicates by default. This module provides
``canonical_json_loads`` which raises ``DuplicateKeyError`` on duplicate
keys, and ``canonical_json_dumps`` which produces deterministic sorted-key
output.
Used by all cross-SDK deserialization paths to ensure both Python and Rust
parsers reach the same conclusion on every input.
Encoder note: ``canonical_json_dumps`` is the ``kailash.delegate.*`` canonical
encoder and emits **raw UTF-8** (``ensure_ascii=False``). It is distinct from
the trust-plane SIGNING encoder
``kailash.trust.signing.crypto.serialize_for_signing``, which emits
**ASCII-escaped** ``\\uXXXX`` (``ensure_ascii=True``). The divergence is
per-subsystem and intentional — see ``canonical_json_dumps`` below and issue
#1258.
"""
from __future__ import annotations
import json
from typing import Any
class DuplicateKeyError(ValueError):
"""Raised when a JSON object contains duplicate keys.
Per SPEC-09 S8.2, duplicate keys produce parser-differential
vulnerabilities between Python (last-wins) and Rust (reject).
Canonical parsing rejects duplicates in both SDKs.
"""
def __init__(self, key: str, path: str = "") -> None:
location = f" at {path}" if path else ""
super().__init__(f"duplicate key {key!r}{location}")
self.key = key
self.path = path
def _make_duplicate_checker(path: str = "") -> Any:
"""Create an ``object_pairs_hook`` that rejects duplicate keys."""
def check_duplicates(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
result: dict[str, Any] = {}
for key, value in pairs:
if key in result:
raise DuplicateKeyError(key, path)
result[key] = value
return result
return check_duplicates
def canonical_json_loads(text: str) -> Any:
"""Parse JSON with strict mode and duplicate key rejection.
Rejects NaN, Infinity, and -Infinity literals which are not valid
JSON per RFC 8259 but accepted by Python's ``json.loads`` default.
Args:
text: JSON string to parse.
Returns:
Parsed Python object.
Raises:
DuplicateKeyError: If any JSON object contains duplicate keys.
json.JSONDecodeError: If the JSON is malformed.
ValueError: If NaN or Infinity literals are present.
"""
result = json.loads(
text,
strict=True,
object_pairs_hook=_make_duplicate_checker(),
parse_constant=_reject_nan_inf,
)
return result
def _reject_nan_inf(constant: str) -> None:
"""Reject NaN/Infinity which are not valid JSON per RFC 8259."""
raise ValueError(
f"Invalid JSON constant {constant!r} — NaN and Infinity "
f"are not permitted in canonical JSON (RFC 8259)"
)
def _reject_non_string_keys(
obj: Any, path: str = "$", _seen: set[int] | None = None
) -> None:
"""Reject non-string object keys before canonical serialization.
``json.dumps`` silently coerces ``int`` / ``float`` / ``bool`` / ``None``
object keys to strings (``{1: "a"}`` -> ``'{"1":"a"}'``). The canonical
wire form assumes string keys (RFC 8259 object members), and
``canonical_json_loads`` always yields string keys — so silent coercion
breaks round-trip symmetry between the encode/decode pair. We reject
non-string keys at the producer boundary instead, recursively, so the
failure surfaces at the signing site rather than as a verification
mismatch on another implementation.
Cyclic structures are rejected with ``ValueError`` (mirroring
``json.dumps``'s own ``ValueError("Circular reference detected")``) via a
markers set added on container entry and discarded on exit. This preserves
the call sites' ``except (TypeError, ValueError)`` exception taxonomy
rather than letting the pure-Python recursion raise an uncaught
``RecursionError`` (a ``RuntimeError`` subclass) before ``json.dumps`` runs.
Shared (DAG) substructures are NOT rejected — only true cycles, exactly
like ``json.dumps``.
Raises:
ValueError: If any object key (at any nesting depth) is not a ``str``,
or if ``obj`` contains a circular reference.
"""
if _seen is None:
_seen = set()
if isinstance(obj, (dict, list, tuple)):
obj_id = id(obj)
if obj_id in _seen:
raise ValueError(
f"Circular reference detected at {path} — canonical JSON "
f"cannot serialize cyclic structures"
)
_seen.add(obj_id)
try:
if isinstance(obj, dict):
for key, value in obj.items():
if not isinstance(key, str):
raise ValueError(
f"non-string object key {key!r} "
f"({type(key).__name__}) at {path} — canonical JSON "
f"requires string keys (RFC 8259 object members); "
f"coercing would break round-trip symmetry with "
f"canonical_json_loads"
)
_reject_non_string_keys(value, f"{path}.{key}", _seen)
else: # list / tuple
for index, value in enumerate(obj):
_reject_non_string_keys(value, f"{path}[{index}]", _seen)
finally:
_seen.discard(obj_id)
def canonical_json_dumps(obj: Any) -> str:
"""Serialize to canonical JSON with sorted keys and no extra whitespace.
The output is deterministic: keys are sorted alphabetically at every
nesting level, and no trailing whitespace or newlines are emitted.
This matches the canonical encoder order required by SPEC-09 S8.2.
This encoder is symmetric with :func:`canonical_json_loads` on the value
domain it accepts: it rejects (raises) ``NaN`` / ``Infinity`` /
``-Infinity`` (via ``allow_nan=False``) — which are not valid JSON per
RFC 8259 and which the paired decoder already refuses — and it rejects
non-string object keys rather than silently stringifying them. This
guarantees the encoder never produces signing pre-images that its own
decoder, Rust ``serde_json``, or any RFC-8259 verifier cannot read back.
Note: integers outside the JS-safe range (``±(2**53 - 1)``) are NOT
rejected. The canonical parity scope is Python and Rust (``serde_json``),
both of which carry 64-bit+ integers losslessly; common signing payloads
(e.g. nanosecond timestamps) depend on this. JS-consumer ``2**53`` safety
is out of scope (issue #1243 acceptance criterion 3).
Canonical contract (cross-SDK, SPEC-09 S8.2 — ``kailash.delegate.*``):
* ``ensure_ascii=False`` — non-ASCII code points are emitted as **raw
UTF-8 bytes**, NOT ``\\uXXXX`` escapes (``{"name":"漢字"}`` →
``{"name":"漢字"}``, not ``{"name":"\\u6f22\\u5b57"}``). This matches
Rust ``serde_json``'s default ``to_string`` output, which does not
escape non-ASCII, so the delegate cross-SDK signing pre-image is
byte-identical on both SDKs.
* ``sort_keys=True`` + ``separators=(",", ":")`` — keys sorted by Unicode
code point at every level (equivalent to Rust ``BTreeMap<String>`` /
UTF-8 byte order, which agree for valid UTF-8), no inter-token
whitespace.
* **No Unicode normalization.** ``"é"`` (NFC, U+00E9) and ``"é"`` (NFD,
U+0065 U+0301) are DISTINCT signing pre-images — the encoder preserves
the input's code points verbatim, exactly as ``serde_json`` does.
Callers requiring NFC/NFD equivalence MUST normalize upstream.
Sibling encoder — divergence is intentional (issue #1258). The trust-plane
SIGNING family (``kailash.trust.signing.crypto.serialize_for_signing`` plus
the PACT audit-chain hash, the trace-event fingerprint, and the
selective-disclosure signers) uses the OPPOSITE ``ensure_ascii=True``
(``\\uXXXX``-escaped, ASCII-only) because its Rust counterpart and the pinned
fixture ``tests/test-vectors/trust-plane-canonical.json`` (issue #959) escape
non-ASCII. The two families NEVER cross-mix: no delegate code path calls a
signing encoder, and no signing path calls ``canonical_json_dumps``. As of
the 2026-06-20 canonical-conformance fix (issues #1403/#1405),
``serialize_for_signing``, the PACT audit-chain hash
(``AuditAnchor._canonical_input``), and the trace-event fingerprint
(``compute_trace_event_fingerprint``) all share the SAME typed-scalar
whitelist ``kailash.trust._canonical.canonical_scalars`` (Decimal / UUID /
datetime / bytes / Enum / dataclass; NO ``default=str``). The
selective-disclosure witness signers still use a ``default=str`` call site
and so diverge byte-for-byte from the whitelisted members on typed-scalar
inputs — a tracked same-class follow-up (see ``specs/trust-canonical-encoders.md``).
What is uniform across the whole signing family, and OPPOSITE to delegate,
is ``ensure_ascii=True``. Each family matches a different Rust serde
contract, so unifying delegate + signing is a breaking cross-SDK
signing-format migration requiring coordinated Rust-side regeneration — NOT
a casual edit (issue #1258). Byte-vectors for this encoder are pinned in
``tests/test-vectors/delegate-canonical.json``.
Args:
obj: Python object to serialize.
Returns:
Canonical JSON string.
Raises:
ValueError: If ``obj`` contains ``NaN`` / ``Infinity`` / ``-Infinity``
float values, or any non-string object key.
"""
_reject_non_string_keys(obj)
return json.dumps(
obj,
sort_keys=True,
separators=(",", ":"),
ensure_ascii=False,
allow_nan=False,
)

Xet Storage Details

Size:
10.1 kB
·
Xet hash:
3ca6987406dacd6088c8b1832ca66de3cbd4d92aab230f5811e0a80074337c09

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.