forked from ChelseaKR/permit-bearings
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevidence_export.py
More file actions
1977 lines (1778 loc) · 70.1 KB
/
Copy pathevidence_export.py
File metadata and controls
1977 lines (1778 loc) · 70.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Portable public/synthetic evidence export and restore verification.
The package is deliberately a bounded data handoff. It contains only files
explicitly named in a versioned profile, uses raw archive-member digests, and
restores inertly into a new directory. It does not adopt a source snapshot,
publish guidance, create a review decision, or handle applicant data.
"""
from __future__ import annotations
import hashlib
import io
import json
import os
import platform
import re
import shutil
import stat
import subprocess # nosec B404
import tempfile
import zipfile
from dataclasses import dataclass
from datetime import date
from errno import EEXIST
from pathlib import Path
from typing import Any
from .dates import resolve_today
from .harness.watch import normalized_digest
# The subprocess boundary below invokes Git only through fixed argument vectors
# with shell execution disabled; the executable is resolved with ``shutil.which``.
PROFILE_PATHS = {
1: Path("data/export/public-synthetic-evidence-v1.json"),
2: Path("data/export/public-synthetic-evidence-v2.json"),
}
DEFAULT_PROFILE_VERSION = 2
DEFAULT_PROFILE_PATH = PROFILE_PATHS[DEFAULT_PROFILE_VERSION]
MANIFEST_FILENAME = "MANIFEST.json"
PACKAGE_SCHEMA_VERSION = DEFAULT_PROFILE_VERSION
PROFILE_SCHEMA_VERSION = DEFAULT_PROFILE_VERSION
SUPPORTED_SCHEMA_VERSIONS = frozenset(PROFILE_PATHS)
MEMBER_SHA256_BASIS = "raw_archive_member_bytes"
_FIXED_ZIP_DATETIME = (1980, 1, 1, 0, 0, 0)
_FIXED_ZIP_MODE = stat.S_IFREG | 0o644
_IDENTIFIER = re.compile(r"^[a-z][a-z0-9-]*$")
_SHA256 = re.compile(r"^sha256:[0-9a-f]{64}$")
_SOURCE_ID = re.compile(r"^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$")
_COMMIT_SHA = re.compile(r"^[0-9a-f]{40}$")
_PATH_COMPONENT = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$")
_MAX_MEMBERS = 128
_MAX_MEMBER_BYTES = 16 * 1024 * 1024
_MAX_TOTAL_BYTES = 32 * 1024 * 1024
_MAX_ARCHIVE_BYTES = 32 * 1024 * 1024
_MAX_MANIFEST_BYTES = 1 * 1024 * 1024
_CHUNK_BYTES = 1024 * 1024
_MAX_PATH_BYTES = 240
_MAX_COMPONENT_BYTES = 100
_MAX_PATH_DEPTH = 12
_MAX_STATE_ASSERTIONS = 64
_WINDOWS_RESERVED_COMPONENTS = {
"aux",
"clock$",
"con",
"nul",
"prn",
*(f"com{index}" for index in range(1, 10)),
*(f"lpt{index}" for index in range(1, 10)),
}
_ROLES = frozenset(
{
"availability_record",
"conformance_checks",
"conformance_development_fixture",
"conformance_result",
"conformance_results",
"content_review_ledger",
"derived_browser_bundle",
"derived_coverage_index",
"export_profile",
"flagship_gate",
"golden_fixtures",
"hcd_letter_snapshot",
"journey_definition",
"journey_evidence",
"jurisdiction_registry",
"license",
"manual_evidence_ledger",
"participant_ledger",
"plain_language_drafts",
"provenance",
"public_source_copy",
"public_source_dataset",
"public_source_index",
"public_transit_source",
"readiness_evidence",
"readiness_packet",
"readiness_remedies",
"readiness_workflow",
"rule_index",
"rule_records",
"rule_verification_ledger",
"source_change_rehearsal_ledger",
"source_registry",
"source_state_receipt",
"third_party_notices",
"workflow_registry",
}
)
_PROFILE_KEYS = {
"schema_version",
"package",
"scope",
"entries",
"public_state_assertions",
}
_PROFILE_PACKAGE_KEYS = {"archive_root", "package_id"}
_PROFILE_SCOPE_KEYS = {
"classification",
"claim_boundary",
"exclusions",
"known_absences",
}
_MANIFEST_KEYS = {
"schema_version",
"package",
"freeze",
"scope",
"profile",
"files",
"tree_fingerprint",
"member_sha256_basis",
"referenced_official_sources_without_retained_copy",
"exclusions",
"known_absences",
"public_state_assertions",
}
_MANIFEST_PACKAGE_KEYS = {"archive_root", "package_id"}
_MANIFEST_FREEZE_KEYS = {"freeze_id", "frozen_on", "repository_commit_sha"}
_MANIFEST_SCOPE_KEYS = {"classification", "claim_boundary"}
_MANIFEST_PROFILE_KEYS = {"path", "sha256"}
_MANIFEST_FILE_KEYS = {"path", "role", "sha256", "bytes"}
_MANIFEST_SOURCE_REFERENCE_KEYS = {"source_id", "label", "url"}
_STATE_ASSERTION_KEYS = {"path", "pointer", "equals"}
_SELF_PROFILE_ENTRY_KEYS = {"path", "role", "raw_sha256", "self_reference"}
_ORDINARY_PROFILE_ENTRY_KEYS = {"path", "role", "raw_sha256"}
_WORKFLOW_ARTIFACT_ROLES = {
"journey": "journey_definition",
"journey_evidence": "journey_evidence",
"program_availability": "availability_record",
"readiness_evidence": "readiness_evidence",
"readiness_packet": "readiness_packet",
"readiness_remedies": "readiness_remedies",
"readiness_workflow": "readiness_workflow",
}
@dataclass(frozen=True)
class ProfileEntry:
"""One explicitly allowed file and its expected raw-byte digest."""
path: str
role: str
raw_sha256: str | None
self_reference: bool = False
@dataclass(frozen=True)
class StateAssertion:
"""A public/synthetic state that must remain true for this profile."""
path: str
pointer: str
equals: str | int | float | bool | None
@dataclass(frozen=True)
class ExportProfile:
"""Validated export profile data."""
package_id: str
archive_root: str
classification: tuple[str, ...]
claim_boundary: str
exclusions: tuple[str, ...]
known_absences: tuple[str, ...]
entries: tuple[ProfileEntry, ...]
state_assertions: tuple[StateAssertion, ...]
profile_path: str
schema_version: int = DEFAULT_PROFILE_VERSION
@dataclass(frozen=True)
class _ManifestFile:
path: str
role: str
sha256: str
byte_count: int
@dataclass(frozen=True)
class _Manifest:
"""Parsed archive manifest, retained internally after strict validation."""
payload: dict[str, Any]
package_id: str
archive_root: str
freeze_id: str
frozen_on: str
repository_commit_sha: str
profile_path: str
profile_sha256: str
files: tuple[_ManifestFile, ...]
schema_version: int
def _require_object(value: Any, field: str) -> dict[str, Any]:
if not isinstance(value, dict):
raise ValueError(f"{field}: expected an object")
return value
def _require_exact_keys(value: dict[str, Any], expected: set[str], field: str) -> None:
if set(value) != expected:
raise ValueError(f"{field}: invalid fields")
def _require_text(value: Any, field: str) -> str:
if not isinstance(value, str) or not value or value != value.strip():
raise ValueError(f"{field}: expected exact non-blank text")
return value
def _require_exact_text(value: Any, field: str) -> str:
if not isinstance(value, str) or not value or value != value.strip():
raise ValueError(f"{field}: expected exact non-blank text")
return value
def _require_identifier(value: Any, field: str) -> str:
identifier = _require_text(value, field)
if not _IDENTIFIER.fullmatch(identifier):
raise ValueError(f"{field}: invalid stable identifier")
return identifier
def _require_role(value: Any, field: str) -> str:
role = _require_text(value, field)
if role not in _ROLES:
raise ValueError(f"{field}: invalid artifact role")
return role
def _require_sha256(value: Any, field: str) -> str:
digest = _require_text(value, field)
if not _SHA256.fullmatch(digest):
raise ValueError(f"{field}: expected a SHA-256 digest")
return digest
def _require_commit_sha(value: Any, field: str) -> str:
commit_sha = _require_exact_text(value, field)
if not _COMMIT_SHA.fullmatch(commit_sha):
raise ValueError(f"{field}: expected a full lowercase commit SHA")
return commit_sha
def _safe_relative_path(value: Any, field: str) -> str:
path = _require_exact_text(value, field)
if not path.isascii() or len(path.encode("ascii")) > _MAX_PATH_BYTES:
raise ValueError(f"{field}: path must be short ASCII text")
if path.startswith("/") or "\\" in path or "\x00" in path or "//" in path:
raise ValueError(f"{field}: absolute or unsafe path")
parts = path.split("/")
if len(parts) > _MAX_PATH_DEPTH or any(part in {"", ".", ".."} for part in parts):
raise ValueError(f"{field}: traversal or normalized path is not allowed")
for part in parts:
if (
len(part.encode("ascii")) > _MAX_COMPONENT_BYTES
or not _PATH_COMPONENT.fullmatch(part)
or part.endswith((".", " "))
or ":" in part
):
raise ValueError(f"{field}: non-canonical path component")
windows_base = part.split(".", 1)[0].casefold()
if windows_base in _WINDOWS_RESERVED_COMPONENTS:
raise ValueError(f"{field}: Windows-reserved path component")
return path
def _require_string_list(value: Any, field: str) -> tuple[str, ...]:
if not isinstance(value, list) or not value:
raise ValueError(f"{field}: expected a non-empty list")
items = tuple(
_require_text(item, f"{field}[{index}]") for index, item in enumerate(value)
)
if len(items) != len(set(items)):
raise ValueError(f"{field}: duplicate values are not allowed")
return items
def _require_iso_date(value: Any, field: str) -> str:
text = _require_text(value, field)
try:
parsed = date.fromisoformat(text)
except ValueError as error:
raise ValueError(f"{field}: expected an ISO calendar date") from error
if parsed.isoformat() != text or parsed < date(1980, 1, 1):
raise ValueError(f"{field}: expected an ISO date on or after 1980-01-01")
return text
def _require_frozen_on(value: Any, field: str, *, today: date) -> str:
frozen_on = _require_iso_date(value, field)
if date.fromisoformat(frozen_on) > today:
raise ValueError(f"{field}: future dates are not allowed")
return frozen_on
def _canonical_json(value: Any) -> bytes:
return json.dumps(
value,
ensure_ascii=False,
separators=(",", ":"),
sort_keys=True,
).encode("utf-8")
def _manifest_json(value: dict[str, Any]) -> bytes:
return (
json.dumps(value, ensure_ascii=False, indent=2, sort_keys=True) + "\n"
).encode("utf-8")
def _sha256_bytes(value: bytes) -> str:
return "sha256:" + hashlib.sha256(value).hexdigest()
def _tree_fingerprint(files: tuple[_ManifestFile, ...]) -> str:
payload = [
{
"bytes": item.byte_count,
"path": item.path,
"role": item.role,
"sha256": item.sha256,
}
for item in files
]
return _sha256_bytes(_canonical_json(payload))
def _parse_profile_entry(
value: Any,
field: str,
*,
profile_path: str,
) -> ProfileEntry:
entry = _require_object(value, field)
path = _safe_relative_path(entry.get("path"), f"{field}.path")
role = _require_role(entry.get("role"), f"{field}.role")
if set(entry) == _ORDINARY_PROFILE_ENTRY_KEYS:
return ProfileEntry(
path=path,
role=role,
raw_sha256=_require_sha256(entry.get("raw_sha256"), f"{field}.raw_sha256"),
)
if set(entry) != _SELF_PROFILE_ENTRY_KEYS:
raise ValueError(f"{field}: invalid fields")
if (
entry.get("self_reference") is not True
or entry.get("raw_sha256") is not None
or path != profile_path
or role != "export_profile"
):
raise ValueError(f"{field}: invalid export-profile self reference")
return ProfileEntry(path=path, role=role, raw_sha256=None, self_reference=True)
def _scalar(value: Any, field: str) -> str | int | float | bool | None:
if value is None or isinstance(value, (str, int, float, bool)):
return value
raise ValueError(f"{field}: expected a scalar JSON value")
def _parse_state_assertion(value: Any, field: str) -> StateAssertion:
assertion = _require_object(value, field)
_require_exact_keys(assertion, _STATE_ASSERTION_KEYS, field)
path = _safe_relative_path(assertion.get("path"), f"{field}.path")
if not path.startswith("data/validation/"):
raise ValueError(
f"{field}.path: only validation ledgers can carry state assertions"
)
pointer = _require_text(assertion.get("pointer"), f"{field}.pointer")
if not pointer.startswith("/") or pointer.endswith("/"):
raise ValueError(f"{field}.pointer: expected a non-root JSON pointer")
return StateAssertion(
path=path,
pointer=pointer,
equals=_scalar(assertion.get("equals"), f"{field}.equals"),
)
def _require_source_registry_entry(
entries: tuple[ProfileEntry, ...], profile_path: str
) -> None:
source_entry = next(
(entry for entry in entries if entry.path == "data/sources.json"), None
)
if source_entry is None or source_entry.role != "source_registry":
raise ValueError(
f"{profile_path}.entries: data/sources.json must be the source registry"
)
def _require_workflow_registry_entry(
entries: tuple[ProfileEntry, ...], profile_path: str
) -> None:
workflow_entry = next(
(entry for entry in entries if entry.path == "data/workflows/registry.json"),
None,
)
if workflow_entry is None or workflow_entry.role != "workflow_registry":
raise ValueError(
f"{profile_path}.entries: data/workflows/registry.json must be the "
"workflow registry"
)
def _profile_schema_version(profile_path: str) -> int:
matches = [
version
for version, canonical_path in PROFILE_PATHS.items()
if canonical_path.as_posix() == profile_path
]
if len(matches) != 1:
raise ValueError(
f"{profile_path}: expected a canonical versioned export profile path"
)
return matches[0]
def _validate_profile_registry_membership(
entries: tuple[ProfileEntry, ...],
profile_path: str,
schema_version: int,
) -> None:
if schema_version == 1:
if any(entry.role == "workflow_registry" for entry in entries):
raise ValueError(
f"{profile_path}.entries: schema v1 cannot include a workflow "
"registry; use the schema-v2 profile"
)
return
_require_workflow_registry_entry(entries, profile_path)
def _parse_profile(
payload: Any,
profile_path: str,
) -> ExportProfile:
profile = _require_object(payload, profile_path)
_require_exact_keys(profile, _PROFILE_KEYS, profile_path)
expected_schema_version = _profile_schema_version(profile_path)
if (
type(profile.get("schema_version")) is not int
or profile.get("schema_version") != expected_schema_version
):
raise ValueError(
f"{profile_path}.schema_version: expected {expected_schema_version}"
)
package = _require_object(profile.get("package"), f"{profile_path}.package")
_require_exact_keys(package, _PROFILE_PACKAGE_KEYS, f"{profile_path}.package")
package_id = _require_identifier(package.get("package_id"), "package.package_id")
archive_root = _require_identifier(
package.get("archive_root"), "package.archive_root"
)
scope = _require_object(profile.get("scope"), f"{profile_path}.scope")
_require_exact_keys(scope, _PROFILE_SCOPE_KEYS, f"{profile_path}.scope")
classification = _require_string_list(
scope.get("classification"), "scope.classification"
)
if classification != ("public", "synthetic"):
raise ValueError("scope.classification: expected public and synthetic")
entries_raw = profile.get("entries")
if (
not isinstance(entries_raw, list)
or not entries_raw
or len(entries_raw) > _MAX_MEMBERS - 1
):
raise ValueError(f"{profile_path}.entries: expected a non-empty list")
entries = tuple(
_parse_profile_entry(value, f"entries[{index}]", profile_path=profile_path)
for index, value in enumerate(entries_raw)
)
paths = tuple(entry.path for entry in entries)
if (
paths != tuple(sorted(paths))
or len(paths) != len(set(paths))
or len({path.casefold() for path in paths}) != len(paths)
):
raise ValueError(f"{profile_path}.entries: expected sorted unique paths")
if any(
not (entry.path.startswith("data/") or entry.path.startswith("corpus/"))
and entry.path not in {"LICENSE", "PROVENANCE.md", "THIRD_PARTY_NOTICES.md"}
for entry in entries
):
raise ValueError(
f"{profile_path}.entries: path is outside the public allowlist"
)
if sum(entry.self_reference for entry in entries) != 1:
raise ValueError(
f"{profile_path}.entries: expected one self-referential profile"
)
_require_source_registry_entry(entries, profile_path)
_validate_profile_registry_membership(
entries,
profile_path,
expected_schema_version,
)
assertions_raw = profile.get("public_state_assertions")
if (
not isinstance(assertions_raw, list)
or not assertions_raw
or len(assertions_raw) > _MAX_STATE_ASSERTIONS
):
raise ValueError(
f"{profile_path}.public_state_assertions: expected a non-empty list"
)
assertions = tuple(
_parse_state_assertion(value, f"public_state_assertions[{index}]")
for index, value in enumerate(assertions_raw)
)
assertion_keys = tuple((item.path, item.pointer) for item in assertions)
if len(assertion_keys) != len(set(assertion_keys)):
raise ValueError("public_state_assertions: duplicate path/pointer")
if not {item.path for item in assertions} <= set(paths):
raise ValueError("public_state_assertions: path is not exported")
return ExportProfile(
package_id=package_id,
archive_root=archive_root,
classification=classification,
claim_boundary=_require_text(
scope.get("claim_boundary"), "scope.claim_boundary"
),
exclusions=_require_string_list(scope.get("exclusions"), "scope.exclusions"),
known_absences=_require_string_list(
scope.get("known_absences"), "scope.known_absences"
),
entries=entries,
state_assertions=assertions,
profile_path=profile_path,
schema_version=expected_schema_version,
)
def _root_directory(root: Path) -> Path:
if root.is_symlink():
raise ValueError(f"{root}: expected a real repository directory")
resolved = root.resolve()
if not resolved.is_dir():
raise ValueError(f"{root}: expected a real repository directory")
return resolved
def _profile_file(
root: Path,
profile_path: Path | None,
*,
profile_version: int | None = None,
) -> tuple[Path, str]:
if profile_path is not None and profile_version is not None:
raise ValueError("select either profile_path or profile_version, not both")
if profile_path is None:
selected_version = profile_version
if selected_version is None:
selected_version = next(
(
version
for version in sorted(PROFILE_PATHS, reverse=True)
if (root / PROFILE_PATHS[version]).exists()
or (root / PROFILE_PATHS[version]).is_symlink()
),
DEFAULT_PROFILE_VERSION,
)
if (
type(selected_version) is not int
or selected_version not in SUPPORTED_SCHEMA_VERSIONS
):
raise ValueError("profile_version: expected 1 or 2")
selected_path = PROFILE_PATHS[selected_version]
relative = selected_path.as_posix()
return root / selected_path, relative
if profile_path.is_absolute():
candidate = profile_path.resolve()
try:
relative = candidate.relative_to(root).as_posix()
except ValueError as error:
raise ValueError(
"profile path must be inside the repository root"
) from error
return candidate, _safe_relative_path(relative, "profile path")
relative = _safe_relative_path(profile_path.as_posix(), "profile path")
return root / Path(*relative.split("/")), relative
def _regular_file(root: Path, relative: str) -> Path:
path = root
for part in relative.split("/"):
path = path / part
if path.is_symlink():
raise ValueError(f"{relative}: symbolic links are not allowed")
try:
resolved = path.resolve(strict=True)
except OSError as error:
raise ValueError(f"{relative}: expected a readable regular file") from error
if not resolved.is_relative_to(root) or not path.is_file():
raise ValueError(f"{relative}: expected a regular file inside the repository")
return path
def _read_regular_file_bytes(root: Path, relative: str, *, maximum: int) -> bytes:
path = _regular_file(root, relative)
try:
if path.stat().st_size > maximum:
raise ValueError(f"{relative}: file exceeds the size limit")
chunks: list[bytes] = []
total = 0
with path.open("rb") as stream:
while chunk := stream.read(_CHUNK_BYTES):
total += len(chunk)
if total > maximum:
raise ValueError(f"{relative}: file exceeds the size limit")
chunks.append(chunk)
except OSError as error:
raise ValueError(f"{relative}: expected a readable regular file") from error
return b"".join(chunks)
class _DuplicateJsonKey(ValueError):
"""Raised by the JSON object-pairs hook before a duplicate is overwritten."""
def _unique_json_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
result: dict[str, Any] = {}
for key, value in pairs:
if key in result:
raise _DuplicateJsonKey(key)
result[key] = value
return result
def _reject_json_constant(value: str) -> None:
raise ValueError(f"unsupported JSON constant {value!r}")
def _read_json_bytes(value: bytes, field: str) -> Any:
try:
return json.loads(
value.decode("utf-8"),
object_pairs_hook=_unique_json_object,
parse_constant=_reject_json_constant,
)
except _DuplicateJsonKey as error:
raise ValueError(f"{field}: duplicate JSON object key {error}") from error
except (UnicodeDecodeError, json.JSONDecodeError, RecursionError) as error:
raise ValueError(f"{field}: invalid UTF-8 JSON") from error
def _validate_local_source_copy(
record: dict[str, Any],
source_id: str,
copy_path: str,
exported_paths: set[str],
payloads: dict[str, bytes] | None,
) -> None:
if copy_path not in exported_paths:
raise ValueError(
f"{source_id}.local_copy: referenced official source is not exported"
)
if payloads is None:
return
if copy_path not in payloads:
raise ValueError(f"{source_id}.local_copy: source bytes are unavailable")
expected_digest = _require_exact_text(record.get("sha256"), f"{source_id}.sha256")
if not re.fullmatch(r"[0-9a-f]{64}", expected_digest):
raise ValueError(f"{source_id}.sha256: invalid normalized SHA-256")
normalize = record.get("normalize")
if normalize not in {None, "html-text"}:
raise ValueError(f"{source_id}.normalize: unsupported normalization")
if normalized_digest(payloads[copy_path], normalize) != expected_digest:
raise ValueError(
f"{source_id}.local_copy: normalized source digest does not match "
"data/sources.json"
)
def _source_references_without_copies(
value: Any,
exported_paths: set[str],
payloads: dict[str, bytes] | None = None,
) -> tuple[dict[str, str], ...]:
registry = _require_object(value, "data/sources.json")
references: list[dict[str, str]] = []
for url, raw_record in registry.items():
source_url = _require_text(url, "data/sources.json URL")
record = _require_object(raw_record, f"data/sources.json[{source_url!r}]")
source_id = _require_text(record.get("source_id"), "source_id")
if not _SOURCE_ID.fullmatch(source_id):
raise ValueError("data/sources.json.source_id: invalid stable identifier")
label = _require_text(record.get("label"), f"{source_id}.label")
local_copy = record.get("local_copy")
if local_copy is None:
references.append(
{"source_id": source_id, "label": label, "url": source_url}
)
continue
copy_path = _safe_relative_path(local_copy, f"{source_id}.local_copy")
_validate_local_source_copy(
record,
source_id,
copy_path,
exported_paths,
payloads,
)
if len({reference["source_id"] for reference in references}) != len(references):
raise ValueError("data/sources.json: duplicate source IDs without local copies")
return tuple(sorted(references, key=lambda reference: reference["source_id"]))
def _pointer_value(value: Any, pointer: str) -> Any:
current = value
for raw_token in pointer[1:].split("/"):
token = raw_token.replace("~1", "/").replace("~0", "~")
if isinstance(current, dict):
if token not in current:
raise ValueError(f"{pointer}: missing object field {token!r}")
current = current[token]
continue
if isinstance(current, list) and token.isdecimal():
index = int(token)
if index < len(current):
current = current[index]
continue
raise ValueError(f"{pointer}: cannot resolve JSON pointer")
return current
def _validate_state_assertions(
profile: ExportProfile,
payloads: dict[str, bytes],
) -> None:
parsed: dict[str, Any] = {}
for assertion in profile.state_assertions:
if assertion.path not in parsed:
parsed[assertion.path] = _read_json_bytes(
payloads[assertion.path], assertion.path
)
actual = _pointer_value(parsed[assertion.path], assertion.pointer)
if type(actual) is not type(assertion.equals) or actual != assertion.equals:
raise ValueError(
f"{assertion.path}{assertion.pointer}: public/synthetic state drifted"
)
def _entry_payloads(root: Path, profile: ExportProfile) -> dict[str, bytes]:
payloads: dict[str, bytes] = {}
total = 0
for entry in profile.entries:
content = _read_regular_file_bytes(
root,
entry.path,
maximum=_MAX_MEMBER_BYTES,
)
total += len(content)
if total > _MAX_TOTAL_BYTES:
raise ValueError("export profile: total file size exceeds the limit")
actual = _sha256_bytes(content)
if entry.raw_sha256 is not None and actual != entry.raw_sha256:
raise ValueError(f"{entry.path}: raw SHA-256 does not match the profile")
payloads[entry.path] = content
return payloads
def _validate_exported_workflow_artifact(
artifact: Any,
*,
artifact_name: str,
artifact_field: str,
required_role: str,
exported: dict[str, ProfileEntry],
payloads: dict[str, bytes],
) -> None:
record = _require_object(artifact, artifact_field)
generated = artifact_name in {"journey_evidence", "readiness_evidence"}
_require_exact_keys(
record,
{"path"} if generated else {"path", "sha256"},
artifact_field,
)
path = _safe_relative_path(record.get("path"), f"{artifact_field}.path")
exported_entry = exported.get(path)
if exported_entry is None or exported_entry.role != required_role:
raise ValueError(
f"{artifact_field}.path: referenced workflow artifact is not "
"exported with its required role"
)
if generated:
return
expected_digest = _require_text(record.get("sha256"), f"{artifact_field}.sha256")
if not re.fullmatch(r"[0-9a-f]{64}", expected_digest):
raise ValueError(f"{artifact_field}.sha256: invalid SHA-256")
if _sha256_bytes(payloads[path]) != f"sha256:{expected_digest}":
raise ValueError(
f"{artifact_field}.sha256: registry fingerprint does not match "
"exported bytes"
)
def _validate_workflow_registry_closure(
profile: ExportProfile,
payloads: dict[str, bytes],
) -> None:
"""Require a registry-aware profile to carry every selected artifact.
This is an export-membership check, not a workflow approval or a substitute
for the canonical workflow-registry loader replayed during build/restore.
"""
registry_entries = tuple(
entry for entry in profile.entries if entry.role == "workflow_registry"
)
if not registry_entries:
return
if profile.schema_version == 1:
raise ValueError("schema v1 cannot include a workflow registry")
if len(registry_entries) != 1:
raise ValueError("export profile: expected exactly one workflow registry")
registry_entry = registry_entries[0]
registry = _require_object(
_read_json_bytes(payloads[registry_entry.path], registry_entry.path),
registry_entry.path,
)
workflows = registry.get("workflows")
if not isinstance(workflows, list) or not workflows:
raise ValueError(f"{registry_entry.path}.workflows: expected a non-empty list")
exported = {entry.path: entry for entry in profile.entries}
for workflow_index, raw_workflow in enumerate(workflows):
workflow_field = f"{registry_entry.path}.workflows[{workflow_index}]"
workflow = _require_object(raw_workflow, workflow_field)
artifacts_field = f"{workflow_field}.artifacts"
artifacts = _require_object(workflow.get("artifacts"), artifacts_field)
_require_exact_keys(artifacts, set(_WORKFLOW_ARTIFACT_ROLES), artifacts_field)
for artifact_name, required_role in _WORKFLOW_ARTIFACT_ROLES.items():
_validate_exported_workflow_artifact(
artifacts.get(artifact_name),
artifact_name=artifact_name,
artifact_field=f"{artifacts_field}.{artifact_name}",
required_role=required_role,
exported=exported,
payloads=payloads,
)
def _git_head(root: Path) -> str:
git = shutil.which("git")
if git is None:
raise ValueError("repository: Git is required to bind an export commit")
try:
completed = subprocess.run( # noqa: S603 # nosec B603
[git, "-C", str(root), "rev-parse", "HEAD"],
check=False,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
)
except OSError as error:
raise ValueError(
"repository: Git is required to bind an export commit"
) from error
if completed.returncode != 0:
raise ValueError("repository: Git HEAD is required to build an export")
return _require_commit_sha(
completed.stdout.decode("ascii", "strict").strip(),
"repository Git HEAD",
)
def _verify_profile_matches_git_head(
root: Path,
profile: ExportProfile,
payloads: dict[str, bytes],
*,
repository_commit_sha: str | None,
) -> str:
head = _git_head(root)
git = shutil.which("git")
if git is None:
raise ValueError("repository: Git is required to bind an export commit")
if repository_commit_sha is not None:
requested = _require_commit_sha(
repository_commit_sha,
"repository_commit_sha",
)
if requested != head:
raise ValueError("repository_commit_sha: does not match Git HEAD")
for entry in profile.entries:
completed = subprocess.run( # noqa: S603 # nosec B603
[git, "-C", str(root), "show", f"{head}:{entry.path}"],
check=False,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
)
if completed.returncode != 0:
raise ValueError(
f"{entry.path}: export profile files must be tracked by Git HEAD"
)
if completed.stdout != payloads[entry.path]:
raise ValueError(f"{entry.path}: differs from the bound Git HEAD")
return head
def load_export_profile(
root: Path,
profile_path: Path | None = None,
*,
profile_version: int | None = None,
) -> ExportProfile:
"""Load a pinned, public/synthetic-only export profile from ``root``."""
repository = _root_directory(root)
_, relative = _profile_file(
repository,
profile_path,
profile_version=profile_version,
)
raw = _read_regular_file_bytes(
repository,
relative,
maximum=_MAX_MANIFEST_BYTES,
)
profile = _parse_profile(_read_json_bytes(raw, relative), relative)
payloads = _entry_payloads(repository, profile)
_validate_workflow_registry_closure(profile, payloads)
_source_references_without_copies(
_read_json_bytes(payloads["data/sources.json"], "data/sources.json"),
set(payloads),
payloads,
)
_validate_state_assertions(profile, payloads)
return profile
def _manifest_payload(
profile: ExportProfile,
freeze_id: str,
frozen_on: str,
repository_commit_sha: str,
payloads: dict[str, bytes],
) -> dict[str, Any]:
files = tuple(
_ManifestFile(
path=entry.path,
role=entry.role,
sha256=_sha256_bytes(payloads[entry.path]),
byte_count=len(payloads[entry.path]),
)
for entry in profile.entries
)
profile_entry = next(item for item in files if item.path == profile.profile_path)
source_references = _source_references_without_copies(
_read_json_bytes(payloads["data/sources.json"], "data/sources.json"),
{item.path for item in files},
payloads,
)
return {
"schema_version": profile.schema_version,
"package": {
"archive_root": profile.archive_root,
"package_id": profile.package_id,
},
"freeze": {
"freeze_id": freeze_id,
"frozen_on": frozen_on,
"repository_commit_sha": repository_commit_sha,
},
"scope": {
"classification": list(profile.classification),
"claim_boundary": profile.claim_boundary,
},
"profile": {"path": profile.profile_path, "sha256": profile_entry.sha256},
"files": [
{