itself 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- itself/__init__.py +282 -0
- itself/_endpoints.py +255 -0
- itself/_filesystem.py +187 -0
- itself/_formats.py +104 -0
- itself/_json.py +223 -0
- itself/_version.py +8 -0
- itself/bundle.py +723 -0
- itself/cli.py +719 -0
- itself/decision_model.py +1283 -0
- itself/evidence_bundle.py +981 -0
- itself/inference.py +1571 -0
- itself/ledger.py +373 -0
- itself/py.typed +0 -0
- itself/receipts.py +621 -0
- itself/records.py +743 -0
- itself/reporting.py +125 -0
- itself/schema_export.py +178 -0
- itself/schemas/v0alpha/evidence-bundle.schema.json +144 -0
- itself/schemas/v0alpha/protocol.schema.json +466 -0
- itself/schemas/v0alpha/reasoning-receipt.schema.json +366 -0
- itself/schemas/v0alpha2/evidence-bundle.schema.json +145 -0
- itself/schemas/v0alpha2/protocol.schema.json +503 -0
- itself/schemas/v0alpha2/reasoning-receipt.schema.json +406 -0
- itself/state.py +178 -0
- itself/types.py +21 -0
- itself/validation.py +185 -0
- itself-0.2.0.dist-info/METADATA +508 -0
- itself-0.2.0.dist-info/RECORD +32 -0
- itself-0.2.0.dist-info/WHEEL +5 -0
- itself-0.2.0.dist-info/entry_points.txt +2 -0
- itself-0.2.0.dist-info/licenses/LICENSE +373 -0
- itself-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,981 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MPL-2.0
|
|
2
|
+
# Copyright (C) 2026 Greater Expanse LLC
|
|
3
|
+
|
|
4
|
+
"""Closed, digest-inventoried evidence bundles for exchange and inspection."""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import hashlib
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import shutil
|
|
12
|
+
import stat
|
|
13
|
+
import tempfile
|
|
14
|
+
from collections.abc import Collection, Iterator, Sequence
|
|
15
|
+
from contextlib import suppress
|
|
16
|
+
from copy import deepcopy
|
|
17
|
+
from dataclasses import dataclass, field, replace
|
|
18
|
+
from datetime import UTC, datetime
|
|
19
|
+
from enum import StrEnum
|
|
20
|
+
from importlib.resources import files
|
|
21
|
+
from pathlib import Path, PurePosixPath
|
|
22
|
+
from typing import Final, Protocol, cast
|
|
23
|
+
|
|
24
|
+
from jsonschema import Draft202012Validator
|
|
25
|
+
from jsonschema.exceptions import ValidationError
|
|
26
|
+
|
|
27
|
+
from ._filesystem import publish_path_no_replace, write_file_exclusive
|
|
28
|
+
from ._formats import schema_format_checker
|
|
29
|
+
from ._json import format_json_path as _format_path
|
|
30
|
+
from ._json import strict_json_loads
|
|
31
|
+
from .bundle import BundleValidator
|
|
32
|
+
from .ledger import Ledger, decode_jsonl_records
|
|
33
|
+
from .receipts import (
|
|
34
|
+
ReasoningReceiptValidator,
|
|
35
|
+
build_reasoning_receipt,
|
|
36
|
+
canonical_ledger_bytes,
|
|
37
|
+
decode_receipt_document,
|
|
38
|
+
)
|
|
39
|
+
from .types import JsonObject, JsonValue, StrPath
|
|
40
|
+
|
|
41
|
+
EVIDENCE_BUNDLE_VERSION: Final = "0.1.0-alpha.2"
|
|
42
|
+
BUNDLE_MANIFEST_NAME: Final = "bundle.json"
|
|
43
|
+
EVIDENCE_BUNDLE_LEDGER_PATH: Final = "ledger.jsonl"
|
|
44
|
+
EVIDENCE_BUNDLE_RECEIPT_PATH: Final = "reasoning-receipt.json"
|
|
45
|
+
DEFAULT_EVIDENCE_BUNDLE_LIMITATIONS: Final = (
|
|
46
|
+
"Structural integrity does not establish that any real-world claim is true.",
|
|
47
|
+
(
|
|
48
|
+
"The bundle does not establish that an evidence source, evaluator, "
|
|
49
|
+
"or authority is correct."
|
|
50
|
+
),
|
|
51
|
+
)
|
|
52
|
+
_DIGEST_CHUNK_BYTES: Final = 1024 * 1024
|
|
53
|
+
# Bundle paths double as artifact URIs. URI readers decode percent escapes and
|
|
54
|
+
# drop queries and fragments, so the builder refuses these characters; the
|
|
55
|
+
# validator still accepts them, which leaves the published format unchanged.
|
|
56
|
+
_BUILDER_REJECTED_PATH_CHARACTERS: Final = frozenset("%?#")
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class _SchemaValidator(Protocol):
|
|
60
|
+
"""Typed surface used from the partially typed jsonschema dependency."""
|
|
61
|
+
|
|
62
|
+
def iter_errors(self, instance: JsonValue) -> Iterator[ValidationError]: ...
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class EvidenceBundleValidationError(ValueError):
|
|
66
|
+
"""Raised when an evidence bundle is structurally or cryptographically invalid."""
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class EvidenceBundleBuildError(ValueError):
|
|
70
|
+
"""Raised when an evidence bundle cannot be safely materialized."""
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass(frozen=True, slots=True)
|
|
74
|
+
class EvidenceBundleLimits:
|
|
75
|
+
"""Explicit resource ceilings applied while building and verifying bundles."""
|
|
76
|
+
|
|
77
|
+
max_manifest_bytes: int = 4 * 1024 * 1024
|
|
78
|
+
max_files: int = 1024
|
|
79
|
+
max_directory_entries: int = 4096
|
|
80
|
+
max_file_bytes: int = 256 * 1024 * 1024
|
|
81
|
+
max_total_bytes: int = 512 * 1024 * 1024
|
|
82
|
+
max_ledger_bytes: int = 128 * 1024 * 1024
|
|
83
|
+
# A receipt can be nearly as large as its ledger, so the two ceilings match.
|
|
84
|
+
max_receipt_bytes: int = 128 * 1024 * 1024
|
|
85
|
+
max_ledger_records: int = 100_000
|
|
86
|
+
|
|
87
|
+
def __post_init__(self) -> None:
|
|
88
|
+
values = (
|
|
89
|
+
("max_manifest_bytes", self.max_manifest_bytes),
|
|
90
|
+
("max_files", self.max_files),
|
|
91
|
+
("max_directory_entries", self.max_directory_entries),
|
|
92
|
+
("max_file_bytes", self.max_file_bytes),
|
|
93
|
+
("max_total_bytes", self.max_total_bytes),
|
|
94
|
+
("max_ledger_bytes", self.max_ledger_bytes),
|
|
95
|
+
("max_receipt_bytes", self.max_receipt_bytes),
|
|
96
|
+
("max_ledger_records", self.max_ledger_records),
|
|
97
|
+
)
|
|
98
|
+
for name, value in values:
|
|
99
|
+
runtime_value = cast(object, value)
|
|
100
|
+
if isinstance(runtime_value, bool) or not isinstance(runtime_value, int):
|
|
101
|
+
raise TypeError(f"{name} must be an integer")
|
|
102
|
+
if value < 0:
|
|
103
|
+
raise ValueError(f"{name} must not be negative")
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
DEFAULT_EVIDENCE_BUNDLE_LIMITS: Final = EvidenceBundleLimits()
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class EvidenceBundleFileRole(StrEnum):
|
|
110
|
+
"""Caller-supplied file roles accepted by the evidence-bundle builder."""
|
|
111
|
+
|
|
112
|
+
INPUT = "input"
|
|
113
|
+
ARTIFACT = "artifact"
|
|
114
|
+
SUPPLEMENTAL = "supplemental"
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
@dataclass(frozen=True, slots=True)
|
|
118
|
+
class EvidenceBundleFile:
|
|
119
|
+
"""One immutable caller-supplied file to materialize inside a bundle."""
|
|
120
|
+
|
|
121
|
+
path: str
|
|
122
|
+
content: bytes
|
|
123
|
+
media_type: str
|
|
124
|
+
role: EvidenceBundleFileRole
|
|
125
|
+
record_ref: str | None = None
|
|
126
|
+
|
|
127
|
+
def __post_init__(self) -> None:
|
|
128
|
+
try:
|
|
129
|
+
parse_bundle_path(self.path)
|
|
130
|
+
except EvidenceBundleValidationError as error:
|
|
131
|
+
raise EvidenceBundleBuildError(str(error)) from error
|
|
132
|
+
if not _BUILDER_REJECTED_PATH_CHARACTERS.isdisjoint(self.path):
|
|
133
|
+
raise EvidenceBundleBuildError(
|
|
134
|
+
f"bundle file path {self.path!r} must not contain '%', '?', or '#'"
|
|
135
|
+
)
|
|
136
|
+
if self.path in {
|
|
137
|
+
BUNDLE_MANIFEST_NAME,
|
|
138
|
+
EVIDENCE_BUNDLE_LEDGER_PATH,
|
|
139
|
+
EVIDENCE_BUNDLE_RECEIPT_PATH,
|
|
140
|
+
}:
|
|
141
|
+
raise EvidenceBundleBuildError(
|
|
142
|
+
f"bundle file path {self.path!r} is reserved by the builder"
|
|
143
|
+
)
|
|
144
|
+
if not isinstance(cast(object, self.content), bytes):
|
|
145
|
+
raise TypeError("bundle file content must be bytes")
|
|
146
|
+
if not self.media_type.strip():
|
|
147
|
+
raise EvidenceBundleBuildError("bundle file media_type must not be empty")
|
|
148
|
+
if not isinstance(cast(object, self.role), EvidenceBundleFileRole):
|
|
149
|
+
raise TypeError("bundle file role must be an EvidenceBundleFileRole")
|
|
150
|
+
if self.role is EvidenceBundleFileRole.ARTIFACT:
|
|
151
|
+
if self.record_ref is None or not self.record_ref.strip():
|
|
152
|
+
raise EvidenceBundleBuildError(
|
|
153
|
+
"artifact bundle files require a non-empty record_ref"
|
|
154
|
+
)
|
|
155
|
+
elif self.record_ref is not None:
|
|
156
|
+
raise EvidenceBundleBuildError(
|
|
157
|
+
"only artifact bundle files may declare record_ref"
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
@classmethod
|
|
161
|
+
def from_path(
|
|
162
|
+
cls,
|
|
163
|
+
source: StrPath,
|
|
164
|
+
*,
|
|
165
|
+
path: str,
|
|
166
|
+
media_type: str,
|
|
167
|
+
role: EvidenceBundleFileRole,
|
|
168
|
+
record_ref: str | None = None,
|
|
169
|
+
max_bytes: int = DEFAULT_EVIDENCE_BUNDLE_LIMITS.max_file_bytes,
|
|
170
|
+
) -> EvidenceBundleFile:
|
|
171
|
+
"""Read one regular, non-symlink source file into an immutable bundle file."""
|
|
172
|
+
|
|
173
|
+
source_path = Path(source)
|
|
174
|
+
runtime_max_bytes = cast(object, max_bytes)
|
|
175
|
+
if isinstance(runtime_max_bytes, bool) or not isinstance(
|
|
176
|
+
runtime_max_bytes, int
|
|
177
|
+
):
|
|
178
|
+
raise TypeError("max_bytes must be an integer")
|
|
179
|
+
if max_bytes < 0:
|
|
180
|
+
raise ValueError("max_bytes must not be negative")
|
|
181
|
+
try:
|
|
182
|
+
content = _read_bounded_regular_file(
|
|
183
|
+
source_path,
|
|
184
|
+
max_bytes=max_bytes,
|
|
185
|
+
)
|
|
186
|
+
except EvidenceBundleValidationError as error:
|
|
187
|
+
raise EvidenceBundleBuildError(str(error)) from error
|
|
188
|
+
return cls(
|
|
189
|
+
path=path,
|
|
190
|
+
content=content,
|
|
191
|
+
media_type=media_type,
|
|
192
|
+
role=role,
|
|
193
|
+
record_ref=record_ref,
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _open_regular_file(path: Path) -> tuple[int, os.stat_result]:
|
|
198
|
+
try:
|
|
199
|
+
metadata = path.lstat()
|
|
200
|
+
except OSError as error:
|
|
201
|
+
raise EvidenceBundleValidationError(
|
|
202
|
+
f"{path}: cannot inspect regular file: {error}"
|
|
203
|
+
) from error
|
|
204
|
+
if not stat.S_ISREG(metadata.st_mode):
|
|
205
|
+
raise EvidenceBundleValidationError(
|
|
206
|
+
f"{path}: expected a regular non-symlink file"
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
flags = os.O_RDONLY | getattr(os, "O_BINARY", 0)
|
|
210
|
+
flags |= getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0)
|
|
211
|
+
try:
|
|
212
|
+
descriptor = os.open(path, flags)
|
|
213
|
+
except OSError as error:
|
|
214
|
+
raise EvidenceBundleValidationError(
|
|
215
|
+
f"{path}: cannot open regular file: {error}"
|
|
216
|
+
) from error
|
|
217
|
+
try:
|
|
218
|
+
opened_metadata = os.fstat(descriptor)
|
|
219
|
+
if not stat.S_ISREG(opened_metadata.st_mode) or (
|
|
220
|
+
opened_metadata.st_dev,
|
|
221
|
+
opened_metadata.st_ino,
|
|
222
|
+
) != (metadata.st_dev, metadata.st_ino):
|
|
223
|
+
raise EvidenceBundleValidationError(f"{path}: file changed while opening")
|
|
224
|
+
except BaseException:
|
|
225
|
+
os.close(descriptor)
|
|
226
|
+
raise
|
|
227
|
+
return descriptor, opened_metadata
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _read_bounded_regular_file(path: Path, *, max_bytes: int) -> bytes:
|
|
231
|
+
descriptor, metadata = _open_regular_file(path)
|
|
232
|
+
if metadata.st_size > max_bytes:
|
|
233
|
+
os.close(descriptor)
|
|
234
|
+
raise EvidenceBundleValidationError(
|
|
235
|
+
f"{path}: file size {metadata.st_size} exceeds limit {max_bytes}"
|
|
236
|
+
)
|
|
237
|
+
with os.fdopen(descriptor, "rb") as handle:
|
|
238
|
+
content = handle.read(max_bytes + 1)
|
|
239
|
+
final_size = os.fstat(handle.fileno()).st_size
|
|
240
|
+
if len(content) > max_bytes:
|
|
241
|
+
raise EvidenceBundleValidationError(
|
|
242
|
+
f"{path}: file exceeds limit {max_bytes} while reading"
|
|
243
|
+
)
|
|
244
|
+
if len(content) != metadata.st_size or final_size != metadata.st_size:
|
|
245
|
+
raise EvidenceBundleValidationError(f"{path}: file changed while reading")
|
|
246
|
+
return content
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _digest_bounded_regular_file(
|
|
250
|
+
path: Path,
|
|
251
|
+
*,
|
|
252
|
+
display_path: str,
|
|
253
|
+
expected_size: int,
|
|
254
|
+
max_bytes: int,
|
|
255
|
+
) -> str:
|
|
256
|
+
descriptor, metadata = _open_regular_file(path)
|
|
257
|
+
if metadata.st_size > max_bytes:
|
|
258
|
+
os.close(descriptor)
|
|
259
|
+
raise EvidenceBundleValidationError(
|
|
260
|
+
f"{path}: file size {metadata.st_size} exceeds limit {max_bytes}"
|
|
261
|
+
)
|
|
262
|
+
if metadata.st_size != expected_size:
|
|
263
|
+
os.close(descriptor)
|
|
264
|
+
raise EvidenceBundleValidationError(
|
|
265
|
+
f"bundle inventory size mismatch for {display_path!r}"
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
digest = hashlib.sha256()
|
|
269
|
+
observed_size = 0
|
|
270
|
+
with os.fdopen(descriptor, "rb") as handle:
|
|
271
|
+
while chunk := handle.read(_DIGEST_CHUNK_BYTES):
|
|
272
|
+
observed_size += len(chunk)
|
|
273
|
+
if observed_size > max_bytes:
|
|
274
|
+
raise EvidenceBundleValidationError(
|
|
275
|
+
f"{path}: file exceeds limit {max_bytes} while hashing"
|
|
276
|
+
)
|
|
277
|
+
digest.update(chunk)
|
|
278
|
+
final_size = os.fstat(handle.fileno()).st_size
|
|
279
|
+
if observed_size != expected_size or final_size != expected_size:
|
|
280
|
+
raise EvidenceBundleValidationError(f"{path}: file changed while hashing")
|
|
281
|
+
return digest.hexdigest()
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _load_json_object(path: Path, *, max_bytes: int) -> JsonObject:
|
|
285
|
+
content = _read_bounded_regular_file(path, max_bytes=max_bytes)
|
|
286
|
+
try:
|
|
287
|
+
value = strict_json_loads(content)
|
|
288
|
+
except (UnicodeError, json.JSONDecodeError, ValueError) as error:
|
|
289
|
+
raise EvidenceBundleValidationError(
|
|
290
|
+
f"{path}: cannot load one strict JSON object: {error}"
|
|
291
|
+
) from error
|
|
292
|
+
if not isinstance(value, dict):
|
|
293
|
+
raise EvidenceBundleValidationError(f"{path}: expected one JSON object")
|
|
294
|
+
return value
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _object(value: JsonValue, field_name: str) -> JsonObject:
|
|
298
|
+
if not isinstance(value, dict):
|
|
299
|
+
raise TypeError(f"schema-valid field {field_name!r} was not an object")
|
|
300
|
+
return value
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _objects(value: JsonValue, field_name: str) -> tuple[JsonObject, ...]:
|
|
304
|
+
if not isinstance(value, list) or not all(isinstance(item, dict) for item in value):
|
|
305
|
+
raise TypeError(f"schema-valid field {field_name!r} was not an object array")
|
|
306
|
+
return tuple(cast(JsonObject, item) for item in value)
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def _string(value: JsonValue, field_name: str) -> str:
|
|
310
|
+
if not isinstance(value, str):
|
|
311
|
+
raise TypeError(f"schema-valid field {field_name!r} was not a string")
|
|
312
|
+
return value
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def _integer(value: JsonValue, field_name: str) -> int:
|
|
316
|
+
if isinstance(value, bool) or not isinstance(value, int):
|
|
317
|
+
raise TypeError(f"schema-valid field {field_name!r} was not an integer")
|
|
318
|
+
return value
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def _file_byte_limit(limits: EvidenceBundleLimits, role: str) -> int:
|
|
322
|
+
limit = limits.max_file_bytes
|
|
323
|
+
if role == "ledger":
|
|
324
|
+
limit = min(limit, limits.max_ledger_bytes)
|
|
325
|
+
elif role == "reasoning_receipt":
|
|
326
|
+
limit = min(limit, limits.max_receipt_bytes)
|
|
327
|
+
return limit
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def _sha256(value: bytes) -> str:
|
|
331
|
+
return hashlib.sha256(value).hexdigest()
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def _pretty_json(value: JsonValue) -> bytes:
|
|
335
|
+
return (
|
|
336
|
+
json.dumps(
|
|
337
|
+
value,
|
|
338
|
+
allow_nan=False,
|
|
339
|
+
ensure_ascii=False,
|
|
340
|
+
indent=2,
|
|
341
|
+
sort_keys=True,
|
|
342
|
+
)
|
|
343
|
+
+ "\n"
|
|
344
|
+
).encode("utf-8")
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def _timestamp(value: datetime) -> str:
|
|
348
|
+
if value.tzinfo is None or value.utcoffset() is None:
|
|
349
|
+
raise EvidenceBundleBuildError("bundle created_at must be timezone-aware")
|
|
350
|
+
return value.astimezone(UTC).isoformat().replace("+00:00", "Z")
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def _write_file(root: Path, relative: str, content: bytes) -> None:
|
|
354
|
+
path = root.joinpath(*parse_bundle_path(relative).parts)
|
|
355
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
356
|
+
write_file_exclusive(
|
|
357
|
+
path,
|
|
358
|
+
content,
|
|
359
|
+
mode=stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH,
|
|
360
|
+
)
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def _inventory_entry(
|
|
364
|
+
*,
|
|
365
|
+
path: str,
|
|
366
|
+
role: str,
|
|
367
|
+
media_type: str,
|
|
368
|
+
content: bytes,
|
|
369
|
+
record_ref: str | None = None,
|
|
370
|
+
) -> JsonObject:
|
|
371
|
+
entry: JsonObject = {
|
|
372
|
+
"path": path,
|
|
373
|
+
"role": role,
|
|
374
|
+
"media_type": media_type,
|
|
375
|
+
"size_bytes": len(content),
|
|
376
|
+
"digest": {
|
|
377
|
+
"algorithm": "sha256",
|
|
378
|
+
"value": _sha256(content),
|
|
379
|
+
},
|
|
380
|
+
}
|
|
381
|
+
if record_ref is not None:
|
|
382
|
+
entry["record_ref"] = record_ref
|
|
383
|
+
return entry
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def canonical_bundle_json(value: JsonValue) -> bytes:
|
|
387
|
+
"""Return the deterministic JSON representation used for bundle identity."""
|
|
388
|
+
|
|
389
|
+
return json.dumps(
|
|
390
|
+
value,
|
|
391
|
+
allow_nan=False,
|
|
392
|
+
ensure_ascii=False,
|
|
393
|
+
separators=(",", ":"),
|
|
394
|
+
sort_keys=True,
|
|
395
|
+
).encode("utf-8")
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def evidence_bundle_id(manifest_without_id: JsonObject) -> str:
|
|
399
|
+
"""Derive the bundle identifier from metadata and the complete inventory."""
|
|
400
|
+
|
|
401
|
+
if "bundle_id" in manifest_without_id:
|
|
402
|
+
raise ValueError("manifest_without_id must not contain bundle_id")
|
|
403
|
+
return f"urn:sha256:{_sha256(canonical_bundle_json(manifest_without_id))}"
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def parse_bundle_path(value: str) -> PurePosixPath:
|
|
407
|
+
"""Parse one normalized, relative evidence-bundle path."""
|
|
408
|
+
|
|
409
|
+
candidate = PurePosixPath(value)
|
|
410
|
+
if (
|
|
411
|
+
not value
|
|
412
|
+
or value.startswith("/")
|
|
413
|
+
or "\\" in value
|
|
414
|
+
or ":" in value
|
|
415
|
+
or candidate.is_absolute()
|
|
416
|
+
or any(part in {"", ".", ".."} for part in value.split("/"))
|
|
417
|
+
):
|
|
418
|
+
raise EvidenceBundleValidationError(
|
|
419
|
+
f"bundle file path {value!r} is not a normalized relative path"
|
|
420
|
+
)
|
|
421
|
+
return candidate
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
@dataclass(frozen=True, slots=True)
|
|
425
|
+
class VerifiedEvidenceBundle:
|
|
426
|
+
"""Validated bundle projections safe for downstream inspection."""
|
|
427
|
+
|
|
428
|
+
path: Path
|
|
429
|
+
manifest: JsonObject
|
|
430
|
+
ledger: Ledger
|
|
431
|
+
receipt: JsonObject
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
def _actual_file_paths(root: Path, limits: EvidenceBundleLimits) -> set[str]:
|
|
435
|
+
actual_paths: set[str] = set()
|
|
436
|
+
pending = [root]
|
|
437
|
+
entry_count = 0
|
|
438
|
+
while pending:
|
|
439
|
+
directory = pending.pop()
|
|
440
|
+
try:
|
|
441
|
+
with os.scandir(directory) as descendants:
|
|
442
|
+
for descendant in descendants:
|
|
443
|
+
entry_count += 1
|
|
444
|
+
if entry_count > limits.max_directory_entries:
|
|
445
|
+
raise EvidenceBundleValidationError(
|
|
446
|
+
"bundle directory entry count exceeds limit "
|
|
447
|
+
f"{limits.max_directory_entries}"
|
|
448
|
+
)
|
|
449
|
+
relative = Path(descendant.path).relative_to(root).as_posix()
|
|
450
|
+
if descendant.is_symlink():
|
|
451
|
+
raise EvidenceBundleValidationError(
|
|
452
|
+
f"bundle must not contain symbolic link {relative!r}"
|
|
453
|
+
)
|
|
454
|
+
if descendant.is_dir(follow_symlinks=False):
|
|
455
|
+
pending.append(Path(descendant.path))
|
|
456
|
+
elif descendant.is_file(follow_symlinks=False):
|
|
457
|
+
actual_paths.add(relative)
|
|
458
|
+
else:
|
|
459
|
+
raise EvidenceBundleValidationError(
|
|
460
|
+
f"bundle contains non-regular entry {relative!r}"
|
|
461
|
+
)
|
|
462
|
+
except EvidenceBundleValidationError:
|
|
463
|
+
raise
|
|
464
|
+
except OSError as error:
|
|
465
|
+
raise EvidenceBundleValidationError(
|
|
466
|
+
f"{directory}: cannot inspect bundle directory: {error}"
|
|
467
|
+
) from error
|
|
468
|
+
return actual_paths
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
def _validate_inventory(
|
|
472
|
+
root: Path,
|
|
473
|
+
entries: tuple[JsonObject, ...],
|
|
474
|
+
limits: EvidenceBundleLimits,
|
|
475
|
+
) -> None:
|
|
476
|
+
"""Check the exact file set and every inventoried size and digest."""
|
|
477
|
+
|
|
478
|
+
if len(entries) > limits.max_files:
|
|
479
|
+
raise EvidenceBundleValidationError(
|
|
480
|
+
f"bundle file count {len(entries)} exceeds limit {limits.max_files}"
|
|
481
|
+
)
|
|
482
|
+
entry_paths = tuple(_string(entry["path"], "path") for entry in entries)
|
|
483
|
+
if len(entry_paths) != len(set(entry_paths)):
|
|
484
|
+
raise EvidenceBundleValidationError(
|
|
485
|
+
"bundle file inventory contains duplicate paths"
|
|
486
|
+
)
|
|
487
|
+
|
|
488
|
+
declared_total = 0
|
|
489
|
+
for entry in entries:
|
|
490
|
+
relative = _string(entry["path"], "path")
|
|
491
|
+
declared_size = entry["size_bytes"]
|
|
492
|
+
# The schema's "integer" also admits 3302.0, which canonical_bundle_json
|
|
493
|
+
# would hash differently from the integer 3302.
|
|
494
|
+
if isinstance(declared_size, bool) or not isinstance(declared_size, int):
|
|
495
|
+
raise EvidenceBundleValidationError(
|
|
496
|
+
f"bundle inventory file {relative!r} must write size_bytes as an "
|
|
497
|
+
f"integer literal, not {declared_size!r}"
|
|
498
|
+
)
|
|
499
|
+
byte_limit = _file_byte_limit(limits, _string(entry["role"], "role"))
|
|
500
|
+
if declared_size > byte_limit:
|
|
501
|
+
raise EvidenceBundleValidationError(
|
|
502
|
+
f"bundle inventory file {relative!r} declares {declared_size} "
|
|
503
|
+
f"bytes, exceeding limit {byte_limit}"
|
|
504
|
+
)
|
|
505
|
+
declared_total += declared_size
|
|
506
|
+
if declared_total > limits.max_total_bytes:
|
|
507
|
+
raise EvidenceBundleValidationError(
|
|
508
|
+
f"bundle inventoried byte total exceeds limit {limits.max_total_bytes}"
|
|
509
|
+
)
|
|
510
|
+
|
|
511
|
+
root_resolved = root.resolve()
|
|
512
|
+
for entry, relative in zip(entries, entry_paths, strict=True):
|
|
513
|
+
relative_path = parse_bundle_path(relative)
|
|
514
|
+
candidate = root.joinpath(*relative_path.parts)
|
|
515
|
+
# A manifest path can make these probes fail, for example with a name
|
|
516
|
+
# longer than NAME_MAX; Path.resolve raises RuntimeError on a symlink
|
|
517
|
+
# loop before Python 3.13.
|
|
518
|
+
try:
|
|
519
|
+
regular = not candidate.is_symlink() and candidate.is_file()
|
|
520
|
+
resolved = candidate.resolve() if regular else None
|
|
521
|
+
except (OSError, RuntimeError) as error:
|
|
522
|
+
raise EvidenceBundleValidationError(
|
|
523
|
+
f"bundle inventory file {relative!r} cannot be inspected: {error}"
|
|
524
|
+
) from error
|
|
525
|
+
if resolved is None:
|
|
526
|
+
raise EvidenceBundleValidationError(
|
|
527
|
+
f"bundle inventory file {relative!r} is missing or not regular"
|
|
528
|
+
)
|
|
529
|
+
if not resolved.is_relative_to(root_resolved):
|
|
530
|
+
raise EvidenceBundleValidationError(
|
|
531
|
+
f"bundle inventory file {relative!r} escapes the bundle root"
|
|
532
|
+
)
|
|
533
|
+
observed_digest = _digest_bounded_regular_file(
|
|
534
|
+
candidate,
|
|
535
|
+
display_path=relative,
|
|
536
|
+
expected_size=_integer(entry["size_bytes"], "size_bytes"),
|
|
537
|
+
max_bytes=_file_byte_limit(limits, _string(entry["role"], "role")),
|
|
538
|
+
)
|
|
539
|
+
digest = _object(entry["digest"], "digest")
|
|
540
|
+
if _string(digest["value"], "digest.value") != observed_digest:
|
|
541
|
+
raise EvidenceBundleValidationError(
|
|
542
|
+
f"bundle inventory digest mismatch for {relative!r}"
|
|
543
|
+
)
|
|
544
|
+
|
|
545
|
+
actual_paths = _actual_file_paths(root, limits)
|
|
546
|
+
expected_paths = set(entry_paths) | {BUNDLE_MANIFEST_NAME}
|
|
547
|
+
if actual_paths != expected_paths:
|
|
548
|
+
missing = sorted(expected_paths.difference(actual_paths))
|
|
549
|
+
extra = sorted(actual_paths.difference(expected_paths))
|
|
550
|
+
raise EvidenceBundleValidationError(
|
|
551
|
+
f"bundle file inventory mismatch; missing={missing}, extra={extra}"
|
|
552
|
+
)
|
|
553
|
+
|
|
554
|
+
|
|
555
|
+
def _read_inventoried_file(
|
|
556
|
+
root: Path,
|
|
557
|
+
entry: JsonObject,
|
|
558
|
+
limits: EvidenceBundleLimits,
|
|
559
|
+
) -> tuple[Path, bytes]:
|
|
560
|
+
"""Read one inventoried file once and return the bytes its entry binds."""
|
|
561
|
+
|
|
562
|
+
relative = _string(entry["path"], "path")
|
|
563
|
+
path = root.joinpath(*parse_bundle_path(relative).parts)
|
|
564
|
+
content = _read_bounded_regular_file(
|
|
565
|
+
path,
|
|
566
|
+
max_bytes=_file_byte_limit(limits, _string(entry["role"], "role")),
|
|
567
|
+
)
|
|
568
|
+
if len(content) != _integer(entry["size_bytes"], "size_bytes"):
|
|
569
|
+
raise EvidenceBundleValidationError(
|
|
570
|
+
f"bundle inventory size mismatch for {relative!r}"
|
|
571
|
+
)
|
|
572
|
+
digest = _object(entry["digest"], "digest")
|
|
573
|
+
if _sha256(content) != _string(digest["value"], "digest.value"):
|
|
574
|
+
raise EvidenceBundleValidationError(
|
|
575
|
+
f"bundle inventory digest mismatch for {relative!r}"
|
|
576
|
+
)
|
|
577
|
+
return path, content
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
@dataclass(frozen=True, slots=True)
|
|
581
|
+
class EvidenceBundleValidator:
|
|
582
|
+
"""Verify inventory, bytes, protocol history, receipt, and artifacts.
|
|
583
|
+
|
|
584
|
+
``trusted_authorizers`` has the meaning it has for ``BundleValidator``: when
|
|
585
|
+
set, only those actor ids may authorize the ledger's evidence-backed
|
|
586
|
+
transitions.
|
|
587
|
+
"""
|
|
588
|
+
|
|
589
|
+
limits: EvidenceBundleLimits = field(default_factory=EvidenceBundleLimits)
|
|
590
|
+
trusted_authorizers: Collection[str] | None = None
|
|
591
|
+
|
|
592
|
+
def __post_init__(self) -> None:
|
|
593
|
+
object.__setattr__(
|
|
594
|
+
self,
|
|
595
|
+
"trusted_authorizers",
|
|
596
|
+
BundleValidator(
|
|
597
|
+
trusted_authorizers=self.trusted_authorizers
|
|
598
|
+
).trusted_authorizers,
|
|
599
|
+
)
|
|
600
|
+
|
|
601
|
+
def _schema_validator(self) -> _SchemaValidator:
|
|
602
|
+
schema_resource = files("itself").joinpath(
|
|
603
|
+
"schemas",
|
|
604
|
+
"v0alpha2",
|
|
605
|
+
"evidence-bundle.schema.json",
|
|
606
|
+
)
|
|
607
|
+
schema = cast(
|
|
608
|
+
JsonObject,
|
|
609
|
+
strict_json_loads(schema_resource.read_text(encoding="utf-8")),
|
|
610
|
+
)
|
|
611
|
+
Draft202012Validator.check_schema(schema)
|
|
612
|
+
return cast(
|
|
613
|
+
_SchemaValidator,
|
|
614
|
+
Draft202012Validator(schema, format_checker=schema_format_checker()),
|
|
615
|
+
)
|
|
616
|
+
|
|
617
|
+
def errors(self, manifest: JsonValue) -> list[str]:
|
|
618
|
+
"""Return stable, human-readable manifest schema errors."""
|
|
619
|
+
|
|
620
|
+
issues = sorted(
|
|
621
|
+
self._schema_validator().iter_errors(manifest),
|
|
622
|
+
key=lambda error: tuple(str(item) for item in error.absolute_path),
|
|
623
|
+
)
|
|
624
|
+
return [
|
|
625
|
+
f"{_format_path(tuple(issue.absolute_path))}: {issue.message}"
|
|
626
|
+
for issue in issues
|
|
627
|
+
]
|
|
628
|
+
|
|
629
|
+
def validate_manifest(self, manifest: JsonValue) -> None:
|
|
630
|
+
"""Validate one evidence-bundle manifest."""
|
|
631
|
+
|
|
632
|
+
issues = self.errors(manifest)
|
|
633
|
+
if issues:
|
|
634
|
+
raise EvidenceBundleValidationError("\n".join(issues))
|
|
635
|
+
|
|
636
|
+
@staticmethod
|
|
637
|
+
def _single_role(
|
|
638
|
+
entries: tuple[JsonObject, ...],
|
|
639
|
+
role: str,
|
|
640
|
+
) -> JsonObject:
|
|
641
|
+
matches = tuple(entry for entry in entries if entry["role"] == role)
|
|
642
|
+
if len(matches) != 1:
|
|
643
|
+
raise EvidenceBundleValidationError(
|
|
644
|
+
f"bundle must inventory exactly one {role!r} file"
|
|
645
|
+
)
|
|
646
|
+
return matches[0]
|
|
647
|
+
|
|
648
|
+
@staticmethod
|
|
649
|
+
def _validate_artifacts(
|
|
650
|
+
ledger: Ledger,
|
|
651
|
+
entries: tuple[JsonObject, ...],
|
|
652
|
+
) -> None:
|
|
653
|
+
artifact_entries = {
|
|
654
|
+
_string(entry["record_ref"], "record_ref"): entry
|
|
655
|
+
for entry in entries
|
|
656
|
+
if entry["role"] == "artifact"
|
|
657
|
+
}
|
|
658
|
+
if len(artifact_entries) != sum(
|
|
659
|
+
entry["role"] == "artifact" for entry in entries
|
|
660
|
+
):
|
|
661
|
+
raise EvidenceBundleValidationError(
|
|
662
|
+
"bundle artifact inventory contains duplicate record_ref values"
|
|
663
|
+
)
|
|
664
|
+
|
|
665
|
+
artifact_records = {
|
|
666
|
+
_string(record["id"], "id"): record
|
|
667
|
+
for record in ledger.records
|
|
668
|
+
if record["kind"] == "artifact_reference"
|
|
669
|
+
}
|
|
670
|
+
if set(artifact_entries) != set(artifact_records):
|
|
671
|
+
raise EvidenceBundleValidationError(
|
|
672
|
+
"closed bundle must materialize every ledger artifact exactly once"
|
|
673
|
+
)
|
|
674
|
+
for record_id, record in artifact_records.items():
|
|
675
|
+
entry = artifact_entries[record_id]
|
|
676
|
+
path = _string(entry["path"], "path")
|
|
677
|
+
if _string(record["uri"], "uri") != path:
|
|
678
|
+
raise EvidenceBundleValidationError(
|
|
679
|
+
f"artifact {record_id!r} URI does not match its inventory path"
|
|
680
|
+
)
|
|
681
|
+
if record["media_type"] != entry["media_type"]:
|
|
682
|
+
raise EvidenceBundleValidationError(
|
|
683
|
+
f"artifact {record_id!r} media type does not match its inventory"
|
|
684
|
+
)
|
|
685
|
+
record_digest_value = record.get("digest")
|
|
686
|
+
if not isinstance(record_digest_value, dict):
|
|
687
|
+
raise EvidenceBundleValidationError(
|
|
688
|
+
f"closed-bundle artifact {record_id!r} must declare a digest"
|
|
689
|
+
)
|
|
690
|
+
record_digest = record_digest_value
|
|
691
|
+
entry_digest = _object(entry["digest"], "digest")
|
|
692
|
+
if record_digest != entry_digest:
|
|
693
|
+
raise EvidenceBundleValidationError(
|
|
694
|
+
f"artifact {record_id!r} digest does not match its inventory"
|
|
695
|
+
)
|
|
696
|
+
|
|
697
|
+
def validate(self, path: StrPath) -> VerifiedEvidenceBundle:
|
|
698
|
+
"""Independently verify one closed evidence-bundle directory."""
|
|
699
|
+
|
|
700
|
+
root = Path(path)
|
|
701
|
+
if not root.is_dir() or root.is_symlink():
|
|
702
|
+
raise EvidenceBundleValidationError(
|
|
703
|
+
f"{root}: bundle root is not a directory"
|
|
704
|
+
)
|
|
705
|
+
manifest = _load_json_object(
|
|
706
|
+
root / BUNDLE_MANIFEST_NAME,
|
|
707
|
+
max_bytes=self.limits.max_manifest_bytes,
|
|
708
|
+
)
|
|
709
|
+
self.validate_manifest(manifest)
|
|
710
|
+
entries = _objects(manifest["files"], "files")
|
|
711
|
+
_validate_inventory(root, entries, self.limits)
|
|
712
|
+
|
|
713
|
+
identity = {
|
|
714
|
+
key: deepcopy(value)
|
|
715
|
+
for key, value in manifest.items()
|
|
716
|
+
if key != "bundle_id"
|
|
717
|
+
}
|
|
718
|
+
if manifest["bundle_id"] != evidence_bundle_id(identity):
|
|
719
|
+
raise EvidenceBundleValidationError(
|
|
720
|
+
"bundle_id does not bind the bundle metadata and file inventory"
|
|
721
|
+
)
|
|
722
|
+
|
|
723
|
+
ledger_entry = self._single_role(entries, "ledger")
|
|
724
|
+
receipt_entry = self._single_role(entries, "reasoning_receipt")
|
|
725
|
+
if ledger_entry["media_type"] != "application/x-ndjson":
|
|
726
|
+
raise EvidenceBundleValidationError(
|
|
727
|
+
"ledger file must use application/x-ndjson"
|
|
728
|
+
)
|
|
729
|
+
if receipt_entry["media_type"] != "application/json":
|
|
730
|
+
raise EvidenceBundleValidationError(
|
|
731
|
+
"reasoning receipt file must use application/json"
|
|
732
|
+
)
|
|
733
|
+
|
|
734
|
+
# Decode only bytes checked against the manifest in the same read, so a
|
|
735
|
+
# file replaced after the inventory pass fails here instead of parsing.
|
|
736
|
+
ledger_path, ledger_content = _read_inventoried_file(
|
|
737
|
+
root,
|
|
738
|
+
ledger_entry,
|
|
739
|
+
self.limits,
|
|
740
|
+
)
|
|
741
|
+
ledger = Ledger(
|
|
742
|
+
decode_jsonl_records(
|
|
743
|
+
ledger_content,
|
|
744
|
+
path=ledger_path,
|
|
745
|
+
max_records=self.limits.max_ledger_records,
|
|
746
|
+
max_bytes=_file_byte_limit(self.limits, "ledger"),
|
|
747
|
+
),
|
|
748
|
+
validator=BundleValidator(trusted_authorizers=self.trusted_authorizers),
|
|
749
|
+
)
|
|
750
|
+
receipt_path, receipt_content = _read_inventoried_file(
|
|
751
|
+
root,
|
|
752
|
+
receipt_entry,
|
|
753
|
+
self.limits,
|
|
754
|
+
)
|
|
755
|
+
receipt = decode_receipt_document(receipt_content, path=receipt_path)
|
|
756
|
+
ReasoningReceiptValidator().validate_against_ledger(receipt, ledger)
|
|
757
|
+
self._validate_artifacts(ledger, entries)
|
|
758
|
+
return VerifiedEvidenceBundle(
|
|
759
|
+
path=root,
|
|
760
|
+
manifest=deepcopy(manifest),
|
|
761
|
+
ledger=ledger,
|
|
762
|
+
receipt=deepcopy(receipt),
|
|
763
|
+
)
|
|
764
|
+
|
|
765
|
+
|
|
766
|
+
@dataclass(frozen=True, slots=True)
|
|
767
|
+
class EvidenceBundleBuilder:
|
|
768
|
+
"""Materialize, verify, and publish one immutable closed evidence bundle."""
|
|
769
|
+
|
|
770
|
+
validator: EvidenceBundleValidator = field(default_factory=EvidenceBundleValidator)
|
|
771
|
+
|
|
772
|
+
@staticmethod
|
|
773
|
+
def _validate_paths(
|
|
774
|
+
bundle_files: Sequence[EvidenceBundleFile],
|
|
775
|
+
) -> tuple[PurePosixPath, ...]:
|
|
776
|
+
paths = (
|
|
777
|
+
*(PurePosixPath(bundle_file.path) for bundle_file in bundle_files),
|
|
778
|
+
PurePosixPath(EVIDENCE_BUNDLE_LEDGER_PATH),
|
|
779
|
+
PurePosixPath(EVIDENCE_BUNDLE_RECEIPT_PATH),
|
|
780
|
+
PurePosixPath(BUNDLE_MANIFEST_NAME),
|
|
781
|
+
)
|
|
782
|
+
if len(paths) != len(set(paths)):
|
|
783
|
+
raise EvidenceBundleBuildError("bundle file paths must be unique")
|
|
784
|
+
for path in paths:
|
|
785
|
+
if any(parent in paths for parent in path.parents if parent.parts):
|
|
786
|
+
raise EvidenceBundleBuildError(
|
|
787
|
+
f"bundle file path {path.as_posix()!r} conflicts with a file parent"
|
|
788
|
+
)
|
|
789
|
+
return paths
|
|
790
|
+
|
|
791
|
+
def _validate_resources(
|
|
792
|
+
self,
|
|
793
|
+
*,
|
|
794
|
+
paths: tuple[PurePosixPath, ...],
|
|
795
|
+
bundle_files: tuple[EvidenceBundleFile, ...],
|
|
796
|
+
ledger: Ledger,
|
|
797
|
+
ledger_content: bytes,
|
|
798
|
+
receipt_content: bytes,
|
|
799
|
+
) -> None:
|
|
800
|
+
limits = self.validator.limits
|
|
801
|
+
inventoried_file_count = len(paths) - 1
|
|
802
|
+
if inventoried_file_count > limits.max_files:
|
|
803
|
+
raise EvidenceBundleBuildError(
|
|
804
|
+
f"bundle file count {inventoried_file_count} exceeds limit "
|
|
805
|
+
f"{limits.max_files}"
|
|
806
|
+
)
|
|
807
|
+
directories = {
|
|
808
|
+
parent for path in paths for parent in path.parents if parent.parts
|
|
809
|
+
}
|
|
810
|
+
directory_entries = len(paths) + len(directories)
|
|
811
|
+
if directory_entries > limits.max_directory_entries:
|
|
812
|
+
raise EvidenceBundleBuildError(
|
|
813
|
+
f"bundle directory entry count {directory_entries} exceeds limit "
|
|
814
|
+
f"{limits.max_directory_entries}"
|
|
815
|
+
)
|
|
816
|
+
if len(ledger) > limits.max_ledger_records:
|
|
817
|
+
raise EvidenceBundleBuildError(
|
|
818
|
+
f"ledger record count {len(ledger)} exceeds limit "
|
|
819
|
+
f"{limits.max_ledger_records}"
|
|
820
|
+
)
|
|
821
|
+
|
|
822
|
+
contents = (
|
|
823
|
+
*(
|
|
824
|
+
(
|
|
825
|
+
bundle_file.path,
|
|
826
|
+
bundle_file.role.value,
|
|
827
|
+
bundle_file.content,
|
|
828
|
+
)
|
|
829
|
+
for bundle_file in bundle_files
|
|
830
|
+
),
|
|
831
|
+
(EVIDENCE_BUNDLE_LEDGER_PATH, "ledger", ledger_content),
|
|
832
|
+
(
|
|
833
|
+
EVIDENCE_BUNDLE_RECEIPT_PATH,
|
|
834
|
+
"reasoning_receipt",
|
|
835
|
+
receipt_content,
|
|
836
|
+
),
|
|
837
|
+
)
|
|
838
|
+
total_bytes = 0
|
|
839
|
+
for relative, role, content in contents:
|
|
840
|
+
byte_limit = _file_byte_limit(limits, role)
|
|
841
|
+
if len(content) > byte_limit:
|
|
842
|
+
raise EvidenceBundleBuildError(
|
|
843
|
+
f"bundle file {relative!r} has {len(content)} bytes, "
|
|
844
|
+
f"exceeding limit {byte_limit}"
|
|
845
|
+
)
|
|
846
|
+
total_bytes += len(content)
|
|
847
|
+
if total_bytes > limits.max_total_bytes:
|
|
848
|
+
raise EvidenceBundleBuildError(
|
|
849
|
+
f"bundle byte total exceeds limit {limits.max_total_bytes}"
|
|
850
|
+
)
|
|
851
|
+
|
|
852
|
+
def build(
|
|
853
|
+
self,
|
|
854
|
+
destination: StrPath,
|
|
855
|
+
*,
|
|
856
|
+
ledger: Ledger,
|
|
857
|
+
title: str,
|
|
858
|
+
files: Sequence[EvidenceBundleFile],
|
|
859
|
+
created_at: datetime | None = None,
|
|
860
|
+
limitations: Sequence[str] = DEFAULT_EVIDENCE_BUNDLE_LIMITATIONS,
|
|
861
|
+
) -> VerifiedEvidenceBundle:
|
|
862
|
+
"""Build into a private sibling directory and publish without overwriting."""
|
|
863
|
+
|
|
864
|
+
target = Path(destination)
|
|
865
|
+
if target.exists() or target.is_symlink():
|
|
866
|
+
raise FileExistsError(target)
|
|
867
|
+
|
|
868
|
+
bundle_files = tuple(files)
|
|
869
|
+
if not all(
|
|
870
|
+
isinstance(cast(object, item), EvidenceBundleFile) for item in bundle_files
|
|
871
|
+
):
|
|
872
|
+
raise TypeError("files must contain only EvidenceBundleFile values")
|
|
873
|
+
paths = self._validate_paths(bundle_files)
|
|
874
|
+
|
|
875
|
+
ledger_content = canonical_ledger_bytes(ledger)
|
|
876
|
+
receipt = build_reasoning_receipt(ledger)
|
|
877
|
+
receipt_content = _pretty_json(receipt)
|
|
878
|
+
self._validate_resources(
|
|
879
|
+
paths=paths,
|
|
880
|
+
bundle_files=bundle_files,
|
|
881
|
+
ledger=ledger,
|
|
882
|
+
ledger_content=ledger_content,
|
|
883
|
+
receipt_content=receipt_content,
|
|
884
|
+
)
|
|
885
|
+
entries = [
|
|
886
|
+
_inventory_entry(
|
|
887
|
+
path=bundle_file.path,
|
|
888
|
+
role=bundle_file.role.value,
|
|
889
|
+
media_type=bundle_file.media_type,
|
|
890
|
+
content=bundle_file.content,
|
|
891
|
+
record_ref=bundle_file.record_ref,
|
|
892
|
+
)
|
|
893
|
+
for bundle_file in bundle_files
|
|
894
|
+
]
|
|
895
|
+
entries.extend(
|
|
896
|
+
(
|
|
897
|
+
_inventory_entry(
|
|
898
|
+
path=EVIDENCE_BUNDLE_LEDGER_PATH,
|
|
899
|
+
role="ledger",
|
|
900
|
+
media_type="application/x-ndjson",
|
|
901
|
+
content=ledger_content,
|
|
902
|
+
),
|
|
903
|
+
_inventory_entry(
|
|
904
|
+
path=EVIDENCE_BUNDLE_RECEIPT_PATH,
|
|
905
|
+
role="reasoning_receipt",
|
|
906
|
+
media_type="application/json",
|
|
907
|
+
content=receipt_content,
|
|
908
|
+
),
|
|
909
|
+
)
|
|
910
|
+
)
|
|
911
|
+
manifest_files: list[JsonValue] = [entry for entry in entries]
|
|
912
|
+
manifest_limitations: list[JsonValue] = [item for item in limitations]
|
|
913
|
+
manifest_without_id: JsonObject = {
|
|
914
|
+
"bundle_version": EVIDENCE_BUNDLE_VERSION,
|
|
915
|
+
"title": title,
|
|
916
|
+
"created_at": _timestamp(created_at or datetime.now(UTC)),
|
|
917
|
+
"closed_artifacts": True,
|
|
918
|
+
"files": manifest_files,
|
|
919
|
+
"limitations": manifest_limitations,
|
|
920
|
+
}
|
|
921
|
+
manifest: JsonObject = {
|
|
922
|
+
"bundle_id": evidence_bundle_id(manifest_without_id),
|
|
923
|
+
**manifest_without_id,
|
|
924
|
+
}
|
|
925
|
+
self.validator.validate_manifest(manifest)
|
|
926
|
+
manifest_content = _pretty_json(manifest)
|
|
927
|
+
if len(manifest_content) > self.validator.limits.max_manifest_bytes:
|
|
928
|
+
raise EvidenceBundleBuildError(
|
|
929
|
+
f"bundle manifest has {len(manifest_content)} bytes, exceeding limit "
|
|
930
|
+
f"{self.validator.limits.max_manifest_bytes}"
|
|
931
|
+
)
|
|
932
|
+
|
|
933
|
+
parent = target.parent
|
|
934
|
+
parent.mkdir(parents=True, exist_ok=True)
|
|
935
|
+
staging = Path(
|
|
936
|
+
tempfile.mkdtemp(
|
|
937
|
+
dir=parent,
|
|
938
|
+
prefix=f".{target.name}.",
|
|
939
|
+
)
|
|
940
|
+
)
|
|
941
|
+
staging.chmod(stat.S_IRWXU)
|
|
942
|
+
published = False
|
|
943
|
+
try:
|
|
944
|
+
for bundle_file in bundle_files:
|
|
945
|
+
_write_file(staging, bundle_file.path, bundle_file.content)
|
|
946
|
+
_write_file(staging, EVIDENCE_BUNDLE_LEDGER_PATH, ledger_content)
|
|
947
|
+
_write_file(staging, EVIDENCE_BUNDLE_RECEIPT_PATH, receipt_content)
|
|
948
|
+
_write_file(staging, BUNDLE_MANIFEST_NAME, manifest_content)
|
|
949
|
+
verified = self.validator.validate(staging)
|
|
950
|
+
if verified.manifest["bundle_id"] != manifest["bundle_id"]:
|
|
951
|
+
raise EvidenceBundleBuildError(
|
|
952
|
+
f"{staging}: staging directory changed before verification"
|
|
953
|
+
)
|
|
954
|
+
|
|
955
|
+
publish_path_no_replace(staging, target)
|
|
956
|
+
published = True
|
|
957
|
+
# Full validation ran once, on staging, and saw the manifest written
|
|
958
|
+
# above. Its result depends only on the file set and the file bytes,
|
|
959
|
+
# so re-checking the published inventory digests and manifest bytes
|
|
960
|
+
# proves the target is what was validated without parsing it again.
|
|
961
|
+
try:
|
|
962
|
+
_validate_inventory(target, tuple(entries), self.validator.limits)
|
|
963
|
+
published_manifest = _read_bounded_regular_file(
|
|
964
|
+
target / BUNDLE_MANIFEST_NAME,
|
|
965
|
+
max_bytes=self.validator.limits.max_manifest_bytes,
|
|
966
|
+
)
|
|
967
|
+
if published_manifest != manifest_content:
|
|
968
|
+
raise EvidenceBundleValidationError(
|
|
969
|
+
f"{target}: published manifest differs from the verified "
|
|
970
|
+
"manifest"
|
|
971
|
+
)
|
|
972
|
+
except BaseException:
|
|
973
|
+
# A bundle that changed after verification must not stay where
|
|
974
|
+
# a reader would take it for the verified one.
|
|
975
|
+
with suppress(OSError):
|
|
976
|
+
shutil.rmtree(target)
|
|
977
|
+
raise
|
|
978
|
+
return replace(verified, path=target)
|
|
979
|
+
finally:
|
|
980
|
+
if not published and staging.exists():
|
|
981
|
+
shutil.rmtree(staging)
|