sm-conformance 0.3.1__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.
- sm_conformance/__init__.py +57 -0
- sm_conformance/_badge_vector_gen.py +252 -0
- sm_conformance/badge.py +390 -0
- sm_conformance/countersign.py +149 -0
- sm_conformance/py.typed +0 -0
- sm_conformance/schema/common.schema.json +31 -0
- sm_conformance/schema/conformance-envelope.schema.json +99 -0
- sm_conformance/schema/counter-signed-envelope.schema.json +41 -0
- sm_conformance/vectors/canonicalization.json +91 -0
- sm_conformance/verify_badge.py +321 -0
- sm_conformance-0.3.1.dist-info/METADATA +154 -0
- sm_conformance-0.3.1.dist-info/RECORD +15 -0
- sm_conformance-0.3.1.dist-info/WHEEL +4 -0
- sm_conformance-0.3.1.dist-info/entry_points.txt +2 -0
- sm_conformance-0.3.1.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""sm-conformance — mechanical, cryptographically-attestable protocol conformance.
|
|
2
|
+
|
|
3
|
+
A signed **conformance badge**: a runtime runs a vectors-driven suite, then ships
|
|
4
|
+
a JSON envelope signed by its own Ed25519 key recording which suite (pinned by a
|
|
5
|
+
``suite_digest``) it passed and the counts. Anyone can re-verify the badge
|
|
6
|
+
offline against the ``signed_by`` did:key — no service on the path.
|
|
7
|
+
|
|
8
|
+
Public surface::
|
|
9
|
+
|
|
10
|
+
from sm_conformance import sign_envelope, verify_envelope, compute_suite_digest
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from sm_conformance.badge import (
|
|
16
|
+
ED25519_MULTICODEC_PREFIX,
|
|
17
|
+
RUN_SURFACE_KEY,
|
|
18
|
+
RUN_TARGET_KEY,
|
|
19
|
+
VerificationError,
|
|
20
|
+
canonical_json,
|
|
21
|
+
compute_suite_digest,
|
|
22
|
+
derive_did_key,
|
|
23
|
+
load_signing_key,
|
|
24
|
+
parse_did_key,
|
|
25
|
+
run_extensions,
|
|
26
|
+
sign_envelope,
|
|
27
|
+
verify_envelope,
|
|
28
|
+
)
|
|
29
|
+
from sm_conformance.countersign import (
|
|
30
|
+
CountersignError,
|
|
31
|
+
counter_sign,
|
|
32
|
+
is_countersigned,
|
|
33
|
+
verify_countersigned,
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
__version__ = "0.1.0"
|
|
37
|
+
|
|
38
|
+
__all__ = [
|
|
39
|
+
"ED25519_MULTICODEC_PREFIX",
|
|
40
|
+
"RUN_SURFACE_KEY",
|
|
41
|
+
"RUN_TARGET_KEY",
|
|
42
|
+
"VerificationError",
|
|
43
|
+
"canonical_json",
|
|
44
|
+
"compute_suite_digest",
|
|
45
|
+
"derive_did_key",
|
|
46
|
+
"load_signing_key",
|
|
47
|
+
"parse_did_key",
|
|
48
|
+
"run_extensions",
|
|
49
|
+
"sign_envelope",
|
|
50
|
+
"verify_envelope",
|
|
51
|
+
# trust-ladder rung 2 — counter-signature
|
|
52
|
+
"CountersignError",
|
|
53
|
+
"counter_sign",
|
|
54
|
+
"is_countersigned",
|
|
55
|
+
"verify_countersigned",
|
|
56
|
+
"__version__",
|
|
57
|
+
]
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
"""ARP Conformance Badge vector generator.
|
|
2
|
+
|
|
3
|
+
One-shot tool. Run from repo root to regenerate every vector in
|
|
4
|
+
``tests/fixtures/``. Vectors are deterministic: the
|
|
5
|
+
signing key seed and all timestamps are fixed, so re-running this
|
|
6
|
+
script produces byte-identical vector files.
|
|
7
|
+
|
|
8
|
+
The vectors exercise SPEC.md §9 verification:
|
|
9
|
+
|
|
10
|
+
- ``valid-signed-badge`` — happy path. Verifies, passes pass-gate.
|
|
11
|
+
- ``tampered-payload`` — payload mutated after signing. §9.5 fail.
|
|
12
|
+
- ``tampered-signature`` — signature byte flipped. §9.5 fail.
|
|
13
|
+
- ``wrong-signer`` — signed_by DID does not match the signing key. §9.5 fail.
|
|
14
|
+
- ``non-didkey-signer`` — signed_by is did:web. §9.2 fail.
|
|
15
|
+
- ``missing-signature`` — signature field absent. §9.1 fail.
|
|
16
|
+
- ``failing-run`` — well-formed envelope with failed > 0. Passes §9.1-9.5
|
|
17
|
+
signature checks; fails §9.7 pass-gate by default; accepted with
|
|
18
|
+
--allow-failures.
|
|
19
|
+
|
|
20
|
+
Each output file is a JSON document with this shape::
|
|
21
|
+
|
|
22
|
+
{
|
|
23
|
+
"id": "<vector-id>",
|
|
24
|
+
"description": "<one-line>",
|
|
25
|
+
"spec_ref": "<conformance.md section refs>",
|
|
26
|
+
"expected_outcome": "verify_pass"
|
|
27
|
+
| "envelope_shape_fail"
|
|
28
|
+
| "didkey_parse_fail"
|
|
29
|
+
| "signature_fail"
|
|
30
|
+
| "pass_gate_fail",
|
|
31
|
+
"verifier_options": { "allow_failures": bool },
|
|
32
|
+
"private_keys": { "runtime": "<base64 seed>" },
|
|
33
|
+
"envelope": { ... } # the badge under test
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
Usage::
|
|
37
|
+
|
|
38
|
+
python conformance/_badge_vector_gen.py
|
|
39
|
+
|
|
40
|
+
Outputs to ``tests/fixtures/``.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
from __future__ import annotations
|
|
44
|
+
|
|
45
|
+
import base64
|
|
46
|
+
import json
|
|
47
|
+
from pathlib import Path
|
|
48
|
+
from typing import Any
|
|
49
|
+
|
|
50
|
+
from sm_conformance.badge import derive_did_key, sign_envelope
|
|
51
|
+
|
|
52
|
+
# Fixed inputs for deterministic vectors. Re-running this script with
|
|
53
|
+
# the same constants produces byte-identical files.
|
|
54
|
+
RUNTIME_SEED = bytes(range(32))
|
|
55
|
+
WRONG_RUNTIME_SEED = bytes(range(32, 64))
|
|
56
|
+
FIXED_COMPLETED_AT = "2026-05-30T12:00:00+00:00"
|
|
57
|
+
FIXED_SIGNED_AT = "2026-05-30T12:00:00+00:00"
|
|
58
|
+
FIXED_SUITE_DIGEST = "sha256:" + "f" * 64 # synthetic digest, not a real run
|
|
59
|
+
|
|
60
|
+
OUTPUT_DIR = Path(__file__).resolve().parent.parent / "tests" / "fixtures"
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _base_payload() -> dict[str, Any]:
|
|
64
|
+
return {
|
|
65
|
+
"schema_version": 1,
|
|
66
|
+
"runtime": "spec-reference",
|
|
67
|
+
"protocol_versions": ["0.3"],
|
|
68
|
+
"suite_digest": FIXED_SUITE_DIGEST,
|
|
69
|
+
"completed_at": FIXED_COMPLETED_AT,
|
|
70
|
+
"exit_status": 0,
|
|
71
|
+
"passed": 46,
|
|
72
|
+
"failed": 0,
|
|
73
|
+
"skipped": 1,
|
|
74
|
+
"xfailed": 0,
|
|
75
|
+
"xpassed": 0,
|
|
76
|
+
"total_vectors": 47,
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _write(name: str, doc: dict[str, Any]) -> None:
|
|
81
|
+
out = OUTPUT_DIR / f"{name}.json"
|
|
82
|
+
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
|
|
83
|
+
out.write_text(json.dumps(doc, indent=2, sort_keys=False) + "\n", encoding="utf-8")
|
|
84
|
+
print(f" wrote {out.relative_to(OUTPUT_DIR.parent.parent)}")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _runtime_keys_block() -> dict[str, str]:
|
|
88
|
+
return {"runtime": base64.b64encode(RUNTIME_SEED).decode("ascii")}
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def gen_valid_signed_badge() -> None:
|
|
92
|
+
envelope = sign_envelope(_base_payload(), RUNTIME_SEED, FIXED_SIGNED_AT)
|
|
93
|
+
_write(
|
|
94
|
+
"valid-signed-badge",
|
|
95
|
+
{
|
|
96
|
+
"id": "valid-signed-badge",
|
|
97
|
+
"description": "Complete envelope, valid signature, passing-run payload.",
|
|
98
|
+
"spec_ref": "conformance.md §4, §7, §9.1-9.7",
|
|
99
|
+
"expected_outcome": "verify_pass",
|
|
100
|
+
"verifier_options": {"allow_failures": False},
|
|
101
|
+
"private_keys": _runtime_keys_block(),
|
|
102
|
+
"envelope": envelope,
|
|
103
|
+
},
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def gen_tampered_payload() -> None:
|
|
108
|
+
envelope = sign_envelope(_base_payload(), RUNTIME_SEED, FIXED_SIGNED_AT)
|
|
109
|
+
# Mutate one payload field after signing — signature now binds the
|
|
110
|
+
# original bytes; canonical_json over the mutated payload differs.
|
|
111
|
+
envelope["payload"]["passed"] = 999
|
|
112
|
+
_write(
|
|
113
|
+
"tampered-payload",
|
|
114
|
+
{
|
|
115
|
+
"id": "tampered-payload",
|
|
116
|
+
"description": "payload.passed mutated from 46 to 999 after signing.",
|
|
117
|
+
"spec_ref": "conformance.md §9.5",
|
|
118
|
+
"expected_outcome": "signature_fail",
|
|
119
|
+
"verifier_options": {"allow_failures": False},
|
|
120
|
+
"private_keys": _runtime_keys_block(),
|
|
121
|
+
"envelope": envelope,
|
|
122
|
+
},
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def gen_tampered_signature() -> None:
|
|
127
|
+
envelope = sign_envelope(_base_payload(), RUNTIME_SEED, FIXED_SIGNED_AT)
|
|
128
|
+
sig_bytes = bytearray(base64.b64decode(envelope["signature"]))
|
|
129
|
+
sig_bytes[0] ^= 0xFF # flip every bit of the first byte
|
|
130
|
+
envelope["signature"] = base64.b64encode(bytes(sig_bytes)).decode("ascii")
|
|
131
|
+
_write(
|
|
132
|
+
"tampered-signature",
|
|
133
|
+
{
|
|
134
|
+
"id": "tampered-signature",
|
|
135
|
+
"description": "First byte of the Ed25519 signature flipped.",
|
|
136
|
+
"spec_ref": "conformance.md §9.5",
|
|
137
|
+
"expected_outcome": "signature_fail",
|
|
138
|
+
"verifier_options": {"allow_failures": False},
|
|
139
|
+
"private_keys": _runtime_keys_block(),
|
|
140
|
+
"envelope": envelope,
|
|
141
|
+
},
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def gen_wrong_signer() -> None:
|
|
146
|
+
envelope = sign_envelope(_base_payload(), RUNTIME_SEED, FIXED_SIGNED_AT)
|
|
147
|
+
# Replace signed_by with the did:key of an UNRELATED runtime key —
|
|
148
|
+
# the signature was made with RUNTIME_SEED but the envelope now
|
|
149
|
+
# claims a different signer; verify against the claimed signer fails.
|
|
150
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
|
|
151
|
+
|
|
152
|
+
wrong_pub = (
|
|
153
|
+
Ed25519PrivateKey.from_private_bytes(WRONG_RUNTIME_SEED).public_key().public_bytes_raw()
|
|
154
|
+
)
|
|
155
|
+
envelope["signed_by"] = derive_did_key(wrong_pub)
|
|
156
|
+
_write(
|
|
157
|
+
"wrong-signer",
|
|
158
|
+
{
|
|
159
|
+
"id": "wrong-signer",
|
|
160
|
+
"description": "signed_by replaced with an unrelated runtime DID after signing.",
|
|
161
|
+
"spec_ref": "conformance.md §9.5",
|
|
162
|
+
"expected_outcome": "signature_fail",
|
|
163
|
+
"verifier_options": {"allow_failures": False},
|
|
164
|
+
"private_keys": {
|
|
165
|
+
"runtime": base64.b64encode(RUNTIME_SEED).decode("ascii"),
|
|
166
|
+
"wrong_runtime": base64.b64encode(WRONG_RUNTIME_SEED).decode("ascii"),
|
|
167
|
+
},
|
|
168
|
+
"envelope": envelope,
|
|
169
|
+
},
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def gen_non_didkey_signer() -> None:
|
|
174
|
+
envelope = sign_envelope(_base_payload(), RUNTIME_SEED, FIXED_SIGNED_AT)
|
|
175
|
+
envelope["signed_by"] = "did:web:example.com"
|
|
176
|
+
_write(
|
|
177
|
+
"non-didkey-signer",
|
|
178
|
+
{
|
|
179
|
+
"id": "non-didkey-signer",
|
|
180
|
+
"description": (
|
|
181
|
+
"signed_by is a did:web; other DID methods are reserved for future versions."
|
|
182
|
+
),
|
|
183
|
+
"spec_ref": "conformance.md §9.2",
|
|
184
|
+
"expected_outcome": "didkey_parse_fail",
|
|
185
|
+
"verifier_options": {"allow_failures": False},
|
|
186
|
+
"private_keys": _runtime_keys_block(),
|
|
187
|
+
"envelope": envelope,
|
|
188
|
+
},
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def gen_missing_signature() -> None:
|
|
193
|
+
envelope = sign_envelope(_base_payload(), RUNTIME_SEED, FIXED_SIGNED_AT)
|
|
194
|
+
del envelope["signature"]
|
|
195
|
+
_write(
|
|
196
|
+
"missing-signature",
|
|
197
|
+
{
|
|
198
|
+
"id": "missing-signature",
|
|
199
|
+
"description": "signature field absent — envelope shape check fails.",
|
|
200
|
+
"spec_ref": "conformance.md §9.1",
|
|
201
|
+
"expected_outcome": "envelope_shape_fail",
|
|
202
|
+
"verifier_options": {"allow_failures": False},
|
|
203
|
+
"private_keys": _runtime_keys_block(),
|
|
204
|
+
"envelope": envelope,
|
|
205
|
+
},
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def gen_failing_run() -> None:
|
|
210
|
+
payload = _base_payload()
|
|
211
|
+
payload["failed"] = 3
|
|
212
|
+
payload["exit_status"] = 1
|
|
213
|
+
payload["passed"] = 43
|
|
214
|
+
envelope = sign_envelope(payload, RUNTIME_SEED, FIXED_SIGNED_AT)
|
|
215
|
+
_write(
|
|
216
|
+
"failing-run",
|
|
217
|
+
{
|
|
218
|
+
"id": "failing-run",
|
|
219
|
+
"description": (
|
|
220
|
+
"Well-formed envelope, valid signature, but payload records "
|
|
221
|
+
"failed=3 and exit_status=1. Verifier rejects by default "
|
|
222
|
+
"(pass-gate, §9.7); accepts with --allow-failures."
|
|
223
|
+
),
|
|
224
|
+
"spec_ref": "conformance.md §9.7",
|
|
225
|
+
"expected_outcome": "pass_gate_fail",
|
|
226
|
+
"verifier_options": {"allow_failures": False},
|
|
227
|
+
"private_keys": _runtime_keys_block(),
|
|
228
|
+
"envelope": envelope,
|
|
229
|
+
},
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
GENERATORS = [
|
|
234
|
+
gen_valid_signed_badge,
|
|
235
|
+
gen_tampered_payload,
|
|
236
|
+
gen_tampered_signature,
|
|
237
|
+
gen_wrong_signer,
|
|
238
|
+
gen_non_didkey_signer,
|
|
239
|
+
gen_missing_signature,
|
|
240
|
+
gen_failing_run,
|
|
241
|
+
]
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def main() -> None:
|
|
245
|
+
print(f"Generating {len(GENERATORS)} badge vectors → {OUTPUT_DIR}")
|
|
246
|
+
for gen in GENERATORS:
|
|
247
|
+
gen()
|
|
248
|
+
print("Done.")
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
if __name__ == "__main__":
|
|
252
|
+
main()
|
sm_conformance/badge.py
ADDED
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
"""Signed conformance badge — generation, canonical encoding, and verification.
|
|
2
|
+
|
|
3
|
+
A conformance badge is the wrapped envelope a runtime ships at
|
|
4
|
+
``conformance.json`` to prove it passed a suite. ``suite_digest`` pins the
|
|
5
|
+
*vector corpus* that was run (not the runtime's own build) — the runtime's
|
|
6
|
+
build, when known, is recorded separately in the ``conformance.run.build``
|
|
7
|
+
extension (see ``run_extensions``). The badge is signed by the runtime's
|
|
8
|
+
Ed25519 key; the verifier canonically re-encodes the payload and confirms
|
|
9
|
+
the signature against the ``signed_by`` did:key.
|
|
10
|
+
|
|
11
|
+
Envelope shape::
|
|
12
|
+
|
|
13
|
+
{
|
|
14
|
+
"payload": {
|
|
15
|
+
"schema_version": 1,
|
|
16
|
+
"runtime": "spec-reference",
|
|
17
|
+
"protocol_versions": ["0.2", "0.3"],
|
|
18
|
+
"suite_digest": "sha256:<hex>",
|
|
19
|
+
"completed_at": "<iso8601>",
|
|
20
|
+
"exit_status": 0,
|
|
21
|
+
"passed": 47, "failed": 0, "skipped": 1,
|
|
22
|
+
"xfailed": 0, "xpassed": 0
|
|
23
|
+
},
|
|
24
|
+
"signed_by": "did:key:z6Mk...",
|
|
25
|
+
"signed_at": "<iso8601>",
|
|
26
|
+
"signature": "<base64>"
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
The signature is over the UTF-8 bytes of ``canonical_json(payload)``.
|
|
30
|
+
For payloads containing only ASCII strings, ints, bools, null, and
|
|
31
|
+
nested dicts/lists with the same constraint, the encoding is byte-
|
|
32
|
+
identical to RFC 8785 JCS. Non-ASCII or floating-point payloads will
|
|
33
|
+
require proper JCS — flagged as future work for a future SPEC.md version.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
from __future__ import annotations
|
|
37
|
+
|
|
38
|
+
import base64
|
|
39
|
+
import hashlib
|
|
40
|
+
import importlib.resources
|
|
41
|
+
import json
|
|
42
|
+
from pathlib import Path
|
|
43
|
+
from typing import Any
|
|
44
|
+
|
|
45
|
+
import base58
|
|
46
|
+
import jcs
|
|
47
|
+
from cryptography.exceptions import InvalidSignature
|
|
48
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import (
|
|
49
|
+
Ed25519PrivateKey,
|
|
50
|
+
Ed25519PublicKey,
|
|
51
|
+
)
|
|
52
|
+
from jsonschema import Draft202012Validator
|
|
53
|
+
from jsonschema.exceptions import ValidationError
|
|
54
|
+
from referencing import Registry
|
|
55
|
+
from referencing.jsonschema import DRAFT202012
|
|
56
|
+
|
|
57
|
+
ED25519_MULTICODEC_PREFIX = b"\xed\x01"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class CanonicalizationError(Exception):
|
|
61
|
+
"""A value cannot be safely canonicalized for signing (see SPEC.md §6)."""
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _reject_uncanonicalizable(value: Any, path: str = "$") -> None:
|
|
65
|
+
"""Reject anything outside the badge's signed value space.
|
|
66
|
+
|
|
67
|
+
Signed payloads are restricted to ASCII strings, integers, booleans, null,
|
|
68
|
+
and containers thereof. Floats (ambiguous encoding), bytes, and non-ASCII
|
|
69
|
+
strings are rejected *on both the sign and verify paths* — so a value that
|
|
70
|
+
two implementations might canonicalize differently can never be signed or
|
|
71
|
+
accepted in the first place. This is the belt to JCS's suspenders.
|
|
72
|
+
"""
|
|
73
|
+
if value is None or isinstance(value, bool | int): # bool is an int subclass; both allowed
|
|
74
|
+
return
|
|
75
|
+
if isinstance(value, str):
|
|
76
|
+
if not value.isascii():
|
|
77
|
+
raise CanonicalizationError(f"non-ASCII string at {path}: signed values must be ASCII")
|
|
78
|
+
return
|
|
79
|
+
if isinstance(value, list):
|
|
80
|
+
for i, item in enumerate(value):
|
|
81
|
+
_reject_uncanonicalizable(item, f"{path}[{i}]")
|
|
82
|
+
return
|
|
83
|
+
if isinstance(value, dict):
|
|
84
|
+
for key, item in value.items():
|
|
85
|
+
if not isinstance(key, str):
|
|
86
|
+
raise CanonicalizationError(f"non-string object key at {path}")
|
|
87
|
+
if not key.isascii():
|
|
88
|
+
raise CanonicalizationError(f"non-ASCII object key at {path}: {key!r}")
|
|
89
|
+
_reject_uncanonicalizable(item, f"{path}.{key}")
|
|
90
|
+
return
|
|
91
|
+
raise CanonicalizationError(
|
|
92
|
+
f"uncanonicalizable {type(value).__name__} at {path}: badge-signed values must be "
|
|
93
|
+
f"ASCII strings, integers, booleans, null, or containers thereof"
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def canonical_json(payload: dict[str, Any]) -> bytes:
|
|
98
|
+
"""RFC 8785 (JCS) canonical bytes for signing, after a strict value-space check.
|
|
99
|
+
|
|
100
|
+
The reject-guard constrains the input to a value space where JCS is
|
|
101
|
+
unambiguous and matches any other conformant JCS implementation byte-for-byte
|
|
102
|
+
(the ``arp`` receipt suite uses the same library). The two together are what
|
|
103
|
+
make a signature portable across implementations.
|
|
104
|
+
"""
|
|
105
|
+
_reject_uncanonicalizable(payload)
|
|
106
|
+
canonical: bytes = jcs.canonicalize(payload)
|
|
107
|
+
return canonical
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _load_schema(filename: str) -> dict[str, Any]:
|
|
111
|
+
text = (importlib.resources.files("sm_conformance") / "schema" / filename).read_text(
|
|
112
|
+
encoding="utf-8"
|
|
113
|
+
)
|
|
114
|
+
schema: dict[str, Any] = json.loads(text)
|
|
115
|
+
return schema
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _build_registry() -> Registry:
|
|
119
|
+
resources = []
|
|
120
|
+
for filename in ("common.schema.json", "conformance-envelope.schema.json"):
|
|
121
|
+
schema = _load_schema(filename)
|
|
122
|
+
resource = DRAFT202012.create_resource(schema)
|
|
123
|
+
resources.append((filename, resource))
|
|
124
|
+
resources.append((schema["$id"], resource))
|
|
125
|
+
return Registry().with_resources(resources)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
_REGISTRY = _build_registry()
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def make_validator(filename: str) -> Draft202012Validator:
|
|
132
|
+
"""Draft 2020-12 validator for a packaged schema, with cross-file $ref resolution."""
|
|
133
|
+
return Draft202012Validator(_load_schema(filename), registry=_REGISTRY)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
_ENVELOPE_VALIDATOR = make_validator("conformance-envelope.schema.json")
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def derive_did_key(pubkey32: bytes) -> str:
|
|
140
|
+
if len(pubkey32) != 32:
|
|
141
|
+
raise ValueError(f"Ed25519 public key must be 32 bytes, got {len(pubkey32)}")
|
|
142
|
+
prefixed = ED25519_MULTICODEC_PREFIX + pubkey32
|
|
143
|
+
encoded = base58.b58encode(prefixed).decode()
|
|
144
|
+
return f"did:key:z{encoded}"
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def parse_did_key(did_key: str) -> bytes:
|
|
148
|
+
"""Inverse of derive_did_key — returns the 32-byte public key."""
|
|
149
|
+
if not did_key.startswith("did:key:z"):
|
|
150
|
+
raise ValueError(f"not a did:key: {did_key!r}")
|
|
151
|
+
multibase = did_key[len("did:key:z") :]
|
|
152
|
+
decoded = base58.b58decode(multibase)
|
|
153
|
+
if not decoded.startswith(ED25519_MULTICODEC_PREFIX):
|
|
154
|
+
raise ValueError(f"did:key does not encode an Ed25519 key: {did_key!r}")
|
|
155
|
+
pubkey = decoded[len(ED25519_MULTICODEC_PREFIX) :]
|
|
156
|
+
if len(pubkey) != 32:
|
|
157
|
+
raise ValueError(f"decoded key has wrong length: {len(pubkey)}")
|
|
158
|
+
return pubkey
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def compute_suite_digest(vectors_root: Path) -> str:
|
|
162
|
+
"""sha256 over every JSON vector file under ``vectors_root``.
|
|
163
|
+
|
|
164
|
+
Pins a badge to a specific vector corpus. Any change to any vector file
|
|
165
|
+
changes the digest, invalidating prior badges.
|
|
166
|
+
|
|
167
|
+
``vectors_root`` is required and MUST exist and contain at least one
|
|
168
|
+
``*.json`` file. Digesting a missing or empty corpus would return a
|
|
169
|
+
valid-looking hash that pins to nothing — the exact footgun a suite digest
|
|
170
|
+
exists to prevent — so both cases raise instead.
|
|
171
|
+
"""
|
|
172
|
+
vectors_root = Path(vectors_root)
|
|
173
|
+
if not vectors_root.exists():
|
|
174
|
+
raise FileNotFoundError(f"vectors_root does not exist: {vectors_root}")
|
|
175
|
+
hasher = hashlib.sha256()
|
|
176
|
+
# Sort on the POSIX relative-path string, not on Path objects: Path ordering
|
|
177
|
+
# is platform-dependent, so a string sort is what makes the digest identical
|
|
178
|
+
# across OSes. (Pair this with a `.gitattributes` that forces LF on the
|
|
179
|
+
# vectors, or a CRLF checkout on Windows changes the bytes and the digest.)
|
|
180
|
+
rels = sorted(p.relative_to(vectors_root).as_posix() for p in vectors_root.rglob("*.json"))
|
|
181
|
+
if not rels:
|
|
182
|
+
raise ValueError(f"no *.json vectors found under {vectors_root}")
|
|
183
|
+
for rel in rels:
|
|
184
|
+
path = vectors_root / rel
|
|
185
|
+
hasher.update(rel.encode("utf-8"))
|
|
186
|
+
hasher.update(b"\x00")
|
|
187
|
+
hasher.update(path.read_bytes())
|
|
188
|
+
hasher.update(b"\x00")
|
|
189
|
+
return f"sha256:{hasher.hexdigest()}"
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def compute_code_digest(root: Path, pattern: str = "*.py") -> str:
|
|
193
|
+
"""sha256 over the code files (default ``*.py``) under ``root``.
|
|
194
|
+
|
|
195
|
+
``compute_suite_digest`` pins the *vector corpus*; for a suite whose pass/fail
|
|
196
|
+
lives in **test modules**, not vectors (e.g. an HTTP server suite), the corpus
|
|
197
|
+
digest does not pin the deciding code. Emit this as the signed
|
|
198
|
+
``conformance.suite.code_digest`` extension so a relying party can pin the code
|
|
199
|
+
too (and assert it with ``--expected-code-digest``). Same byte-stable scheme as
|
|
200
|
+
the suite digest: POSIX-relative-path-string sort, raw bytes, NUL-delimited —
|
|
201
|
+
pair with a ``.gitattributes`` pinning LF.
|
|
202
|
+
"""
|
|
203
|
+
root = Path(root)
|
|
204
|
+
if not root.exists():
|
|
205
|
+
raise FileNotFoundError(f"code-digest root does not exist: {root}")
|
|
206
|
+
hasher = hashlib.sha256()
|
|
207
|
+
rels = sorted(p.relative_to(root).as_posix() for p in root.rglob(pattern))
|
|
208
|
+
if not rels:
|
|
209
|
+
raise ValueError(f"no {pattern} files found under {root}")
|
|
210
|
+
for rel in rels:
|
|
211
|
+
hasher.update(rel.encode("utf-8"))
|
|
212
|
+
hasher.update(b"\x00")
|
|
213
|
+
hasher.update((root / rel).read_bytes())
|
|
214
|
+
hasher.update(b"\x00")
|
|
215
|
+
return f"sha256:{hasher.hexdigest()}"
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
SUITE_CODE_DIGEST_KEY = "conformance.suite.code_digest"
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
# Informational provenance keys recording *what* a run attested. Two runs of the
|
|
222
|
+
# same runtime against different surfaces (e.g. an offline client suite vs a live
|
|
223
|
+
# server suite) produce payloads that differ only in their counts; these
|
|
224
|
+
# namespaced keys let a reader tell them apart. Forward-compatible additions per
|
|
225
|
+
# SPEC.md §5.2 (the ``conformance.*`` namespace marks them informational, not
|
|
226
|
+
# protocol wire): a verifier MUST preserve and MUST NOT fail on them, but is not
|
|
227
|
+
# required to interpret them. They satisfy the extensionsObject contract in
|
|
228
|
+
# sm_conformance/schema/common.schema.json (namespace-prefixed, >=3 dotted segments).
|
|
229
|
+
RUN_SURFACE_KEY = "conformance.run.surface"
|
|
230
|
+
RUN_TARGET_KEY = "conformance.run.target"
|
|
231
|
+
RUN_BUILD_KEY = "conformance.run.build"
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def run_extensions(surface: str, target: str, build: str | None = None) -> dict[str, str]:
|
|
235
|
+
"""Provenance for a run: ``surface``, the ``target`` it ran against, and the
|
|
236
|
+
runtime ``build`` it tested.
|
|
237
|
+
|
|
238
|
+
Example: ``run_extensions("server", "https://api.example.test", build="a16905c")``.
|
|
239
|
+
``build`` answers an auditor's "which build passed?" — ``suite_digest`` pins the
|
|
240
|
+
*suite corpus*, not the runtime — so record the runtime's commit/version/artifact
|
|
241
|
+
hash here when it is known. Informational only — see SPEC.md §5.2.
|
|
242
|
+
"""
|
|
243
|
+
ext = {
|
|
244
|
+
RUN_SURFACE_KEY: surface,
|
|
245
|
+
RUN_TARGET_KEY: target.rstrip("/"),
|
|
246
|
+
}
|
|
247
|
+
if build is not None:
|
|
248
|
+
ext[RUN_BUILD_KEY] = build
|
|
249
|
+
return ext
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def load_signing_key(path: Path) -> bytes:
|
|
253
|
+
"""Read an Ed25519 private key — 64 hex characters (preferred) or 32 raw bytes.
|
|
254
|
+
|
|
255
|
+
Hex is the canonical format. Raw is best-effort: a legitimate 32-byte raw
|
|
256
|
+
key that happens to end in 0x0a or 0x20 cannot be distinguished from a
|
|
257
|
+
33-byte hex file with trailing whitespace, so this routine never strips
|
|
258
|
+
raw bytes — the file must be exactly 32 bytes long for the raw path.
|
|
259
|
+
"""
|
|
260
|
+
raw = path.read_bytes()
|
|
261
|
+
# Hex path: file is a printable ASCII hex string, possibly with trailing
|
|
262
|
+
# whitespace from an editor. Strip and require exactly 64 hex chars.
|
|
263
|
+
try:
|
|
264
|
+
stripped = raw.decode("ascii").strip()
|
|
265
|
+
except UnicodeDecodeError:
|
|
266
|
+
stripped = None
|
|
267
|
+
if (
|
|
268
|
+
stripped is not None
|
|
269
|
+
and len(stripped) == 64
|
|
270
|
+
and all(c in "0123456789abcdefABCDEF" for c in stripped)
|
|
271
|
+
):
|
|
272
|
+
return bytes.fromhex(stripped)
|
|
273
|
+
# Raw path: file must be exactly 32 bytes, no stripping.
|
|
274
|
+
if len(raw) == 32:
|
|
275
|
+
return raw
|
|
276
|
+
raise ValueError(
|
|
277
|
+
f"signing key file {path} must be 64 hex characters (preferred) "
|
|
278
|
+
f"or exactly 32 raw bytes, got {len(raw)} bytes"
|
|
279
|
+
)
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def sign_envelope(
|
|
283
|
+
payload: dict[str, Any],
|
|
284
|
+
private_key32: bytes,
|
|
285
|
+
signed_at: str,
|
|
286
|
+
) -> dict[str, Any]:
|
|
287
|
+
"""Wrap payload in a signed envelope ready for JSON serialization."""
|
|
288
|
+
if len(private_key32) != 32:
|
|
289
|
+
raise ValueError(f"Ed25519 seed must be 32 bytes, got {len(private_key32)}")
|
|
290
|
+
priv = Ed25519PrivateKey.from_private_bytes(private_key32)
|
|
291
|
+
pub_bytes = priv.public_key().public_bytes_raw()
|
|
292
|
+
did_key = derive_did_key(pub_bytes)
|
|
293
|
+
canonical = canonical_json(payload)
|
|
294
|
+
signature = priv.sign(canonical)
|
|
295
|
+
return {
|
|
296
|
+
"payload": payload,
|
|
297
|
+
"signed_by": did_key,
|
|
298
|
+
"signed_at": signed_at,
|
|
299
|
+
"signature": base64.b64encode(signature).decode("ascii"),
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def build_badge(
|
|
304
|
+
runtime: str,
|
|
305
|
+
*,
|
|
306
|
+
signing_key32: bytes,
|
|
307
|
+
suite_digest: str,
|
|
308
|
+
protocol_versions: list[str],
|
|
309
|
+
completed_at: str,
|
|
310
|
+
passed: int,
|
|
311
|
+
failed: int,
|
|
312
|
+
skipped: int = 0,
|
|
313
|
+
xfailed: int = 0,
|
|
314
|
+
xpassed: int = 0,
|
|
315
|
+
errored: int = 0,
|
|
316
|
+
total_vectors: int | None = None,
|
|
317
|
+
skipped_vectors: list[str] | None = None,
|
|
318
|
+
extensions: dict[str, str] | None = None,
|
|
319
|
+
signed_at: str | None = None,
|
|
320
|
+
) -> dict[str, Any]:
|
|
321
|
+
"""Assemble and sign a conformance badge from a test run's results.
|
|
322
|
+
|
|
323
|
+
The turnkey generator: given the counts — and, when known, the *identities*
|
|
324
|
+
of the skipped vectors (``skipped_vectors``) and run provenance
|
|
325
|
+
(``extensions``, e.g. from :func:`run_extensions`) — produce the signed
|
|
326
|
+
envelope a runtime ships. ``exit_status`` is derived (0 iff ``failed == 0``);
|
|
327
|
+
``signed_at`` defaults to ``completed_at``. Recording *which* vectors were
|
|
328
|
+
skipped is what lets a relying party tell a fully-run badge from one that
|
|
329
|
+
skipped the adversarial cases (SPEC.md §5.2, §9).
|
|
330
|
+
"""
|
|
331
|
+
payload: dict[str, Any] = {
|
|
332
|
+
"schema_version": 1,
|
|
333
|
+
"runtime": runtime,
|
|
334
|
+
"protocol_versions": list(protocol_versions),
|
|
335
|
+
"suite_digest": suite_digest,
|
|
336
|
+
"completed_at": completed_at,
|
|
337
|
+
"exit_status": 0 if failed == 0 else 1,
|
|
338
|
+
"passed": passed,
|
|
339
|
+
"failed": failed,
|
|
340
|
+
"skipped": skipped,
|
|
341
|
+
"xfailed": xfailed,
|
|
342
|
+
"xpassed": xpassed,
|
|
343
|
+
"errored": errored,
|
|
344
|
+
}
|
|
345
|
+
if total_vectors is not None:
|
|
346
|
+
payload["total_vectors"] = total_vectors
|
|
347
|
+
if skipped_vectors is not None:
|
|
348
|
+
payload["skipped_vectors"] = sorted(skipped_vectors)
|
|
349
|
+
if extensions:
|
|
350
|
+
payload["extensions"] = dict(extensions)
|
|
351
|
+
return sign_envelope(payload, signing_key32, signed_at or completed_at)
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
class VerificationError(Exception):
|
|
355
|
+
pass
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def verify_envelope(envelope: dict[str, Any]) -> dict[str, Any]:
|
|
359
|
+
"""Verify a signed envelope. Returns the payload on success; raises otherwise."""
|
|
360
|
+
for field in ("payload", "signed_by", "signed_at", "signature"):
|
|
361
|
+
if field not in envelope:
|
|
362
|
+
raise VerificationError(f"envelope missing required field: {field}")
|
|
363
|
+
payload = envelope["payload"]
|
|
364
|
+
if not isinstance(payload, dict):
|
|
365
|
+
raise VerificationError("payload must be an object")
|
|
366
|
+
try:
|
|
367
|
+
pubkey = parse_did_key(envelope["signed_by"])
|
|
368
|
+
except ValueError as exc:
|
|
369
|
+
raise VerificationError(f"invalid signed_by: {exc}") from exc
|
|
370
|
+
try:
|
|
371
|
+
sig = base64.b64decode(envelope["signature"], validate=True)
|
|
372
|
+
except Exception as exc:
|
|
373
|
+
raise VerificationError(f"signature is not valid base64: {exc}") from exc
|
|
374
|
+
try:
|
|
375
|
+
canonical = canonical_json(payload)
|
|
376
|
+
except CanonicalizationError as exc:
|
|
377
|
+
raise VerificationError(f"payload is not canonicalizable: {exc}") from exc
|
|
378
|
+
pub = Ed25519PublicKey.from_public_bytes(pubkey)
|
|
379
|
+
try:
|
|
380
|
+
pub.verify(sig, canonical)
|
|
381
|
+
except InvalidSignature as exc:
|
|
382
|
+
raise VerificationError("signature verification failed") from exc
|
|
383
|
+
# Authenticate the bytes first (above), then enforce that the signed structure
|
|
384
|
+
# is well-formed — schema constraints are load-bearing on the verify path, not
|
|
385
|
+
# merely a test-time check (SPEC.md §9).
|
|
386
|
+
try:
|
|
387
|
+
_ENVELOPE_VALIDATOR.validate(envelope)
|
|
388
|
+
except ValidationError as exc:
|
|
389
|
+
raise VerificationError(f"envelope failed schema validation: {exc.message}") from exc
|
|
390
|
+
return payload
|