Files
rpki/scripts/experiments/reuse_eval/replay_bundle.py

208 lines
10 KiB
Python

#!/usr/bin/env python3
"""Preserve/verify the consumed replay subset without rewriting capture bytes.
The manifest is deliberately a workload subset, not a full archive closure.
Export and stream read originals only. Extraction accepts regular manifest files
only, verifies each SHA256, and refuses to overwrite differing local contents.
"""
from __future__ import annotations
import argparse
import json
from pathlib import Path, PurePosixPath
import shutil
import sys
import tarfile
from common import atomic_json, file_sha256, read_json
SCHEMA = "rpki-consumed-replay-bundle-v1"
def safe_path(root: Path, relative: str) -> Path:
parts = PurePosixPath(relative)
if parts.is_absolute() or not parts.parts or any(p in (".", "..") for p in parts.parts):
raise ValueError("unsafe bundle path")
path = root / relative
if not path.resolve().is_relative_to(root.resolve()):
raise ValueError("bundle path escapes root")
return path
def load_manifest(path: Path, expected_sha256: str | None = None) -> dict:
if expected_sha256 is not None and file_sha256(path) != expected_sha256:
raise ValueError("bundle manifest SHA256 mismatch")
manifest = read_json(path)
if manifest.get("schema") != SCHEMA or manifest.get("full_archive_closure") is not False:
raise ValueError("unsupported bundle manifest")
files = manifest["files"]
if len({f["path"] for f in files}) != len(files):
raise ValueError("duplicate bundle file")
for row in files:
safe_path(path.parent, row["path"])
if (len(row["sha256"]) != 64 or any(c not in "0123456789abcdef" for c in row["sha256"])
or type(row["bytes"]) is not int or row["bytes"] < 0):
raise ValueError("invalid bundle file binding")
return manifest
def export_manifest(archive: Path, scope: Path, inventory_path: Path, origin_manifest: Path) -> dict:
from scope import require_closure
selected = require_closure(archive, scope)
inventory = read_json(inventory_path)
if inventory["scope_sha256"] != file_sha256(scope):
raise ValueError("inventory scope mismatch")
sources = {}
def add(path: str, source: Path, sha: str | None = None, size: int | None = None):
stat = source.stat()
actual = file_sha256(source) # Also hash the large original payloads.
if (sha is not None and actual != sha) or (size is not None and stat.st_size != size):
raise ValueError(f"original content changed: {path}")
row = {"path": path, "source": str(source.resolve()), "sha256": actual, "bytes": stat.st_size}
if path in sources and sources[path] != row:
raise ValueError("conflicting bundle source")
sources[path] = row
for name in ("contract.json", "capture.json", "registry.json", "closure-report.json"):
add("archive/" + name, archive / name)
add("config/scope.json", scope)
add("config/scoped-closure-report.json", scope.with_name("scoped-closure-report.json"))
add("provenance/actual_replay_payloads.json", inventory_path)
original = read_json(origin_manifest)
if original["scope_sha256"] != file_sha256(scope) or original["epoch"] != selected["epochs"][0]["sha256"]:
raise ValueError("original server mapping is not bound to this scope")
add("provenance/origin-replay-manifest.json", origin_manifest)
epochs = []
observations, events = set(), set()
for step, selection in enumerate(selected["epochs"]):
add("archive/" + selection["path"], archive / selection["path"], selection["sha256"])
epoch = read_json(archive / selection["path"])
observations.update(binding["id"] for binding in epoch["repositories"].values())
events.update(epoch["ta_object_events"].values())
events.update(epoch["rsync_view_events"].values())
allowed = [r for r in inventory["payload_inventory"]
if step in r["steps"] and r["kind"] not in ("tal", "rsync")]
epochs.append({**selection, "step": step, "http_entities": allowed,
"expected_transport": inventory["per_step"][step]})
for name in sorted(observations):
add(f"archive/observations/{name}.json", archive / "observations" / f"{name}.json")
for name in sorted(events):
add(f"archive/events/{name}.json", archive / "events" / f"{name}.json")
for row in inventory["payload_inventory"]:
sha = row["sha256"]
relative = "inputs/" + row["uri"] if row["kind"] == "tal" else f"blobs/sha256/{sha[:2]}/{sha}"
if "archive/" + relative not in sources:
add("archive/" + relative, archive / relative, sha, row["bytes"])
return {"schema": SCHEMA, "full_archive_closure": False,
"description": "Exact consumed inputs for the frozen natural 13-step chain; unused advertised snapshots/deltas omitted",
"scope_sha256": file_sha256(scope), "inventory_sha256": file_sha256(inventory_path),
"origin_hosts": sorted(original["hosts"]),
"files": sorted(sources.values(), key=lambda r: r["path"]),
"payload_inventory": inventory["payload_inventory"], "epochs": epochs,
"payload_totals": inventory["total_used_including_ta_tal"],
"historical_formal_summary_sha256": inventory["formal_summary_sha256"]}
def verify(root: Path, manifest: dict) -> dict:
total = 0
allowed = {r["path"] for r in manifest["files"]} | {"bundle-manifest.json"}
actual = {str(p.relative_to(root)) for p in root.rglob("*") if p.is_file()}
if actual - allowed:
raise ValueError("unlisted bundle files: " + str(sorted(actual - allowed)))
for row in manifest["files"]:
path = safe_path(root, row["path"])
if not path.is_file() or path.stat().st_size != row["bytes"] or file_sha256(path) != row["sha256"]:
raise ValueError(f"bundle file missing or changed: {row['path']}")
total += row["bytes"]
return {"pass": True, "files": len(manifest["files"]), "bytes": total,
"full_archive_closure": False, "payload_totals": manifest["payload_totals"]}
def epoch_subset(root: Path, epoch: Path, scope: Path, manifest_path: Path, expected_sha256: str) -> dict:
"""Bind server eligibility to pinned, original metadata; no implicit skip mode."""
if not expected_sha256 or root.resolve() != (manifest_path.parent / "archive").resolve():
raise ValueError("subset requires a pinned manifest beside its archive")
manifest = load_manifest(manifest_path, expected_sha256)
if file_sha256(scope) != manifest["scope_sha256"]:
raise ValueError("subset scope changed")
for row in manifest["files"]:
if "/blobs/" not in row["path"]:
path = safe_path(manifest_path.parent, row["path"])
if path.stat().st_size != row["bytes"] or file_sha256(path) != row["sha256"]:
raise ValueError("subset metadata changed: " + row["path"])
relative = str(epoch.resolve().relative_to(root.resolve()))
matches = [e for e in manifest["epochs"] if e["path"] == relative and e["sha256"] == file_sha256(epoch)]
if len(matches) != 1:
raise ValueError("epoch is not bound by the consumed subset")
return matches[0]
def stream(manifest: dict) -> None:
with tarfile.open(fileobj=sys.stdout.buffer, mode="w|") as tar:
for row in manifest["files"]:
source = Path(row["source"])
if source.stat().st_size != row["bytes"]:
raise ValueError("source changed after manifest export")
tar.add(source, arcname=row["path"], recursive=False)
def extract(root: Path, manifest: dict) -> dict:
allowed = {r["path"]: r for r in manifest["files"]}
seen = set()
with tarfile.open(fileobj=sys.stdin.buffer, mode="r|") as tar:
for member in tar:
if member.name not in allowed or member.name in seen or not member.isfile():
raise ValueError("unexpected/duplicate/non-regular tar member")
row = allowed[member.name]
if member.size != row["bytes"]:
raise ValueError("tar member size mismatch")
target = safe_path(root, member.name)
target.parent.mkdir(parents=True, exist_ok=True)
if target.exists():
if target.stat().st_size != row["bytes"] or file_sha256(target) != row["sha256"]:
raise ValueError("refusing to overwrite differing bundle content")
else:
pending = target.with_name(target.name + ".partial")
try:
with tar.extractfile(member) as source, pending.open("xb") as out:
shutil.copyfileobj(source, out)
if file_sha256(pending) != row["sha256"]:
raise ValueError("transferred blob SHA256 mismatch")
pending.chmod(0o444)
pending.replace(target)
finally:
pending.unlink(missing_ok=True)
seen.add(member.name)
if seen != set(allowed):
raise ValueError("incomplete bundle transfer")
return verify(root, manifest)
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=("export", "stream", "extract", "verify"))
parser.add_argument("--manifest", type=Path, required=True)
parser.add_argument("--root", type=Path)
parser.add_argument("--archive", type=Path)
parser.add_argument("--scope", type=Path)
parser.add_argument("--inventory", type=Path)
parser.add_argument("--origin-replay-manifest", type=Path)
parser.add_argument("--expected-sha256")
args = parser.parse_args()
if args.action == "export":
if args.manifest.exists():
raise ValueError("refusing to replace bundle manifest")
atomic_json(args.manifest, export_manifest(args.archive, args.scope, args.inventory, args.origin_replay_manifest))
print(json.dumps({"manifest_sha256": file_sha256(args.manifest)}))
else:
manifest = load_manifest(args.manifest, args.expected_sha256)
if args.action == "stream":
stream(manifest)
else:
print(json.dumps(extract(args.root, manifest) if args.action == "extract" else verify(args.root, manifest)))
if __name__ == "__main__":
main()