system-design-primer-skill 2.3.0 → 2.4.0

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.
Files changed (66) hide show
  1. package/README.md +15 -7
  2. package/SKILL.md +22 -2
  3. package/VERSION +1 -1
  4. package/evals/README.md +1022 -0
  5. package/evals/system-design-cases.json +414 -0
  6. package/package.json +3 -2
  7. package/references/03-data-and-storage.md +8 -2
  8. package/references/04-caching.md +3 -3
  9. package/references/05-async-and-messaging.md +4 -0
  10. package/references/06-distributed-systems.md +2 -2
  11. package/references/07-reliability-and-resilience.md +7 -3
  12. package/references/08-api-security-observability.md +4 -0
  13. package/references/15-failure-analysis.md +4 -0
  14. package/references/19-agent-security-and-permissions.md +22 -6
  15. package/references/20-agent-state-and-memory.md +4 -0
  16. package/references/22-kubernetes-and-container-platforms.md +1 -1
  17. package/references/24-multi-region-and-disaster-recovery.md +6 -2
  18. package/references/27-production-observability-and-slo.md +4 -0
  19. package/references/28-event-streaming-and-kafka-pulsar.md +6 -0
  20. package/references/32-workflow-orchestration-and-temporal.md +4 -0
  21. package/references/34-postgresql-internals-and-performance.md +2 -0
  22. package/references/35-mysql-innodb-and-performance.md +2 -0
  23. package/references/36-sharding-and-distributed-sql.md +1 -1
  24. package/references/37-consensus-and-distributed-transactions.md +7 -3
  25. package/references/40-zero-downtime-database-migrations.md +3 -3
  26. package/references/48-oauth-oidc-and-passkeys.md +3 -3
  27. package/references/49-iam-rbac-abac-rebac.md +7 -3
  28. package/references/51-secrets-kms-pki-and-key-management.md +4 -0
  29. package/references/52-supply-chain-security-sbom-slsa.md +62 -0
  30. package/references/54-privacy-engineering-and-data-governance.md +4 -0
  31. package/references/55-opentelemetry-and-instrumentation.md +4 -0
  32. package/references/56-distributed-tracing-and-context-propagation.md +4 -0
  33. package/references/59-capacity-planning-and-performance-modeling.md +8 -4
  34. package/references/60-chaos-engineering-and-resilience-experiments.md +4 -0
  35. package/references/61-incident-management-and-postmortems.md +4 -0
  36. package/references/67-storage-infrastructure-and-storage-systems.md +4 -0
  37. package/references/68-tcp-quic-and-network-performance.md +1 -1
  38. package/references/69-task-routing-and-evidence.md +75 -18
  39. package/scripts/audit_chain.py +36 -0
  40. package/scripts/compare_reports.py +43 -0
  41. package/scripts/evaluate.py +475 -0
  42. package/scripts/evaluation_catalog.py +129 -0
  43. package/scripts/evaluation_fingerprints.py +20 -0
  44. package/scripts/evidence_archive.py +79 -0
  45. package/scripts/evidence_signing.py +98 -0
  46. package/scripts/evidence_timestamp.py +441 -0
  47. package/scripts/install.ps1 +2 -2
  48. package/scripts/install.sh +2 -2
  49. package/scripts/report_integrity.py +184 -0
  50. package/scripts/review_consensus.py +77 -0
  51. package/scripts/review_evidence.py +105 -0
  52. package/scripts/review_provenance.py +44 -0
  53. package/scripts/reviewer_calibration.py +215 -0
  54. package/scripts/rubric_compatibility.py +134 -0
  55. package/scripts/run_evals.py +130 -0
  56. package/scripts/run_manifest.py +179 -0
  57. package/scripts/statistical_analysis.py +308 -0
  58. package/scripts/tsa_attestation.py +709 -0
  59. package/scripts/tsa_validation_report.py +627 -0
  60. package/scripts/validate.py +233 -21
  61. package/scripts/verify_build_provenance.py +625 -0
  62. package/scripts/verify_tsa_ocsp.py +962 -0
  63. package/scripts/verify_tsa_revocation.py +782 -0
  64. package/scripts/windows_broker_protocol.py +274 -0
  65. package/scripts/windows_broker_transport.py +141 -0
  66. package/scripts/windows_broker_win32.py +713 -0
@@ -0,0 +1,709 @@
1
+ """Detached Ed25519 attestations for TSA validation reports.
2
+
3
+ The verifier digest is an independently supplied source/package identity claim. A
4
+ signature authenticates the attester's statement; it does not prove that the
5
+ identified verifier executed in an honest environment.
6
+ """
7
+ from __future__ import annotations
8
+ import argparse
9
+ import base64
10
+ import hashlib
11
+ import json
12
+ import re
13
+ import sys
14
+ from datetime import datetime, timedelta, timezone
15
+ from pathlib import Path
16
+ from typing import Any
17
+ from cryptography.hazmat.primitives import serialization
18
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey
19
+ from scripts.evidence_timestamp import verify_timestamp
20
+ from scripts.tsa_validation_report import _build_limitations, _build_overall_assessment
21
+
22
+ SCHEMA_VERSION = 1
23
+ DOMAIN = b"system-design-primer-tsa-validation-attestation-v1\0"
24
+ KEY_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$")
25
+ HEX256 = re.compile(r"^[0-9a-f]{64}$")
26
+ UTC_RE = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?Z$")
27
+ TSA_CHAIN_VALIDATION_SCOPE = (
28
+ "PKIX path validation at the floor/ceiling Unix-second bounds of genTime; "
29
+ "RFC 3161 Accuracy is reported separately and does not widen the -attime interval"
30
+ )
31
+ TSA_CHAIN_VALIDATION_POLICY = (
32
+ "OpenSSL ts -verify uses the caller-pinned -CAfile and explicit empty -CApath/-CAstore, "
33
+ "-auth_level 2, -purpose timestampsign, and -x509_strict at the exact floor/ceiling "
34
+ "Unix-second bound(s) of genTime; pathLenConstraint and Name Constraints enforced by OpenSSL"
35
+ )
36
+ TSA_TIMESTAMP_VERIFICATION_METHOD = (
37
+ "OpenSSL RFC 3161 CMS signature, request/response imprint, nonce (when requested), "
38
+ "and TSA chain verification at genTime"
39
+ )
40
+ ENVELOPE_FIELDS = {"schema_version", "algorithm", "key_id", "attested_at",
41
+ "report_sha256", "verifier_bundle_sha256", "verifier_identity",
42
+ "claims_sha256", "signature"}
43
+ STORE_FIELDS = {"schema_version", "keys"}
44
+ KEY_FIELDS = {"public_key_pem", "status", "not_before", "not_after", "revoked_at"}
45
+
46
+
47
+ def canonical_json(value: Any) -> bytes:
48
+ return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")
49
+
50
+
51
+ def digest_file(path: Path) -> str:
52
+ return hashlib.sha256(path.read_bytes()).hexdigest()
53
+
54
+
55
+ def parse_utc(value: Any, field: str) -> datetime:
56
+ if not isinstance(value, str) or not UTC_RE.fullmatch(value):
57
+ raise ValueError(field + " must be an RFC3339 UTC timestamp ending in Z (up to microsecond precision)")
58
+ try:
59
+ result = datetime.fromisoformat(value[:-1] + "+00:00")
60
+ except ValueError as exc:
61
+ raise ValueError("invalid " + field + " timestamp") from exc
62
+ if result.utcoffset() is None or result.utcoffset().total_seconds() != 0:
63
+ raise ValueError(field + " must be UTC")
64
+ return result
65
+
66
+
67
+ def parse_utc_parts(value: Any, field: str) -> tuple[datetime, str]:
68
+ """Parse UTC GeneralizedTime while retaining arbitrary-precision fractional digits."""
69
+ match = re.fullmatch(
70
+ r"(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d+))?Z",
71
+ value if isinstance(value, str) else "",
72
+ )
73
+ if not match:
74
+ raise ValueError(field + " must be an RFC3339 UTC timestamp ending in Z")
75
+ try:
76
+ whole_second = datetime.fromisoformat(match.group(1) + "+00:00")
77
+ except ValueError as exc:
78
+ raise ValueError("invalid " + field + " timestamp") from exc
79
+ return whole_second, match.group(2) or ""
80
+
81
+
82
+ def parse_rfc3161_gen_time_parts(value: Any, field: str = "gen_time") -> tuple[datetime, str]:
83
+ """Enforce RFC 3161's canonical DER fractional-seconds representation."""
84
+ whole_second, fraction = parse_utc_parts(value, field)
85
+ if fraction.endswith("0"):
86
+ raise ValueError(field + " fractional seconds must omit trailing zeros")
87
+ return whole_second, fraction
88
+
89
+
90
+ def compare_utc_values(left: str, right: str, field: str = "UTC timestamp") -> int:
91
+ """Compare UTC instants without truncating arbitrary fractional precision."""
92
+ left_second, left_fraction = parse_utc_parts(left, field + " left value")
93
+ right_second, right_fraction = parse_utc_parts(right, field + " right value")
94
+ if left_second < right_second:
95
+ return -1
96
+ if left_second > right_second:
97
+ return 1
98
+ width = max(len(left_fraction), len(right_fraction))
99
+ left_digits = left_fraction.ljust(width, "0")
100
+ right_digits = right_fraction.ljust(width, "0")
101
+ return (left_digits > right_digits) - (left_digits < right_digits)
102
+
103
+
104
+ def format_utc_datetime(value: datetime) -> str:
105
+ return value.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")
106
+
107
+
108
+ def decimal_digits_to_int(digits: str) -> int:
109
+ """Convert decimal digits in small chunks to avoid Python's global digit cap."""
110
+ result = 0
111
+ for offset in range(0, len(digits), 9):
112
+ chunk = digits[offset:offset + 9]
113
+ result = result * (10 ** len(chunk)) + int(chunk)
114
+ return result
115
+
116
+
117
+ def int_to_fixed_decimal(value: int, width: int) -> str:
118
+ """Render a non-negative integer with a fixed decimal width in bounded chunks."""
119
+ if value < 0:
120
+ raise ValueError("fixed decimal conversion requires a non-negative integer")
121
+ chunks = []
122
+ base = 10 ** 9
123
+ while value:
124
+ value, remainder = divmod(value, base)
125
+ chunks.append(remainder)
126
+ if chunks:
127
+ rendered = str(chunks[-1]) + "".join(
128
+ f"{chunk:09d}" for chunk in reversed(chunks[:-1])
129
+ )
130
+ else:
131
+ rendered = "0"
132
+ return rendered.zfill(width)
133
+
134
+
135
+ def calculate_accuracy_bounds(
136
+ gen_time: str, accuracy: dict[str, int]
137
+ ) -> tuple[str, str]:
138
+ """Add/subtract RFC 3161 Accuracy exactly, preserving arbitrary genTime precision."""
139
+ whole_second, fraction = parse_rfc3161_gen_time_parts(gen_time, "timestamp gen_time")
140
+ width = max(6, len(fraction))
141
+ scale = 10 ** width
142
+ epoch = datetime(1970, 1, 1, tzinfo=timezone.utc)
143
+ delta = whole_second - epoch
144
+ whole_epoch_seconds = delta.days * 86400 + delta.seconds
145
+ instant_ticks = whole_epoch_seconds * scale + decimal_digits_to_int(
146
+ fraction.ljust(width, "0") or "0"
147
+ )
148
+ uncertainty_ticks = (
149
+ accuracy.get("seconds", 0) * scale
150
+ + accuracy.get("millis", 0) * (scale // 1000)
151
+ + accuracy.get("micros", 0) * (scale // 1_000_000)
152
+ )
153
+
154
+ def render(ticks: int) -> str:
155
+ epoch_seconds, fractional_ticks = divmod(ticks, scale)
156
+ try:
157
+ value = epoch + timedelta(seconds=epoch_seconds)
158
+ except (OverflowError, ValueError) as exc:
159
+ raise ValueError("RFC 3161 timestamp accuracy exceeds the supported datetime range") from exc
160
+ prefix = value.strftime("%Y-%m-%dT%H:%M:%S")
161
+ return prefix + "." + int_to_fixed_decimal(fractional_ticks, width) + "Z"
162
+
163
+ try:
164
+ return render(instant_ticks - uncertainty_ticks), render(instant_ticks + uncertainty_ticks)
165
+ except (OverflowError, ValueError) as exc:
166
+ raise ValueError("RFC 3161 timestamp accuracy exceeds the supported datetime range") from exc
167
+
168
+
169
+ def require_sha256(value: Any, field: str) -> str:
170
+ if not isinstance(value, str) or not HEX256.fullmatch(value):
171
+ raise ValueError(field + " must be a lowercase SHA-256 digest")
172
+ return value
173
+
174
+
175
+ def validate_crl_issuer_validity(value: Any, field: str, gen_time: str) -> dict[str, Any]:
176
+ if not isinstance(value, dict):
177
+ raise ValueError(field + " evidence is missing")
178
+ required = ("crl_this_update", "not_before", "not_after")
179
+ times = {name: parse_utc(value.get(name), field + "." + name) for name in required}
180
+ if not (times["not_before"] <= times["crl_this_update"] <= times["not_after"]):
181
+ raise ValueError(field + " does not establish issuer validity at CRL thisUpdate")
182
+ parse_rfc3161_gen_time_parts(gen_time, "gen_time")
183
+ if compare_utc_values(value.get("crl_this_update"), gen_time, field + " CRL thisUpdate vs gen_time") > 0:
184
+ raise ValueError(field + " CRL thisUpdate is later than the historical target time")
185
+ for flag in ("valid_at_this_update", "basic_constraints_ca", "key_cert_sign", "crl_sign"):
186
+ if value.get(flag) is not True:
187
+ raise ValueError(field + " must affirm " + flag)
188
+ if value.get("time_basis") != "CRL issuer certificate validity and CA/keyCertSign/cRLSign authorization are checked at CRL thisUpdate; OpenSSL validates the full target certificate PKIX path, including the issuer path to the pinned trust anchor, at RFC3161 genTime bounds":
189
+ raise ValueError(field + " time-basis declaration is missing or unsupported")
190
+ return value
191
+ def report_claims(report: dict[str, Any]) -> dict[str, Any]:
192
+ required = ("gen_time", "tsa_certificate_sha256", "timestamp_result_sha256",
193
+ "result_digest_policy", "timestamp_signer_serial_number",
194
+ "historical_revocation_assessment", "current_ocsp_assessment",
195
+ "historical_ocsp_responder_revocation_assessment", "overall_assessment", "limitations")
196
+ missing = [name for name in required if name not in report]
197
+ if report.get("schema_version") != 1 or report.get("report_type") != "tsa_long_term_validation_evidence":
198
+ raise ValueError("unsupported TSA validation report schema or type")
199
+ if missing:
200
+ raise ValueError("TSA report missing required attestation fields: " + ", ".join(missing))
201
+ parse_rfc3161_gen_time_parts(report["gen_time"], "gen_time")
202
+ require_sha256(report["tsa_certificate_sha256"], "tsa_certificate_sha256")
203
+ require_sha256(report["timestamp_result_sha256"], "timestamp_result_sha256")
204
+ timestamp_chain = report.get("timestamp_chain_validation")
205
+ expected_chain_fields = {
206
+ "status", "validation_time", "scope", "policy", "intermediates_sha256"
207
+ }
208
+ if not isinstance(timestamp_chain, dict) or set(timestamp_chain) != expected_chain_fields:
209
+ raise ValueError("TSA report timestamp_chain_validation is missing or malformed")
210
+ if timestamp_chain.get("status") != "verified":
211
+ raise ValueError("TSA report timestamp_chain_validation status is not verified")
212
+ if timestamp_chain.get("validation_time") != report["gen_time"]:
213
+ raise ValueError("TSA report timestamp chain validation time must match gen_time")
214
+ if timestamp_chain.get("scope") != (
215
+ "PKIX path validation at the floor/ceiling Unix-second bounds of genTime; "
216
+ "RFC 3161 Accuracy is reported separately and does not widen the -attime interval"
217
+ ):
218
+ raise ValueError("TSA report timestamp chain validation scope is missing or unsupported")
219
+ if timestamp_chain.get("policy") != (
220
+ "OpenSSL ts -verify uses the caller-pinned -CAfile and explicit empty -CApath/-CAstore, "
221
+ "-auth_level 2, -purpose timestampsign, and -x509_strict at the exact floor/ceiling "
222
+ "Unix-second bound(s) of genTime; pathLenConstraint and Name Constraints enforced by OpenSSL"
223
+ ):
224
+ raise ValueError("TSA report timestamp chain validation policy is missing or unsupported")
225
+ intermediate_digest = timestamp_chain.get("intermediates_sha256")
226
+ if intermediate_digest is not None:
227
+ require_sha256(intermediate_digest, "timestamp_chain_validation.intermediates_sha256")
228
+ if report["result_digest_policy"] != "caller_supplied_sha256_pins_checked_for_byte_equality_only":
229
+ raise ValueError("TSA report does not accurately describe caller-supplied digest-pin checking")
230
+ if report.get("gen_time_source") != "caller_asserted_from_external_timestamp_verification":
231
+ raise ValueError("TSA report genTime provenance must be explicitly caller-asserted")
232
+ if report.get("gen_time_provenance") != {
233
+ "source": "caller_supplied_gen_time_argument",
234
+ "independently_verified_by_this_report": False,
235
+ }:
236
+ raise ValueError("TSA report must not claim independent genTime verification")
237
+ if report.get("result_digest_pin_provenance") != {
238
+ "source": "caller_supplied_command_line_arguments",
239
+ "independently_authenticated_by_this_report": False,
240
+ }:
241
+ raise ValueError("TSA report must disclose that digest-pin provenance is not authenticated here")
242
+ signer_serial = report["timestamp_signer_serial_number"]
243
+ if not isinstance(signer_serial, str) or not signer_serial.strip() or len(signer_serial) > 128:
244
+ raise ValueError("timestamp_signer_serial_number must be a non-empty string of at most 128 characters")
245
+ historical = report["historical_revocation_assessment"]
246
+ if not isinstance(historical, dict):
247
+ raise ValueError("historical_revocation_assessment must be an object")
248
+ claim_scope = historical.get("claim_scope")
249
+ if not isinstance(claim_scope, dict) or claim_scope.get("complete_revocation_status") is not False:
250
+ raise ValueError("historical CRL claim scope must explicitly disclaim complete revocation status")
251
+ if historical.get("source") != "verified_crl" or historical.get("status") != "not_revoked_at_gen_time":
252
+ raise ValueError("historical CRL assessment must explicitly report verified non-revocation")
253
+ if historical.get("validation_time") != report["gen_time"]:
254
+ raise ValueError("historical CRL validation_time must exactly match report gen_time")
255
+ gen_whole_second, gen_fraction = parse_rfc3161_gen_time_parts(report["gen_time"], "gen_time")
256
+ effective_second = gen_whole_second
257
+ if any(digit != "0" for digit in gen_fraction):
258
+ effective_second += timedelta(seconds=1)
259
+ expected_effective_at_time = effective_second.isoformat(timespec="seconds").replace("+00:00", "Z")
260
+ if historical.get("evaluation_time_upper_bound") != expected_effective_at_time:
261
+ raise ValueError("historical CRL evaluation_time_upper_bound does not conservatively ceil gen_time")
262
+ for field in ("crl_sha256", "issuer_roots_sha256", "crl_issuer_certificate_sha256", "result_file_sha256"):
263
+ require_sha256(historical.get(field), "historical_revocation_assessment." + field)
264
+ if historical.get("issuer_intermediates_sha256") is not None:
265
+ require_sha256(historical.get("issuer_intermediates_sha256"), "historical_revocation_assessment.issuer_intermediates_sha256")
266
+ if historical.get("trust_anchor_policy") != "issuer-roots bundle contains only self-issued trust-anchor certificates; CRL issuer CA/keyCertSign/cRLSign are checked independently; intermediates are supplied separately via -untrusted":
267
+ raise ValueError("historical CRL trust-anchor/intermediate separation policy is missing or unsupported")
268
+ if not isinstance(historical.get("crl_signature_algorithm_oid"), str) or not historical["crl_signature_algorithm_oid"].strip():
269
+ raise ValueError("historical_revocation_assessment.crl_signature_algorithm_oid must be non-empty")
270
+ if historical.get("crl_signature_policy") != "RSA/DSA >= 2048 bits or EC >= 256 bits with SHA-256/384/512; Ed25519/Ed448 allowed":
271
+ raise ValueError("historical CRL signature policy is missing or unsupported")
272
+ if historical.get("verification") != "OpenSSL path and CRL signature validation plus direct-CRL issuer, CA/keyCertSign/cRLSign, issuer validity at CRL thisUpdate, AKI, scope, freshness, signature-policy and entry-semantic preflight":
273
+ raise ValueError("historical CRL verification provenance is missing or unsupported")
274
+ validate_crl_issuer_validity(historical.get("crl_issuer_certificate_validity"),
275
+ "historical_revocation_assessment CRL issuer validity", report["gen_time"])
276
+ entry = historical.get("revocation_entry")
277
+ if not isinstance(entry, dict) or entry.get("status_at_time") not in ("not_listed", "not_yet_revoked"):
278
+ raise ValueError("historical CRL revocation_entry does not establish non-revocation")
279
+ if entry.get("present") is True and entry.get("status_at_time") != "not_yet_revoked":
280
+ raise ValueError("historical CRL entry presence contradicts non-revocation")
281
+ if entry.get("present") is False and entry.get("status_at_time") != "not_listed":
282
+ raise ValueError("historical CRL entry absence contradicts not-listed status")
283
+
284
+ current = report["current_ocsp_assessment"]
285
+ if not isinstance(current, dict) or type(current.get("provided")) is not bool:
286
+ raise ValueError("current_ocsp_assessment must declare a boolean provided field")
287
+ if current.get("provided") is False:
288
+ if current.get("assessment") != "not_provided" or current.get("historical_status_claim") is not False:
289
+ raise ValueError("omitted OCSP evidence must be classified not_provided with no historical claim")
290
+ if report["historical_ocsp_responder_revocation_assessment"].get("status") != "not_assessed":
291
+ raise ValueError("OCSP responder revocation cannot be assessed without OCSP evidence")
292
+ else:
293
+ if current.get("assessment") not in ("good", "revoked", "unknown"):
294
+ raise ValueError("current OCSP assessment has an invalid status")
295
+ scope = current.get("scope")
296
+ current_scope = "current-time OCSP response validation; not a historical status determination"
297
+ historical_scope = "historical OCSP status validation at the supplied target time"
298
+ if scope not in (current_scope, historical_scope):
299
+ raise ValueError("current OCSP assessment has an unsupported scope")
300
+ if current.get("nonce_checked") is not False:
301
+ raise ValueError("current OCSP assessment must explicitly state nonce_checked=false")
302
+ if current.get("historical_status_claim") is not (scope == historical_scope):
303
+ raise ValueError("OCSP historical_status_claim contradicts its declared scope")
304
+ for field in ("response_sha256", "issuer_roots_sha256", "result_file_sha256"):
305
+ require_sha256(current.get(field), "current_ocsp_assessment." + field)
306
+ responder_digest = current.get("responder_certificate_sha256")
307
+ if responder_digest is not None:
308
+ require_sha256(responder_digest, "current_ocsp_assessment.responder_certificate_sha256")
309
+ validation = parse_utc(current.get("validation_time"), "OCSP validation_time")
310
+ produced = parse_utc(current.get("produced_at"), "OCSP produced_at")
311
+ this_update = parse_utc(current.get("this_update"), "OCSP this_update")
312
+ next_update = parse_utc(current.get("next_update"), "OCSP next_update")
313
+ if next_update < this_update or validation < this_update or validation > next_update:
314
+ raise ValueError("OCSP assessment contains inconsistent signed validity times")
315
+ if scope == historical_scope:
316
+ gen_whole_second, gen_fraction = parse_rfc3161_gen_time_parts(report["gen_time"], "gen_time")
317
+ if len(gen_fraction) > 6:
318
+ raise ValueError("historical OCSP cannot represent genTime with more than six fractional digits")
319
+ if (current.get("historical_at_time") != report["gen_time"]
320
+ or compare_utc_values(current.get("validation_time"), report["gen_time"], "historical OCSP validation_time") != 0):
321
+ raise ValueError("historical OCSP assessment must exactly match report gen_time")
322
+ if (compare_utc_values(current.get("produced_at"), report["gen_time"], "historical OCSP producedAt") > 0
323
+ or compare_utc_values(current.get("next_update"), report["gen_time"], "historical OCSP nextUpdate") < 0):
324
+ raise ValueError("historical OCSP assessment is not valid at report gen_time")
325
+
326
+ responder = report["historical_ocsp_responder_revocation_assessment"]
327
+ if not isinstance(responder, dict):
328
+ raise ValueError("historical_ocsp_responder_revocation_assessment must be an object")
329
+ if responder.get("status") == "not_assessed":
330
+ if not isinstance(responder.get("reason"), str) or not responder["reason"].strip():
331
+ raise ValueError("not-assessed OCSP responder revocation must include a reason")
332
+ elif responder.get("status") == "not_revoked_at_gen_time":
333
+ if current.get("provided") is not True or current.get("historical_status_claim") is not True:
334
+ raise ValueError("OCSP responder revocation requires historical OCSP evidence")
335
+ if current.get("responder_certificate_sha256") is None:
336
+ raise ValueError("OCSP responder revocation requires a bound responder certificate")
337
+ if responder.get("responder_certificate_sha256") != current["responder_certificate_sha256"]:
338
+ raise ValueError("OCSP responder revocation fingerprint differs from the OCSP signer")
339
+ if responder.get("validation_time") != report["gen_time"]:
340
+ raise ValueError("OCSP responder revocation validation_time must match report gen_time")
341
+ for field in ("crl_sha256", "issuer_roots_sha256", "crl_issuer_certificate_sha256", "result_file_sha256"):
342
+ require_sha256(responder.get(field), "historical_ocsp_responder_revocation_assessment." + field)
343
+ if responder.get("issuer_intermediates_sha256") is not None:
344
+ require_sha256(responder.get("issuer_intermediates_sha256"), "historical_ocsp_responder_revocation_assessment.issuer_intermediates_sha256")
345
+ if responder.get("trust_anchor_policy") != "issuer-roots bundle contains only self-issued trust-anchor certificates; CRL issuer CA/keyCertSign/cRLSign are checked independently; intermediates are supplied separately via -untrusted":
346
+ raise ValueError("historical OCSP responder CRL trust-anchor/intermediate separation policy is missing or unsupported")
347
+ if not isinstance(responder.get("crl_signature_algorithm_oid"), str) or not responder["crl_signature_algorithm_oid"].strip():
348
+ raise ValueError("historical OCSP responder CRL signature algorithm identity is missing")
349
+ if responder.get("crl_signature_policy") != "RSA/DSA >= 2048 bits or EC >= 256 bits with SHA-256/384/512; Ed25519/Ed448 allowed":
350
+ raise ValueError("historical OCSP responder CRL signature policy is missing or unsupported")
351
+ if responder.get("verification") != "OpenSSL path and CRL signature validation plus direct-CRL issuer, CA/keyCertSign/cRLSign, issuer validity at CRL thisUpdate, AKI, scope, freshness, signature-policy and entry-semantic preflight":
352
+ raise ValueError("historical OCSP responder CRL verification provenance is missing or unsupported")
353
+ validate_crl_issuer_validity(responder.get("crl_issuer_certificate_validity"),
354
+ "historical OCSP responder CRL issuer validity", report["gen_time"])
355
+ responder_entry = responder.get("revocation_entry")
356
+ if not isinstance(responder_entry, dict) or responder_entry.get("status_at_time") not in ("not_listed", "not_yet_revoked"):
357
+ raise ValueError("historical OCSP responder CRL entry evidence does not establish non-revocation")
358
+ else:
359
+ raise ValueError("historical OCSP responder revocation has an unsupported status")
360
+ expected_overall_assessment = _build_overall_assessment(current)
361
+ if report.get("overall_assessment") != expected_overall_assessment:
362
+ raise ValueError("TSA report overall_assessment contradicts its CRL/OCSP evidence scope or status")
363
+ limitations = report.get("limitations")
364
+ if (not isinstance(limitations, list)
365
+ or any(not isinstance(item, str) or not item.strip() for item in limitations)):
366
+ raise ValueError("TSA report limitations must be a list of non-empty strings")
367
+ timestamp_not_established = report.get("timestamp_not_established")
368
+ if (not isinstance(timestamp_not_established, list) or not timestamp_not_established
369
+ or any(not isinstance(item, str) or not item.strip() for item in timestamp_not_established)):
370
+ raise ValueError("TSA report timestamp_not_established must be a non-empty list")
371
+ expected_limitations = _build_limitations(current, responder) + timestamp_not_established
372
+ if limitations != expected_limitations:
373
+ raise ValueError("TSA report limitations do not match the supplied OCSP/responder evidence scope")
374
+ # The complete report, not a selected projection, is the canonical claim.
375
+ return dict(report)
376
+
377
+
378
+ def signed_payload(envelope: dict[str, Any]) -> bytes:
379
+ fields = {key: envelope[key] for key in (
380
+ "schema_version", "algorithm", "key_id", "attested_at", "report_sha256",
381
+ "verifier_bundle_sha256", "verifier_identity", "claims_sha256")}
382
+ return DOMAIN + canonical_json(fields)
383
+
384
+
385
+ def create_attestation(report_path: Path, private_key_path: Path, key_id: str,
386
+ verifier_bundle_sha256: str, verifier_identity: str) -> dict[str, Any]:
387
+ if not KEY_ID_RE.fullmatch(key_id):
388
+ raise ValueError("invalid key_id")
389
+ require_sha256(verifier_bundle_sha256, "verifier_bundle_sha256")
390
+ if not isinstance(verifier_identity, str) or not verifier_identity.strip() or len(verifier_identity) > 256:
391
+ raise ValueError("verifier_identity must be a non-empty string of at most 256 characters")
392
+ raw = report_path.read_bytes()
393
+ report = json.loads(raw.decode("utf-8"))
394
+ if not isinstance(report, dict):
395
+ raise ValueError("TSA report must be a JSON object")
396
+ claims = report_claims(report)
397
+ key = serialization.load_pem_private_key(private_key_path.read_bytes(), password=None)
398
+ if not isinstance(key, Ed25519PrivateKey):
399
+ raise ValueError("private key must be an unencrypted Ed25519 PEM key")
400
+ envelope = {
401
+ "schema_version": SCHEMA_VERSION,
402
+ "algorithm": "Ed25519",
403
+ "key_id": key_id,
404
+ "attested_at": datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z"),
405
+ "report_sha256": hashlib.sha256(raw).hexdigest(),
406
+ "verifier_bundle_sha256": verifier_bundle_sha256,
407
+ "verifier_identity": verifier_identity,
408
+ "claims_sha256": hashlib.sha256(canonical_json(claims)).hexdigest(),
409
+ }
410
+ envelope["signature"] = base64.b64encode(key.sign(signed_payload(envelope))).decode("ascii")
411
+ return envelope
412
+
413
+
414
+ def validate_timestamp_verification_scope(
415
+ result: dict[str, Any], *, chain_supplied: bool
416
+ ) -> None:
417
+ scope = result.get("verification_scope")
418
+ required = {"cms_signature", "request_imprint", "response_imprint",
419
+ "request_response_binding", "nonce_binding",
420
+ "tsa_pkix_chain_at_gen_time", "tsa_signer_certificate_profile",
421
+ "tsa_signer_validity_at_gen_time"}
422
+ if not isinstance(scope, dict) or set(scope) != required:
423
+ raise ValueError("RFC 3161 timestamp verification scope is missing or malformed")
424
+ for field in required - {"nonce_binding"}:
425
+ if scope[field] != "verified":
426
+ raise ValueError("RFC 3161 timestamp scope does not establish " + field)
427
+ if type(result.get("nonce_present")) is not bool:
428
+ raise ValueError("RFC 3161 timestamp nonce_present must be an explicit boolean")
429
+ expected = "verified" if result["nonce_present"] else "not_requested"
430
+ if scope["nonce_binding"] != expected:
431
+ raise ValueError("RFC 3161 timestamp nonce scope contradicts nonce_present")
432
+ limits = result.get("not_established")
433
+ if not isinstance(limits, list) or not limits or any(not isinstance(x, str) or not x.strip() for x in limits):
434
+ raise ValueError("RFC 3161 timestamp limitations must be a non-empty list of descriptions")
435
+
436
+ if result.get("tsa_chain_valid_at_gen_time") is not True:
437
+ raise ValueError("RFC 3161 TSA chain is not explicitly verified at genTime")
438
+ gen_time = result.get("gen_time")
439
+ parse_rfc3161_gen_time_parts(gen_time, "timestamp gen_time")
440
+ if result.get("tsa_chain_validation_time") != gen_time:
441
+ raise ValueError("RFC 3161 TSA chain validation time does not match genTime")
442
+ if result.get("tsa_chain_validation_scope") != TSA_CHAIN_VALIDATION_SCOPE:
443
+ raise ValueError("RFC 3161 TSA chain validation scope is missing or unsupported")
444
+ if result.get("tsa_chain_validation_policy") != TSA_CHAIN_VALIDATION_POLICY:
445
+ raise ValueError("RFC 3161 TSA chain validation policy is missing or unsupported")
446
+ if result.get("verification") != TSA_TIMESTAMP_VERIFICATION_METHOD:
447
+ raise ValueError("RFC 3161 timestamp verification-method provenance is missing or unsupported")
448
+ if "tsa_chain_sha256" not in result:
449
+ raise ValueError("RFC 3161 TSA intermediate-chain digest must be explicitly present")
450
+ chain_digest = result.get("tsa_chain_sha256")
451
+ if chain_supplied:
452
+ require_sha256(chain_digest, "RFC 3161 TSA intermediate-chain SHA-256")
453
+ elif chain_digest is not None:
454
+ raise ValueError("RFC 3161 TSA intermediate-chain digest is present but no chain input was supplied")
455
+
456
+ def verify_attestation(report_path: Path, attestation_path: Path, trust_store_path: Path,
457
+ expected_trust_store_sha256: str,
458
+ timestamp_request_path: Path | None = None,
459
+ timestamp_response_path: Path | None = None,
460
+ tsa_ca_path: Path | None = None,
461
+ expected_tsa_ca_sha256: str | None = None,
462
+ tsa_chain_path: Path | None = None,
463
+ verifier_bundle_path: Path | None = None) -> dict[str, Any]:
464
+ raw_report = report_path.read_bytes()
465
+ report = json.loads(raw_report.decode("utf-8"))
466
+ if not isinstance(report, dict):
467
+ raise ValueError("TSA report must be a JSON object")
468
+ claims = report_claims(report)
469
+ envelope = json.loads(attestation_path.read_text(encoding="utf-8"))
470
+ if not isinstance(envelope, dict) or set(envelope) != ENVELOPE_FIELDS:
471
+ raise ValueError("invalid attestation envelope schema")
472
+ if envelope["schema_version"] != SCHEMA_VERSION or envelope["algorithm"] != "Ed25519":
473
+ raise ValueError("unsupported attestation schema or algorithm")
474
+ key_id = envelope["key_id"]
475
+ if not isinstance(key_id, str) or not KEY_ID_RE.fullmatch(key_id):
476
+ raise ValueError("invalid key_id")
477
+ attested_time = parse_utc(envelope["attested_at"], "attested_at")
478
+ report_digest = hashlib.sha256(raw_report).hexdigest()
479
+ if require_sha256(envelope["report_sha256"], "report_sha256") != report_digest:
480
+ raise ValueError("attestation report SHA-256 mismatch")
481
+ verifier_bundle_digest = require_sha256(envelope["verifier_bundle_sha256"], "verifier_bundle_sha256")
482
+ verifier_bundle_bytes_verified = False
483
+ if verifier_bundle_path is not None:
484
+ if not verifier_bundle_path.is_file():
485
+ raise ValueError("verifier bundle path must identify a regular file")
486
+ if digest_file(verifier_bundle_path) != verifier_bundle_digest:
487
+ raise ValueError("verifier bundle SHA-256 does not match the signed envelope")
488
+ verifier_bundle_bytes_verified = True
489
+ if (not isinstance(envelope["verifier_identity"], str)
490
+ or not envelope["verifier_identity"].strip()
491
+ or len(envelope["verifier_identity"]) > 256):
492
+ raise ValueError("invalid verifier_identity")
493
+ if not isinstance(envelope["signature"], str):
494
+ raise ValueError("signature must be base64 text")
495
+ try:
496
+ signature_bytes = base64.b64decode(envelope["signature"], validate=True)
497
+ except (ValueError, TypeError) as exc:
498
+ raise ValueError("signature must be valid base64") from exc
499
+ if len(signature_bytes) != 64:
500
+ raise ValueError("Ed25519 signature must decode to exactly 64 bytes")
501
+ claims_digest = hashlib.sha256(canonical_json(claims)).hexdigest()
502
+ if require_sha256(envelope["claims_sha256"], "claims_sha256") != claims_digest:
503
+ raise ValueError("attestation claims digest mismatch")
504
+ require_sha256(expected_trust_store_sha256, "expected trust-store SHA-256")
505
+ trust_digest = digest_file(trust_store_path)
506
+ if trust_digest != expected_trust_store_sha256:
507
+ raise ValueError("trust-store SHA-256 pin mismatch")
508
+ store = json.loads(trust_store_path.read_text(encoding="utf-8"))
509
+ if not isinstance(store, dict) or set(store) != STORE_FIELDS or store.get("schema_version") != 2 or not isinstance(store.get("keys"), dict):
510
+ raise ValueError("invalid trust store schema v2")
511
+ entry = store["keys"].get(key_id)
512
+ if not isinstance(entry, dict) or set(entry) != KEY_FIELDS:
513
+ raise ValueError("unknown or malformed trust-store key")
514
+ if entry["status"] not in {"active", "revoked", "disabled"}:
515
+ raise ValueError("invalid trust-store key status")
516
+ not_before = parse_utc(entry["not_before"], "not_before")
517
+ not_after = parse_utc(entry["not_after"], "not_after")
518
+ if not_before >= not_after:
519
+ raise ValueError("key validity interval must have not_before < not_after")
520
+ revoked_at = None if entry["revoked_at"] is None else parse_utc(entry["revoked_at"], "revoked_at")
521
+ if entry["status"] == "revoked" and revoked_at is None:
522
+ raise ValueError("revoked trust-store keys must declare revoked_at for historical evaluation")
523
+ timestamp_args = (timestamp_request_path, timestamp_response_path, tsa_ca_path, expected_tsa_ca_sha256)
524
+ if tsa_chain_path is not None and not all(value is not None for value in timestamp_args):
525
+ raise ValueError("TSA intermediate chain requires the complete RFC 3161 timestamp evidence set")
526
+ if any(value is not None for value in timestamp_args) and not all(value is not None for value in timestamp_args):
527
+ raise ValueError("RFC 3161 attestation timestamp requires request, response, TSA CA bundle, and CA SHA-256 pin together")
528
+ public_key = serialization.load_pem_public_key(entry["public_key_pem"].encode("ascii"))
529
+ if not isinstance(public_key, Ed25519PublicKey):
530
+ raise ValueError("trust-store key must be Ed25519")
531
+ try:
532
+ public_key.verify(base64.b64decode(envelope["signature"], validate=True), signed_payload(envelope))
533
+ except Exception as exc:
534
+ raise ValueError("Ed25519 attestation signature verification failed") from exc
535
+ trusted_timestamp = None
536
+ if all(value is not None for value in timestamp_args):
537
+ trusted_timestamp = verify_timestamp(
538
+ attestation_path, timestamp_request_path, timestamp_response_path,
539
+ tsa_ca_path, expected_tsa_ca_sha256, tsa_chain_path)
540
+ if (trusted_timestamp.get("verified") is not True
541
+ or trusted_timestamp.get("tsa_signer_valid_at_gen_time") is not True):
542
+ raise ValueError("RFC 3161 timestamp did not establish a verified, valid TSA signer")
543
+ timestamp_gen_time = trusted_timestamp.get("gen_time")
544
+ parse_rfc3161_gen_time_parts(timestamp_gen_time, "timestamp gen_time")
545
+ validate_timestamp_verification_scope(
546
+ trusted_timestamp, chain_supplied=tsa_chain_path is not None
547
+ )
548
+ require_sha256(trusted_timestamp.get("tsa_signer_certificate_sha256"), "TSA signer certificate SHA-256")
549
+ expected_signature_digest = hashlib.sha256(signature_bytes).hexdigest()
550
+ if trusted_timestamp.get("signature_sha256") != expected_signature_digest:
551
+ raise ValueError("RFC 3161 timestamp is not bound to the exact attestation signature")
552
+
553
+ # RFC 3161 Accuracy is an uncertainty bound, not an exact-time assertion.
554
+ # Only use a conservative upper bound when the token explicitly supplies it.
555
+ timestamp_lower_bound = None
556
+ timestamp_upper_bound = None
557
+ timestamp_accuracy_assessed = False
558
+ if trusted_timestamp is not None and trusted_timestamp.get("accuracy") is not None:
559
+ accuracy = trusted_timestamp["accuracy"]
560
+ allowed_accuracy_fields = {"seconds", "millis", "micros"}
561
+ if (not isinstance(accuracy, dict) or not accuracy
562
+ or set(accuracy) - allowed_accuracy_fields):
563
+ raise ValueError("RFC 3161 timestamp accuracy must be a non-empty object with seconds, millis, and/or micros")
564
+ for field, value in accuracy.items():
565
+ if type(value) is not int or value < 0:
566
+ raise ValueError("RFC 3161 timestamp accuracy components must be non-negative integers")
567
+ if field in {"millis", "micros"} and not 1 <= value <= 999:
568
+ raise ValueError("RFC 3161 timestamp millis and micros must be between 1 and 999")
569
+ timestamp_lower_bound, timestamp_upper_bound = calculate_accuracy_bounds(
570
+ timestamp_gen_time, accuracy
571
+ )
572
+ timestamp_accuracy_assessed = True
573
+
574
+ now = datetime.now(timezone.utc)
575
+ currently_authorized = (entry["status"] == "active" and not_before <= now <= not_after
576
+ and (revoked_at is None or now < revoked_at))
577
+ signature_existed_before_revocation = (
578
+ timestamp_upper_bound is not None and revoked_at is not None
579
+ and compare_utc_values(timestamp_upper_bound, format_utc_datetime(revoked_at)) < 0
580
+ )
581
+ signature_existed_before_key_validity = (
582
+ timestamp_upper_bound is not None
583
+ and compare_utc_values(timestamp_upper_bound, format_utc_datetime(not_before)) < 0
584
+ )
585
+ # This enum is a compact evidence classification, not a historical-validity
586
+ # verdict. The independent booleans above retain simultaneous boundary facts.
587
+ if trusted_timestamp is None:
588
+ historical_assessment = "not_assessed_no_trusted_timestamp"
589
+ elif signature_existed_before_key_validity:
590
+ historical_assessment = "signature_preexisted_key_validity"
591
+ elif signature_existed_before_revocation:
592
+ historical_assessment = "signature_preexisted_revocation"
593
+ else:
594
+ historical_assessment = "timestamped_existence_only"
595
+ return {"verified": True, "signature_valid": True, "historically_valid": False,
596
+ "historical_assessment": historical_assessment,
597
+ "historical_validity_basis": (
598
+ (
599
+ "signature_creation_time_not_proven; RFC 3161 token establishes existence by "
600
+ "the conservative trusted timestamp upper bound (genTime plus explicit Accuracy); "
601
+ "this is not proof that the signature was created during the key-validity interval"
602
+ ) if timestamp_accuracy_assessed else
603
+ "signature_creation_time_not_proven; RFC 3161 token has no explicit Accuracy and "
604
+ "no conservative timestamp bound is derived for key-validity or revocation ordering"
605
+ ) if trusted_timestamp else "attester_asserted_attested_at_is_not_trusted_time",
606
+ "historical_time_cryptographically_proven": trusted_timestamp is not None,
607
+ "signature_existence_proven_by_trusted_timestamp": trusted_timestamp is not None,
608
+ "signature_existed_before_revocation": bool(signature_existed_before_revocation),
609
+ "signature_existence_proven_before_key_not_before": bool(signature_existed_before_key_validity),
610
+ "trusted_signature_timestamp": trusted_timestamp,
611
+ "trusted_timestamp_lower_bound": timestamp_lower_bound,
612
+ "trusted_timestamp_upper_bound": timestamp_upper_bound,
613
+ "timestamp_accuracy_assessed": timestamp_accuracy_assessed,
614
+ "currently_authorized": currently_authorized, "key_id": key_id,
615
+ "attested_at": envelope["attested_at"], "report_sha256": report_digest,
616
+ "verifier_bundle_sha256": envelope["verifier_bundle_sha256"],
617
+ "verifier_identity": envelope["verifier_identity"],
618
+ "claims_sha256": claims_digest, "trust_store_sha256": trust_digest,
619
+ # This value is covered by the signed report claims. It identifies
620
+ # the pinned verifier-result bytes; this function does not re-verify
621
+ # the original RFC 3161 response file.
622
+ "attested_timestamp_result_sha256": report["timestamp_result_sha256"],
623
+ "timestamp_result_digest_attested": True,
624
+ "execution_provenance_established": False,
625
+ "evidence_provenance": {
626
+ "trust_store_digest_pin": {
627
+ "source": "caller_supplied_command_line_argument",
628
+ "authenticated_by_this_verifier": False,
629
+ },
630
+ "verifier_bundle_digest": {
631
+ "source": "attester_asserted_in_signed_envelope",
632
+ "bundle_bytes_verified": verifier_bundle_bytes_verified,
633
+ "bundle_bytes_verification": (
634
+ "local_file_sha256_matches_signed_digest"
635
+ if verifier_bundle_bytes_verified else "not_performed"
636
+ ),
637
+ "execution_provenance_established": False,
638
+ },
639
+ "verifier_identity": {
640
+ "source": "attester_asserted_in_signed_envelope",
641
+ "independently_authenticated_by_this_verifier": False,
642
+ },
643
+ "input_evidence_bytes": {
644
+ "verified_by_this_attestation_verifier": False,
645
+ "scope": "CRL, OCSP, and original timestamp-result evidence are represented by report digests and assertions; their source files are not reopened or re-verified here",
646
+ },
647
+ "tsa_ca_digest_pin": ({
648
+ "source": "caller_supplied_command_line_argument",
649
+ "authenticated_by_this_verifier": False,
650
+ } if trusted_timestamp is not None else None),
651
+ "timestamp_token": {
652
+ "verified_by_this_verifier": trusted_timestamp is not None,
653
+ "signature_binding": "exact_attestation_signature" if trusted_timestamp is not None else "not_verified",
654
+ "scope": "RFC 3161 token over this attestation signature; not the original TSA token summarized in the signed report",
655
+ },
656
+ }}
657
+
658
+
659
+ def main() -> int:
660
+ parser = argparse.ArgumentParser(description=__doc__)
661
+ sub = parser.add_subparsers(dest="command", required=True)
662
+ sign = sub.add_parser("sign")
663
+ sign.add_argument("--report", type=Path, required=True)
664
+ sign.add_argument("--private-key", type=Path, required=True)
665
+ sign.add_argument("--key-id", required=True)
666
+ sign.add_argument("--verifier-bundle", type=Path, required=True,
667
+ help="local verifier bundle file; its SHA-256 is measured before signing")
668
+ sign.add_argument("--verifier-identity", required=True,
669
+ help="attester-asserted verifier label; identity is not independently authenticated")
670
+ sign.add_argument("--output", type=Path, required=True)
671
+ verify = sub.add_parser("verify")
672
+ verify.add_argument("--report", type=Path, required=True)
673
+ verify.add_argument("--attestation", type=Path, required=True)
674
+ verify.add_argument("--trust-store", type=Path, required=True)
675
+ verify.add_argument("--trust-store-sha256", required=True)
676
+ verify.add_argument("--verifier-bundle", type=Path, required=True,
677
+ help="verifier bundle file whose bytes must match the signed SHA-256")
678
+ verify.add_argument("--timestamp-request", type=Path)
679
+ verify.add_argument("--timestamp-response", type=Path)
680
+ verify.add_argument("--tsa-ca", type=Path)
681
+ verify.add_argument("--tsa-ca-sha256")
682
+ verify.add_argument("--tsa-chain", type=Path)
683
+ args = parser.parse_args()
684
+ try:
685
+ if args.command == "sign":
686
+ if not args.verifier_bundle.is_file():
687
+ raise ValueError("verifier bundle path must identify a regular file")
688
+ result = create_attestation(args.report, args.private_key, args.key_id,
689
+ digest_file(args.verifier_bundle), args.verifier_identity)
690
+ if args.output.exists():
691
+ raise FileExistsError(args.output)
692
+ with args.output.open("x", encoding="utf-8", newline="") as stream:
693
+ stream.write(json.dumps(result, sort_keys=True, indent=2) + "\n")
694
+ output = {"signed": True, "key_id": result["key_id"],
695
+ "report_sha256": result["report_sha256"], "output": str(args.output)}
696
+ else:
697
+ output = verify_attestation(args.report, args.attestation, args.trust_store,
698
+ args.trust_store_sha256, args.timestamp_request,
699
+ args.timestamp_response, args.tsa_ca,
700
+ args.tsa_ca_sha256, args.tsa_chain, args.verifier_bundle)
701
+ except (OSError, json.JSONDecodeError, ValueError, TypeError) as exc:
702
+ print("ERROR: " + str(exc), file=sys.stderr)
703
+ return 1
704
+ print(json.dumps(output, sort_keys=True, indent=2))
705
+ return 0
706
+
707
+
708
+ if __name__ == "__main__":
709
+ raise SystemExit(main())