Skip to content

Commit 5653daf

Browse files
fix(jcs): count open containers for the nesting bound, so an empty container leaf is refused (a2aproject#1294)
## What `_jcs.canonicalize` bounds nesting at `MAX_DEPTH = 128`, but the counter tracks **values on the path** (0-based) rather than **open containers** (outermost at 1). An empty container is therefore accepted one level past the bound, while the same shape wrapped around a scalar is refused — the effective limit depends on what the innermost value is. This counts open containers instead, and applies the same rule to `signing._clean_empty`, which runs **before** canonicalization and would otherwise be the exhaustion path. ## Why `jcs_depth_v1` (a2aproject/A2A#2246) pins eight inputs and their verdicts; it is added here as `tests/utils/jcs_depth_vectors.json`, retained as published with attribution. On the current code the empty-container case is mis-accepted: | vector | depth | expected | before | after | |---|---|---|---|---| | `jcs-depth-001` … `-004` | 128 | accept | bytes | bytes | | `jcs-depth-101`, `-102` | 129 | reject | `CanonicalizationError` | `CanonicalizationError` | | `jcs-depth-103` (empty-container leaf) | 129 | reject | **bytes returned** | `CanonicalizationError` | | `jcs-depth-104` | 10⁷ | reject | `RecursionError`, at the decode | `RecursionError`, at the decode | `jcs-depth-104` never reaches the walk: the JSON decoder refuses that input first, in both trees. The test accepts either refusal, as the vector asks, rather than claiming the canonicalizer produced it. The intended rule is already written down in this repo — the docstring of `test_nesting_at_the_limit_is_accepted` says "the deepest container is at depth n + 1", i.e. containers with the outermost at 1 — so this makes the implementation match its own stated intent, and that boundary test keeps passing unchanged. ## Tests * `tests/utils/test_jcs.py` gains the corpus-driven tests: every preimage digest checked **before** any expectation is used; accepts compared byte-for-byte against the published bytes and SHA-256; rejects asserted to raise; plus a direct empty-container boundary pair and the same pair through `_clean_empty`. * Without the fix: **3 failed, 180 passed** (the two empty-container cases and the pre-pass case). With it: **205 passed**, `test_jcs.py` and `test_signing.py` both green. * `ruff check` and `ruff format --check` clean on all four files. ## Scope Independent of a2aproject/A2A#2122 and of a2aproject#1287, which are about canonicalization *scope*, not the nesting bound. Nothing at or below the bound changes: the 24 cards in a2aproject/a2a-tck#246 canonicalize byte-identically before and after. Reported at a2aproject/A2A#2255. Corpus authored by Sankalp Gilda (Apache-2.0); the JSON keeps the upstream pointer and states that every expected byte string came from the reference implementation it names. Co-authored-by: mykytanetipa <mykytanetipa@google.com>
1 parent 2f9e44a commit 5653daf

4 files changed

Lines changed: 342 additions & 6 deletions

File tree

‎src/a2a/utils/_jcs.py‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ def canonicalize(obj: Any) -> str:
8181
than `MAX_DEPTH`.
8282
"""
8383
out: list[str] = []
84-
_write(obj, out, 0)
84+
_write(obj, out, 1)
8585
canonical = ''.join(out)
8686
try:
8787
# RFC 8785 canonical output is UTF-8. Round-tripping here rejects
@@ -96,8 +96,13 @@ def canonicalize(obj: Any) -> str:
9696

9797

9898
def _write(obj: Any, out: list[str], depth: int) -> None:
99-
"""Appends the canonical form of `obj` to `out`."""
100-
if depth > MAX_DEPTH:
99+
"""Appends the canonical form of `obj` to `out`.
100+
101+
`depth` is the number of open containers on the path to `obj`, the
102+
outermost at 1. Only containers are recursed into, so only containers
103+
carry a depth worth checking; a scalar's depth is never read.
104+
"""
105+
if isinstance(obj, (list, tuple, dict)) and depth > MAX_DEPTH:
101106
raise CanonicalizationError(
102107
f'nesting exceeds the maximum depth of {MAX_DEPTH}'
103108
)

‎src/a2a/utils/signing.py‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -164,15 +164,16 @@ def signature_verifier(
164164
return signature_verifier
165165

166166

167-
def _clean_empty(d: Any, depth: int = 0) -> Any:
167+
def _clean_empty(d: Any, depth: int = 1) -> Any:
168168
"""Recursively remove empty strings, lists and dicts from a dictionary.
169169
170170
Depth is bounded for the same reason canonicalization is: nesting reaches
171171
this function from `AgentExtension.params`, and without the bound a deeply
172172
nested card exhausts the interpreter stack here, before the canonicalizer
173-
ever gets the chance to reject it.
173+
ever gets the chance to reject it. `depth` counts open containers on the
174+
path to `d`, the outermost at 1, and matches `_jcs.MAX_DEPTH`'s rule.
174175
"""
175-
if depth > MAX_DEPTH:
176+
if isinstance(d, (dict, list)) and depth > MAX_DEPTH:
176177
raise CanonicalizationError(
177178
f'nesting exceeds the maximum depth of {MAX_DEPTH}'
178179
)

‎tests/utils/jcs_depth_vectors.json‎

Lines changed: 227 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,227 @@
1+
{
2+
"corpus": "jcs_depth_v1",
3+
"suite": "a2a-agent-card-signature-conformance",
4+
"layer": "nesting-bound",
5+
"specRef": "https://www.rfc-editor.org/rfc/rfc8785 (no nesting limit stated) and https://a2aproject.org/specification/#841-canonicalization-requirements",
6+
"scope": "The input a canonicalizer must refuse. RFC 8785 pins the bytes a canonicalizer must produce and states no bound on how deeply an input may nest, so two implementations that agree on every byte-level vector can still disagree on whether a deep artifact canonicalizes at all. Canonicalization runs before signature verification, so the walk is reachable without a key.",
7+
"max_depth": 128,
8+
"depth_counting_rule": "Depth counts OPEN CONTAINERS: the outermost brace or bracket is depth 1, and every object or array opened inside it adds one, an empty container included. A counter that charges a level per parsed child instead never charges an empty container and lands one level off - which is what the empty-container vectors separate.",
9+
"reference_impl": "Python rfc8785 0.1.4 (Trail of Bits)",
10+
"attribution": {
11+
"corpus": "jcs_depth_v1",
12+
"author": "Sankalp Gilda",
13+
"license": "Apache-2.0",
14+
"upstream": "https://github.com/a2aproject/A2A/pull/2246 (proposals/content-integrity-profile/vectors/jcs_depth_v1)",
15+
"source_corpus": {
16+
"name": "agent-evidence-vectors",
17+
"suite": "adversarial-execution-evidence-conformance",
18+
"repository": "https://github.com/astrogilda/agent-evidence-vectors"
19+
},
20+
"note": "Retained as published: every expected byte string was produced by canonicalising the materialised preimage with the reference implementation above, and all preimage digests are checked before any expectation is used."
21+
},
22+
"preimage_rule_form": {
23+
"note": "Preimages are given as nesting rules rather than literal JSON so this file stays four levels deep and can be read by a parser that enforces the bound it describes. Materialise as text: for i from 0 to count-1 emit the opener for containers[i % len(containers)] ('{\"a\":' for object, '[' for array), then emit leaf, then emit the matching closers innermost-first.",
24+
"openers": {
25+
"object": "{\"a\":",
26+
"array": "["
27+
},
28+
"closers": {
29+
"object": "}",
30+
"array": "]"
31+
}
32+
},
33+
"vectors": [
34+
{
35+
"vector_id": "jcs-depth-001-object-at-bound",
36+
"description": "128 nested objects, the deepest input the bound admits. A canonicaliser that applies the bound one level early refuses this and is off by one.",
37+
"outcome": "accept",
38+
"depth": 128,
39+
"preimage_rule": {
40+
"form": "nest",
41+
"containers": [
42+
"object"
43+
],
44+
"count": 128,
45+
"leaf": "1"
46+
},
47+
"preimage_bytes": 769,
48+
"preimage_sha256": "a4908c65856c2fb1e94d6b2b55620177bd082f54d43252b9e0648f9ccd53e3fe",
49+
"expected_jcs_bytes_b64": "eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOjF9fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fQ==",
50+
"expected_sha256": "a4908c65856c2fb1e94d6b2b55620177bd082f54d43252b9e0648f9ccd53e3fe",
51+
"trace": {
52+
"corpus": "agent-evidence-vectors"
53+
}
54+
},
55+
{
56+
"vector_id": "jcs-depth-002-array-at-bound",
57+
"description": "128 nested arrays at the bound. Separated from the object case because a depth counter placed only in the object branch never charges an array.",
58+
"outcome": "accept",
59+
"depth": 128,
60+
"preimage_rule": {
61+
"form": "nest",
62+
"containers": [
63+
"array"
64+
],
65+
"count": 128,
66+
"leaf": "1"
67+
},
68+
"preimage_bytes": 257,
69+
"preimage_sha256": "68da6c21da4d39e99f241a56379e98c2053372e77cd74f72400af6d3a37261c3",
70+
"expected_jcs_bytes_b64": "W1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1sxXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV0=",
71+
"expected_sha256": "68da6c21da4d39e99f241a56379e98c2053372e77cd74f72400af6d3a37261c3",
72+
"trace": {
73+
"corpus": "agent-evidence-vectors"
74+
}
75+
},
76+
{
77+
"vector_id": "jcs-depth-003-alternating-at-bound",
78+
"description": "128 containers alternating object, array, object, array at the bound. Catches a counter that tracks one container kind and resets on the other.",
79+
"outcome": "accept",
80+
"depth": 128,
81+
"preimage_rule": {
82+
"form": "nest",
83+
"containers": [
84+
"object",
85+
"array"
86+
],
87+
"count": 128,
88+
"leaf": "1"
89+
},
90+
"preimage_bytes": 513,
91+
"preimage_sha256": "aa4e4f042129f600f2352f2ecd58559409175fd83cf4918c382afc3d33942268",
92+
"expected_jcs_bytes_b64": "eyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbeyJhIjpbMV19XX1dfV19XX1dfV19XX1dfV19XX1dfV19XX1dfV19XX1dfV19XX1dfV19XX1dfV19XX1dfV19XX1dfV19XX1dfV19XX1dfV19XX1dfV19XX1dfV19XX1dfV19XX1dfV19XX1dfV19XX1dfV19XX1dfV19XX1dfV19XX1dfV19",
93+
"expected_sha256": "aa4e4f042129f600f2352f2ecd58559409175fd83cf4918c382afc3d33942268",
94+
"trace": {
95+
"corpus": "agent-evidence-vectors"
96+
}
97+
},
98+
{
99+
"vector_id": "jcs-depth-004-empty-object-leaf-at-bound",
100+
"description": "127 wrapping objects around an empty object. The empty container is itself the 128th open container, so this sits exactly at the bound and is accepted.",
101+
"outcome": "accept",
102+
"depth": 128,
103+
"preimage_rule": {
104+
"form": "nest",
105+
"containers": [
106+
"object"
107+
],
108+
"count": 127,
109+
"leaf": "{}"
110+
},
111+
"preimage_bytes": 764,
112+
"preimage_sha256": "95abadd19f4a27dd41c2e3b46baca7320d039f4e4686fcdaebb0a7d7146bb16e",
113+
"expected_jcs_bytes_b64": "eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7ImEiOnsiYSI6eyJhIjp7fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX0=",
114+
"expected_sha256": "95abadd19f4a27dd41c2e3b46baca7320d039f4e4686fcdaebb0a7d7146bb16e",
115+
"trace": {
116+
"corpus": "agent-evidence-vectors"
117+
}
118+
},
119+
{
120+
"vector_id": "jcs-depth-101-object-one-past-bound",
121+
"description": "129 nested objects, one level past the bound. Differs from jcs-depth-001-object-at-bound by exactly one wrapping object.",
122+
"outcome": "reject",
123+
"depth": 129,
124+
"preimage_rule": {
125+
"form": "nest",
126+
"containers": [
127+
"object"
128+
],
129+
"count": 129,
130+
"leaf": "1"
131+
},
132+
"preimage_bytes": 775,
133+
"preimage_sha256": "eeb23e8c9c090d0303063348ae7ca4a5914992972fc20e295e8e386802e2a95a",
134+
"trace": {
135+
"corpus": "agent-evidence-vectors",
136+
"sibling_vector_id": "v08251931ec038e91"
137+
}
138+
},
139+
{
140+
"vector_id": "jcs-depth-102-array-one-past-bound",
141+
"description": "129 nested arrays, one level past the bound.",
142+
"outcome": "reject",
143+
"depth": 129,
144+
"preimage_rule": {
145+
"form": "nest",
146+
"containers": [
147+
"array"
148+
],
149+
"count": 129,
150+
"leaf": "1"
151+
},
152+
"preimage_bytes": 259,
153+
"preimage_sha256": "84aaf90be3265f8e148bdcc72153a59156d358f74e3dedd2d6a5dd566f5944f5",
154+
"trace": {
155+
"corpus": "agent-evidence-vectors"
156+
}
157+
},
158+
{
159+
"vector_id": "jcs-depth-103-empty-object-leaf-one-past-bound",
160+
"description": "128 wrapping objects around an empty object: open-container depth 129, one past the bound. This is the case a scalar leaf cannot discriminate. A canonicaliser that charges a level per parsed child rather than per opened container never charges the empty object, reads this as depth 128 and accepts it while refusing jcs-depth-101-object-one-past-bound.",
161+
"outcome": "reject",
162+
"depth": 129,
163+
"preimage_rule": {
164+
"form": "nest",
165+
"containers": [
166+
"object"
167+
],
168+
"count": 128,
169+
"leaf": "{}"
170+
},
171+
"preimage_bytes": 770,
172+
"preimage_sha256": "47ec83edd0d185f58e09a843867e31af9088c4da554f55c730c52f547161a8b1",
173+
"trace": {
174+
"corpus": "agent-evidence-vectors",
175+
"sibling_vector_id": "v83f4b7fe6068ef86"
176+
}
177+
},
178+
{
179+
"vector_id": "jcs-depth-104-deep-input-refused-not-crashed",
180+
"description": "500 nested arrays: well past the bound, but shallow enough that the JSON decoder accepts the input (CPython's decoder recurses to about 1000 levels), so the refusal has to come from the depth bound and reach the caller as a catchable rejection rather than as a decoder failure or a stack crash. A payload of ten million levels does not test that: json.loads refuses it before canonicalization is entered at all, so the vector would pin the decoder's own recursion limit instead of the bound.",
181+
"outcome": "reject",
182+
"depth": 500,
183+
"preimage_rule": {
184+
"form": "nest",
185+
"containers": [
186+
"array"
187+
],
188+
"count": 500,
189+
"leaf": "1"
190+
},
191+
"preimage_bytes": 1001,
192+
"preimage_sha256": "a655facd9262ddb5ddf32b1f4f8d937fb2ded910b13fe7f12c44abb2783756eb",
193+
"trace": {
194+
"corpus": "agent-evidence-vectors"
195+
}
196+
}
197+
],
198+
"pair_invariants": [
199+
{
200+
"name": "object_bound_is_exact",
201+
"a": "jcs-depth-001-object-at-bound",
202+
"b": "jcs-depth-101-object-one-past-bound",
203+
"relation": "accept_then_reject",
204+
"why": "The two inputs differ by one wrapping object. An implementation that accepts both has no bound; one that refuses both has the bound off by one. Only the pair locates it."
205+
},
206+
{
207+
"name": "array_bound_is_exact",
208+
"a": "jcs-depth-002-array-at-bound",
209+
"b": "jcs-depth-102-array-one-past-bound",
210+
"relation": "accept_then_reject",
211+
"why": "The same boundary in the array branch, which a counter placed only in the object branch never reaches."
212+
},
213+
{
214+
"name": "empty_container_charges_a_level",
215+
"a": "jcs-depth-004-empty-object-leaf-at-bound",
216+
"b": "jcs-depth-103-empty-object-leaf-one-past-bound",
217+
"relation": "accept_then_reject",
218+
"why": "A per-child counter never charges an empty container, so it reads the second input as depth 128 and accepts it. Both scalar-leaf vectors pass under that counter, which is why this pair exists."
219+
},
220+
{
221+
"name": "refusal_is_not_a_crash",
222+
"vector": "jcs-depth-104-deep-input-refused-not-crashed",
223+
"relation": "reject_without_stack_exhaustion",
224+
"why": "The vector is passed only if the implementation returns a rejection to its caller. A process that dies on this input has not rejected it, and a crash on an unauthenticated artifact is the outcome the bound exists to prevent."
225+
}
226+
]
227+
}

‎tests/utils/test_jcs.py‎

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
own output.
77
"""
88

9+
import base64
10+
import hashlib
911
import json
1012
import math
1113
import random
@@ -368,6 +370,107 @@ def test_deep_arrays_are_bounded():
368370
canonicalize(value)
369371

370372

373+
# --- Nesting bound: the jcs_depth_v1 corpus -------------------------------
374+
375+
# `jcs_depth_vectors.json` is the `jcs_depth_v1` corpus. It pins the input a
376+
# canonicalizer must REFUSE rather than the bytes it must produce, because RFC
377+
# 8785 states no nesting limit and canonicalization runs before signature
378+
# verification. Depth counts open containers, the outermost at depth 1, and an
379+
# empty container is its own level.
380+
_DEPTH_VECTORS = json.loads(
381+
(Path(__file__).parent / 'jcs_depth_vectors.json').read_text(
382+
encoding='utf-8'
383+
)
384+
)
385+
_DEPTH_ACCEPT = [
386+
v for v in _DEPTH_VECTORS['vectors'] if v['outcome'] == 'accept'
387+
]
388+
_DEPTH_REJECT = [
389+
v for v in _DEPTH_VECTORS['vectors'] if v['outcome'] == 'reject'
390+
]
391+
392+
_DEPTH_OPENERS = {'object': '{"a":', 'array': '['}
393+
_DEPTH_CLOSERS = {'object': '}', 'array': ']'}
394+
395+
396+
def _materialise_depth(rule: dict[str, Any]) -> str:
397+
"""Materialises a preimage rule into the JSON text it describes."""
398+
containers = rule['containers']
399+
opened = ''.join(
400+
_DEPTH_OPENERS[containers[i % len(containers)]]
401+
for i in range(rule['count'])
402+
)
403+
closed = ''.join(
404+
_DEPTH_CLOSERS[containers[i % len(containers)]]
405+
for i in range(rule['count'] - 1, -1, -1)
406+
)
407+
return opened + rule['leaf'] + closed
408+
409+
410+
def _empty_leaf_nest(depth: int) -> dict[str, Any]:
411+
"""Wraps `{}` in `depth` objects: the shape an empty container sits in."""
412+
value: Any = {}
413+
for _ in range(depth):
414+
value = {'a': value}
415+
return value
416+
417+
418+
@pytest.mark.parametrize(
419+
'vector', _DEPTH_VECTORS['vectors'], ids=lambda v: v['vector_id']
420+
)
421+
def test_depth_vector_preimage_is_the_pinned_one(vector):
422+
"""The input is checked before the output: a vector built wrong proves nothing."""
423+
encoded = _materialise_depth(vector['preimage_rule']).encode('utf-8')
424+
assert len(encoded) == vector['preimage_bytes']
425+
assert hashlib.sha256(encoded).hexdigest() == vector['preimage_sha256']
426+
427+
428+
@pytest.mark.parametrize('vector', _DEPTH_ACCEPT, ids=lambda v: v['vector_id'])
429+
def test_depth_at_the_bound_is_canonicalised(vector):
430+
"""The deepest input the limit admits, the empty-container leaf included."""
431+
canonical = canonicalize(
432+
json.loads(_materialise_depth(vector['preimage_rule']))
433+
)
434+
encoded = canonical.encode('utf-8')
435+
assert encoded == base64.b64decode(vector['expected_jcs_bytes_b64'])
436+
assert hashlib.sha256(encoded).hexdigest() == vector['expected_sha256']
437+
438+
439+
@pytest.mark.parametrize('vector', _DEPTH_REJECT, ids=lambda v: v['vector_id'])
440+
def test_depth_past_the_bound_is_refused(vector):
441+
"""One container past the limit is refused whatever the innermost value is.
442+
443+
The refusal is `CanonicalizationError` for every reject vector: the deepest
444+
payload here (jcs-depth-104) is far past the bound but still shallow enough
445+
for the JSON decoder to accept it, so the bound - not a decoder limit and
446+
not a stack exhaustion - is what the caller sees.
447+
"""
448+
with pytest.raises(CanonicalizationError):
449+
canonicalize(json.loads(_materialise_depth(vector['preimage_rule'])))
450+
451+
452+
def test_an_empty_container_leaf_is_its_own_level():
453+
"""The case a per-child counter misses.
454+
455+
A counter that charges a level on recursion into a child never charges an
456+
empty container, so it accepts one container too many here while still
457+
refusing the same depth wrapped around a scalar.
458+
"""
459+
at_bound = _empty_leaf_nest(MAX_DEPTH - 1)
460+
assert canonicalize(at_bound) == (
461+
'{"a":' * (MAX_DEPTH - 1) + '{}' + '}' * (MAX_DEPTH - 1)
462+
)
463+
with pytest.raises(CanonicalizationError):
464+
canonicalize(_empty_leaf_nest(MAX_DEPTH))
465+
466+
467+
def test_clean_empty_counts_containers_too():
468+
"""`_clean_empty` runs first, so it has to hold the same bound."""
469+
signing._clean_empty(_empty_leaf_nest(MAX_DEPTH - 1))
470+
with pytest.raises(CanonicalizationError):
471+
signing._clean_empty(_empty_leaf_nest(MAX_DEPTH))
472+
473+
371474
# --- Types with no canonical form ---
372475

373476

0 commit comments

Comments
 (0)