agent-warrant 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,46 @@
1
+ from __future__ import annotations
2
+
3
+ from .canonical import canonicalize
4
+ from .exceptions import RevocationSourceUnreachable, UnresolvableIssuer
5
+ from .grant import CURRENT_VERSION, Grant, PossessionProof, VerifyResult, prove, sign, verify
6
+ from .identity import decode_public_key, encode_public_key, generate_keypair
7
+ from .issuer import HolderKeypair, Issuer, Verifier
8
+ from .resolver import DidWebResolver, IssuerResolver, PinnedResolver
9
+ from .revocation import (
10
+ HttpRevocationChecker,
11
+ HttpRevocationListFetcher,
12
+ RevocationChecker,
13
+ RevocationList,
14
+ RevocationListFetcher,
15
+ StaticRevocationChecker,
16
+ sign_revocation_list,
17
+ )
18
+
19
+ __all__ = [
20
+ "CURRENT_VERSION",
21
+ "DidWebResolver",
22
+ "Grant",
23
+ "HolderKeypair",
24
+ "HttpRevocationChecker",
25
+ "HttpRevocationListFetcher",
26
+ "Issuer",
27
+ "IssuerResolver",
28
+ "PinnedResolver",
29
+ "PossessionProof",
30
+ "RevocationChecker",
31
+ "RevocationList",
32
+ "RevocationListFetcher",
33
+ "RevocationSourceUnreachable",
34
+ "StaticRevocationChecker",
35
+ "UnresolvableIssuer",
36
+ "VerifyResult",
37
+ "Verifier",
38
+ "canonicalize",
39
+ "decode_public_key",
40
+ "encode_public_key",
41
+ "generate_keypair",
42
+ "prove",
43
+ "sign",
44
+ "sign_revocation_list",
45
+ "verify",
46
+ ]
@@ -0,0 +1,224 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import math
5
+ import re
6
+ from collections.abc import Iterable
7
+ from typing import Any
8
+
9
+ # A compact authority claim's scope structure never legitimately needs deep nesting.
10
+ # Bounding it here, at the source, protects every caller of canonicalize() uniformly --
11
+ # found live: canonicalize()'s own pure-Python recursive walk (not json.loads, which
12
+ # decode()'s size cap and RecursionError catch already guard) trips Python's interpreter
13
+ # recursion limit at roughly 2-3KB of nested input, well UNDER the encoded-grant size cap
14
+ # (MAX_ENCODED_GRANT_BYTES=16KB) that was assumed to prevent this class of gap. Patching
15
+ # each of canonicalize()'s call sites individually with a RecursionError catch was
16
+ # considered and rejected: it's exactly the kind of fragile, easy-to-miss-a-spot fix that
17
+ # already missed this same call before (three separate never-raises violations were found
18
+ # in three separate adversarial review passes on this codebase, each via a different
19
+ # unguarded field). Depth-limiting the shared primitive fixes it for every caller at once,
20
+ # present and future.
21
+ MAX_CANONICALIZE_DEPTH = 32
22
+
23
+
24
+ def canonicalize(fields: dict[str, Any]) -> bytes:
25
+ """RFC 8785 (JCS)-style deterministic serialization: sorted keys, compact
26
+ separators, UTF-8 bytes. Signing and verification both route through this
27
+ single implementation -- never re-derived inline (see DESIGN.md's note on
28
+ the two-drifting-implementations anti-pattern this guards against).
29
+
30
+ Only the JCS number-formatting cases this project's own data model can
31
+ ever produce are handled: no floats appear in a Grant/PossessionProof
32
+ (timestamps are floats -- see the explicit rejection below). Deliberately
33
+ narrower than full JCS, not full RFC 8785 conformance.
34
+
35
+ Depth-bounded (see MAX_CANONICALIZE_DEPTH): raises ValueError, not
36
+ RecursionError, on anything nested past a small ceiling. Every caller in
37
+ this project treats ValueError as an expected, caught failure mode --
38
+ RecursionError was not, and every value passed here can be
39
+ attacker-controlled.
40
+ """
41
+ _validate(fields, depth=0)
42
+ return json.dumps(fields, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
43
+
44
+
45
+ def _validate(value: Any, depth: int) -> None:
46
+ if depth > MAX_CANONICALIZE_DEPTH:
47
+ raise ValueError(f"value nested deeper than {MAX_CANONICALIZE_DEPTH} levels; refusing to canonicalize")
48
+ if isinstance(value, bool):
49
+ return
50
+ if isinstance(value, float):
51
+ if not math.isfinite(value):
52
+ raise ValueError(f"non-finite float {value!r} cannot be canonicalized (JCS has no NaN/Infinity)")
53
+ return
54
+ if isinstance(value, dict):
55
+ for inner in value.values():
56
+ _validate(inner, depth + 1)
57
+ return
58
+ if isinstance(value, (list, tuple)):
59
+ for inner in value:
60
+ _validate(inner, depth + 1)
61
+ return
62
+ if isinstance(value, (str, int)) or value is None:
63
+ return
64
+ raise ValueError(f"{type(value).__name__} cannot be canonicalized: not a JSON-representable type")
65
+
66
+
67
+ MAX_STRICT_DECODE_BYTES = 65536
68
+ MAX_STRICT_DECODE_DEPTH = 8
69
+ DOMAIN_SEPARATOR = b"\x00"
70
+ _RECORD_TYPE = re.compile(r"[a-z][a-z0-9-]*")
71
+ MAX_SAFE_INTEGER = 2**53 - 1
72
+ _SURROGATES = re.compile("[\ud800-\udfff]")
73
+ _JSON_WHITESPACE = " \t\n\r"
74
+
75
+
76
+ def strict_decode(
77
+ data: bytes | str,
78
+ *,
79
+ required: Iterable[str],
80
+ optional: Iterable[str] = (),
81
+ integer_fields: Iterable[str] = (),
82
+ max_bytes: int = MAX_STRICT_DECODE_BYTES,
83
+ max_depth: int = MAX_STRICT_DECODE_DEPTH,
84
+ ) -> dict[str, Any]:
85
+ """Decode a JSON object for a new record type, refusing anything ambiguous.
86
+
87
+ Raises ValueError, with a specific message, on: input over max_bytes (counted
88
+ as UTF-8 bytes, also for str input), invalid UTF-8 or JSON, a BOM, leading or
89
+ trailing whitespace, a non-object top level, duplicate keys at any depth,
90
+ floats anywhere (including 1.0 and 1e3), NaN/Infinity, -0, integers outside
91
+ +/-(2**53-1), lone surrogates in keys or strings, nesting past max_depth, keys
92
+ outside required + optional, missing required keys, and any integer_fields
93
+ value that is not an int (bool is refused). required, optional and
94
+ integer_fields must not be a str (TypeError).
95
+
96
+ Applies no Unicode normalisation: strings decode byte-for-byte as sent.
97
+ """
98
+ required_set = _field_set("required", required)
99
+ allowed = required_set | _field_set("optional", optional)
100
+ integers = _field_set("integer_fields", integer_fields)
101
+ try:
102
+ raw = data.encode("utf-8") if isinstance(data, str) else data
103
+ except UnicodeEncodeError:
104
+ raise ValueError("input contains a lone surrogate") from None
105
+ if len(raw) > max_bytes:
106
+ raise ValueError(f"input is {len(raw)} bytes, over the {max_bytes} byte limit")
107
+ try:
108
+ text = raw.decode("utf-8")
109
+ if text != text.strip(_JSON_WHITESPACE):
110
+ raise ValueError("input has leading or trailing whitespace")
111
+ value = json.loads(
112
+ text,
113
+ object_pairs_hook=_reject_duplicate_keys,
114
+ parse_int=_parse_int,
115
+ parse_float=_reject_float,
116
+ parse_constant=_reject_constant,
117
+ )
118
+ except RecursionError:
119
+ raise ValueError("input nested too deeply to decode") from None
120
+ except UnicodeDecodeError as exc:
121
+ raise ValueError(f"input is not valid UTF-8: {exc.reason}") from None
122
+ except json.JSONDecodeError as exc:
123
+ raise ValueError(f"input is not valid JSON: {exc.msg}") from None
124
+ if not isinstance(value, dict):
125
+ raise ValueError(f"top level must be a JSON object, got {type(value).__name__}")
126
+ _check_value(value, 1, max_depth)
127
+ unknown = sorted(set(value) - allowed)
128
+ if unknown:
129
+ raise ValueError(f"unknown keys: {', '.join(unknown)}")
130
+ missing = sorted(required_set - set(value))
131
+ if missing:
132
+ raise ValueError(f"missing required keys: {', '.join(missing)}")
133
+ for name in sorted(integers & set(value)):
134
+ field = value[name]
135
+ if isinstance(field, bool) or not isinstance(field, int):
136
+ raise ValueError(f"{name} must be an integer, got {type(field).__name__}")
137
+ return value
138
+
139
+
140
+ def signing_input(record_type: str, version: int, body: dict[str, Any]) -> bytes:
141
+ """Bytes to sign or verify for a new record type: the domain tag
142
+ agent-warrant/<record_type>/v<version>, a NUL separator, then the canonical
143
+ body. The tag is part of the signed bytes, so a signature over one record
144
+ type never verifies as another type or version.
145
+
146
+ body must be a dict with str keys whose values are str, int, bool, None, list
147
+ or dict, recursively (no tuple, float or bytes), nested at most
148
+ MAX_STRICT_DECODE_DEPTH levels, with no lone surrogates and integers within
149
+ +/-(2**53-1). Signatures cover only these re-canonicalized bytes; the raw
150
+ input a body was decoded from is never hashed.
151
+ """
152
+ if not _RECORD_TYPE.fullmatch(record_type):
153
+ raise ValueError(f"record type {record_type!r} must match {_RECORD_TYPE.pattern}")
154
+ if isinstance(version, bool) or not isinstance(version, int) or version < 1:
155
+ raise ValueError(f"version must be a positive integer, got {version!r}")
156
+ if not isinstance(body, dict):
157
+ raise ValueError(f"body must be a dict, got {type(body).__name__}")
158
+ _check_value(body, 1, MAX_STRICT_DECODE_DEPTH)
159
+ tag = f"agent-warrant/{record_type}/v{version}".encode()
160
+ return tag + DOMAIN_SEPARATOR + canonicalize(body)
161
+
162
+
163
+ def _reject_duplicate_keys(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
164
+ result: dict[str, Any] = {}
165
+ for key, value in pairs:
166
+ if key in result:
167
+ raise ValueError(f"duplicate key {key!r}")
168
+ result[key] = value
169
+ return result
170
+
171
+
172
+ def _reject_float(literal: str) -> float:
173
+ raise ValueError(f"floats are not allowed: {literal}")
174
+
175
+
176
+ def _reject_constant(literal: str) -> float:
177
+ raise ValueError(f"{literal} is not allowed")
178
+
179
+
180
+ def _field_set(name: str, value: Iterable[str]) -> frozenset[str]:
181
+ if isinstance(value, str):
182
+ raise TypeError(f"{name} must be a collection of field names, not a str")
183
+ return frozenset(value)
184
+
185
+
186
+ def _parse_int(literal: str) -> int:
187
+ if literal == "-0":
188
+ raise ValueError("-0 is not allowed")
189
+ return int(literal)
190
+
191
+
192
+ def _check_string(value: str) -> None:
193
+ if _SURROGATES.search(value):
194
+ raise ValueError("lone surrogate code point in string")
195
+
196
+
197
+ def _check_value(value: Any, depth: int, limit: int) -> None:
198
+ if isinstance(value, bool) or value is None:
199
+ return
200
+ if isinstance(value, str):
201
+ _check_string(value)
202
+ return
203
+ if isinstance(value, int):
204
+ if abs(value) > MAX_SAFE_INTEGER:
205
+ raise ValueError(f"integer {value} is outside +/-{MAX_SAFE_INTEGER}")
206
+ return
207
+ if isinstance(value, float):
208
+ raise ValueError(f"floats are not allowed: {value!r}")
209
+ if isinstance(value, dict):
210
+ if depth > limit:
211
+ raise ValueError(f"nesting deeper than {limit} levels")
212
+ for key, inner in value.items():
213
+ if not isinstance(key, str):
214
+ raise ValueError(f"keys must be str, got {type(key).__name__}")
215
+ _check_string(key)
216
+ _check_value(inner, depth + 1, limit)
217
+ return
218
+ if isinstance(value, list):
219
+ if depth > limit:
220
+ raise ValueError(f"nesting deeper than {limit} levels")
221
+ for inner in value:
222
+ _check_value(inner, depth + 1, limit)
223
+ return
224
+ raise ValueError(f"{type(value).__name__} is not an allowed value type")