diff --git a/Cargo.toml b/Cargo.toml index a86519f..7593801 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -33,5 +33,6 @@ reqwest = { version = "0.12.12", default-features = false, features = ["blocking pprof = { version = "0.14.1", optional = true, features = ["flamegraph", "prost-codec"] } flate2 = { version = "1.0.35", optional = true } tempfile = "3.16.0" +libc = "0.2" [dev-dependencies] diff --git a/examples/reuse_fallback_dump.rs b/examples/reuse_fallback_dump.rs new file mode 100644 index 0000000..acc4ad1 --- /dev/null +++ b/examples/reuse_fallback_dump.rs @@ -0,0 +1,53 @@ +//! Read-only extraction of a single fallback cache binding for #187 diagnosis. +use std::path::Path; + +use rocksdb::{DB, Options}; +use rpki::storage::{ + CF_VCIR, CF_VCIR_FAILED_FETCH_REUSE_IDENTITY, ValidatedCaInstanceResult, + VcirFailedFetchReuseIdentity, column_family_descriptors, +}; +use serde::Serialize; +use sha2::{Digest, Sha256}; + +fn binding(value: &T) -> Result> { + Ok(hex::encode(Sha256::digest(serde_cbor::to_vec(value)?))) +} + +fn main() -> Result<(), Box> { + let args: Vec = std::env::args().collect(); + if args.len() != 3 { + return Err("usage: reuse_fallback_dump ".into()); + } + let db = DB::open_cf_descriptors_read_only( + &Options::default(), + Path::new(&args[1]), + column_family_descriptors(), + false, + )?; + let raw = db + .get_cf( + &db.cf_handle(CF_VCIR).ok_or("missing VCIR family")?, + format!("vcir:{}", args[2]).as_bytes(), + )? + .ok_or("missing selected VCIR")?; + let vcir: ValidatedCaInstanceResult = serde_cbor::from_slice(&raw)?; + let raw = db + .get_cf( + &db.cf_handle(CF_VCIR_FAILED_FETCH_REUSE_IDENTITY) + .ok_or("missing identity family")?, + format!("vcir_failed_fetch_reuse_identity:{}", args[2]).as_bytes(), + )? + .ok_or("missing selected identity")?; + let identity: VcirFailedFetchReuseIdentity = serde_cbor::from_slice(&raw)?; + println!( + "{}", + serde_json::to_string(&serde_json::json!({ + "manifestRsyncUri": args[2], + "vcirSha256": binding(&vcir)?, + "reuseIdentitySha256": binding(&identity)?, + "vcir": vcir, + "identity": identity, + }))? + ); + Ok(()) +} diff --git a/scripts/experiments/reuse_eval/.gitignore b/scripts/experiments/reuse_eval/.gitignore new file mode 100644 index 0000000..7a60b85 --- /dev/null +++ b/scripts/experiments/reuse_eval/.gitignore @@ -0,0 +1,2 @@ +__pycache__/ +*.pyc diff --git a/scripts/experiments/reuse_eval/README.md b/scripts/experiments/reuse_eval/README.md new file mode 100644 index 0000000..1f6544f --- /dev/null +++ b/scripts/experiments/reuse_eval/README.md @@ -0,0 +1,133 @@ +# #187 原始传输录制与五策略回放评估 + +实现采集、归档、闭包核验、固定 epoch HTTPS/rsync 服务、缓存归因、完整序列控制器和单轮正式七指标导出。 +186 上 v18 预跑与 v20 第一轮正式测试均已完成65/65,后者七指标已逐项重算并与预跑校验。 +2026-11-12用户决定收尾本次交付:后续两轮正式测试暂不执行,不启动新录制或回放;186的原始录制、预跑、正式结果、state及历史失败现场全部保留,不清理或改写。 +正式独立重复数为1,预跑不并入正式统计;不能把功能测试的 timing 当性能结果。 +普通 `rpki` 不启用录制;显式传 `--record-transport-dir ` 才归档。 +记录的是解码后 HTTP 实体字节和 rsync 文件,不是 TLS 报文。 + +## 录制入口 + +在已经分配独占窗口的 186 上执行;不得使用/操作 231。 +旧 Panda 的状态与恢复脚本见 `specs/develop/20261109_2/`。 +所有二进制、输入、临时文件、状态与归档位于独立 `/data/rpki187/20261109/`。 + +配置示例(所有路径显式给出,capture_root 每次唯一): + +```json +{ + "run_root": "/data/rpki187/20261109", + "archive_root": "/data/rpki187/20261109/archive/capture_YYYYMMDDTHHMMSSZ", + "binary": "/data/rpki187/20261109/bin/rpki-recording", + "tals": ["/data/rpki187/20261109/fixtures/tal/afrinic.tal", "/data/rpki187/20261109/fixtures/tal/apnic.tal", "/data/rpki187/20261109/fixtures/tal/arin.tal", "/data/rpki187/20261109/fixtures/tal/lacnic.tal", "/data/rpki187/20261109/fixtures/tal/ripe.tal"], + "duration_secs": 3600, + "poll_secs": 60, + "step_secs": 300, + "workers": 4, + "max_repositories": 1000, + "bootstrap_attempts": 3, + "rp_timeout_secs": 1800, + "rp_args": ["--parallel-max-repo-sync-workers-global", "4", "--parallel-phase2-object-workers", "4", "--rsync-scope", "module-root"], + "limits": {"min_free_bytes": 161061273600, "min_root_free_inodes": 10000, "max_growth_bytes": 214748364800, "max_body_bytes": 2147483648, "request_timeout_secs": 30, "body_deadline_secs": 240, "observation_deadline_secs": 600, "attempts": 2} +} +``` + +```bash +python3 preflight.py --config /data/rpki187/20261109/config/capture.json --out /data/rpki187/20261109/proof/capture-preflight.json +python3 capture.py --config /data/rpki187/20261109/config/capture.json +python3 verify.py --archive /data/rpki187/20261109/archive/capture_YYYYMMDDTHHMMSSZ +``` + +真实内部 RP 完整 bootstrap 后,采集器补齐每个已发现 notification 的当前 snapshot 与可取得的 delta。 +内部 RP 当前文件 TAL 模式要求显式 TA 路径;控制器在每轮发现运行前,从 TAL 原始 HTTPS 地址(必要时 rsync)下载真实 TA,归档为 `source=ta_refresh` 事件,再将该轮固定的证书文件传给 RP 验证。不会使用旧的测试 TA。 +只有完整初始 epoch 合格才定义 t0 并计时一小时。每仓库的轮询器至多每 60 秒发起一轮,单仓库不重叠; +较慢仓库可能落后,实际请求/完成时间保留。内部 RP 每 300 秒额外做一次真实发现/传输探测,其请求通过 `source=rpki` 区分; +新增仓库在发现后进入采集,不声称互联网全量或每次短暂发布皆被捕获。 +采集过程不测性能;正式测量使用 release 构建与冻结归档。 + +## 归档契约 + +- `capture.json`:配置、二进制哈希、真实 TAL/constraints、发现 run 命令/状态、t0/end/status。 +- `inputs/`:真实 TAL 和对应 constraints 的固定副本;TA 证书通过实际 HTTP/rsync-object 事件保存,内部 RP 保持真实信任链验签。 + 文件 TAL 导出 CIR 时必须提供 HTTP(S) TAL locator;本工具使用 `https://capture.rpki187.invalid/tal//<文件名>` 作为明确的内容标识,不访问该地址、不更改 TAL 字节。实际 RRDP/TA 网络 URI 始终保留原值。 +- `blobs/sha256/<前两位>/`:不可变原始 XML/DER 内容;同 URI 可以对应多个 hash。原始 URI 和签名内容不改写。 +- `events/.json`:原子事件,schema=`rpki-transport-capture-v1`;source/transport/kind/URI/start/complete/status/有限 headers/body;失败 complete=false。无认证头/cookie。rsync `view` 含完整 URI→blob map,空 view 可表示删除;partial 不作为成功视图。 +- `observations/.json`:notification 引用、可用/缺失文件、session/serial、snapshot view、delta 与 snapshot 一致性结论。 +- `views/.json`:用于闭包核验的 URI→对象内容哈希,不代替真实原始文件;视图摘要定义为按 URI 排序、每行紧凑 JSON `[uri,hash]` 加换行的 SHA-256。 +- `epochs/epoch_XXXX.json`:逻辑时刻之前已完成的最新完整 observation、最新失败尝试、TA/rsync 事件及缺口;绝不使用未来完成的数据。理论 13 步。 +- `closure-report.json`:blob、epoch 绑定、snapshot view 与时间边界核验。 +- `discovery/`:内部 RP 私有 state/mirror/CIR/CCR/真实验证报告;不接触旧 Panda 状态。 + +采集初始的非必需旧 delta 已淘汰时明确列出,完整 snapshot 仍可建立起点; +同 session 更新所需 delta 链缺失/前置 hash 错误/应用结果与 snapshot 不同,该 observation 不合格。 +初始闭包不完整时 status=bootstrap_incomplete,保留证据并退出 2,不开启一小时正式窗口。 +显式配置 `bootstrap_gap_policy: "record-with-gaps"` 可继续保存诊断性一小时原始序列, +状态为 `recording_with_gaps` / `recorded_with_gaps`,并固化 bootstrap 缺口。所有失败地址继续采样, +epoch 的严格 complete 标志不放宽;没有显式范围契约时,verify/server 仍拒绝不完整输入。 +该模式退出 0 仅表示采集完成,不能作为正式实验准入;范围选择和证书图闭包另行核验。 +不得仅凭录制成功声称五组或全部 replay 已验收。 + +停止:SIGTERM/SIGINT 停止提交新采样,已有请求有界 drain,保留真实完成时间; +controller 会终止自己创建的 RP 进程组。新 capture 必须新目录,禁止覆盖旧录制。 +原始文件、发现报告可能较大,首轮 disk-growth 预算 200 GiB(保守包含同盘其他增长),最低空闲 150 GiB; +root 空闲 inode <10k 停止。归档中断 status=interrupted/failed,不冒作完整一小时。 + +## 用户已批准的 109 仓库范围 + +`scope.py` 只生成原 archive 外的显式契约,不修改原始 `complete=false`、八个 missing 或对象字节。 +契约冻结 13 个原 epoch、109 个 included、8 个 excluded、五个真实 TA,以及最后一步真实 rsync view 的事件来源。 +`verify.py --scope` 重新核验原 blob/更新链和时间绑定,输出独立 `scoped-closure-report.json`; +scoped server/prepare 必须先有这份成功报告。生成 scope 的 metadata 检查本身不代表原始文件闭包通过。 + +```bash +python3 scope.py --archive /data/rpki187/20261109/archive/capture_03 \ + --routes CONFIG/native_routes.json --out /data/rpki187/20261109/scoped109_v12/scope.json +python3 verify.py --archive /data/rpki187/20261109/archive/capture_03 \ + --scope /data/rpki187/20261109/scoped109_v12/scope.json +python3 sequence_matrix.py --config CONFIG/pilot186_v12.json +``` + +配置与执行说明见 workspace `specs/develop/20261109_4/remote_pilot_runbook.md`。 +最后一步通过受控立即 HTTP 503 触发 `rpki.xindi.eu` 的原始只读 rsync view;不重现原公网 TLS 超时延迟。 +八个 excluded notification 也固定 503,未知实体 404,无上游补取。原 TAL/TA、对象签名、逻辑验证时间和 policy 保持真实验证路径。 + +`sequence_matrix.py` 仅允许指定 186 主机/root/独立持久化目录。它保存旧 Panda 的初始活动状态,暂停后检查竞争 RP, +创建实验 namespace,五组依次运行全部 13 步;每步从自己的前态推进,核对契约、全部五 TA、CIR/CCR、T1/T2 和真实传输分支。 +每次 RP 单独的 cgroup 采集 CPU/MemoryPeak(server 在另一 namespace/CPU),exact cache-size 在计时外采集。 +成功步骤删除控制器新建的 pre-state/T2 scratch DB,仅保留哈希和测量证明;T1 权威 state、完整 run 输出及原始录制全部保留,失败步骤的 scratch 留作排查。 +正常完成、异常或 SIGINT/SIGTERM 时清理本控制器的 namespace,并恢复它暂停的旧 Panda;原本 inactive 的服务不会主动启动。 +硬断电/SIGKILL 后需按 runbook 检查并恢复,不能据旧 summary 推断当前状态。 + +完整 pilot 为 65 个 T1 和 65 个 T2,v18 已在186全部通过。 +未启用正式测量的 pilot 显式输出 `performance_ready=false`,其 sync wall union、payload-ready 原子发布边界缺失,不能补造这两项或将 pilot 作为完整七指标正式结果。 +T1 cgroup CPU/内存、T2 engine wall/CPU、分层命中计数和 cache-size 可作为 pilot 原始证据;T1/T2 不相加推导端到端时间。 + +## 单轮正式入口与当前保留位置 + +`single_formal.py` 读取冻结配置,先校验原预跑65项证明、工具/ELF/scope哈希,在独立新结果根调用同一矩阵引擎,结束后重读原始证明并导出 `single-report.json` 与65行 `all-steps.csv`。正式模式要求 `--evaluation-metrics-out` 的原生同步区间及CCR原子发布时钟;HTTP/rsync测量scope归一化后仍须与原始传输结果完全匹配。 + +七指标为同步执行区间并集、独立T2冻结输入验证wall、trigger至CCR原子发布、各层hits/queries、T1整个cgroup CPU秒、GNU time最大RSS、所选策略必要缓存字节。T2从T1前缓存开始,输入覆盖不得导入本步新验证结论,包含必要缓存持久化与I/O drain。 + +当前原件均留在186的 `/data/rpki187/20261109/`: + +- `archive/capture_03`:原始录制,109个成功RRDP仓库,八个持续缺口单列,五个真实TA,一小时13个逻辑时点。 +- `results/scoped109_pilot_v18`:已完成预跑,65/65。 +- `results/scoped109_formal_v20_r1`:已完成第一轮正式测试,65/65。 +- `results/scoped109_single_v20`:正式单轮状态与最终导出。 + +五策略均关闭prefetch,使用CPU1–3、3个worker及5GiB内存上限,server使用CPU0;同机共享存储、page cache和CPU sibling,不能声称物理资源完全隔离。当前没有第二、第三轮正式结果,后续运行须按用户新的安排另行启动。 + +分析和最终收尾见工作区 `specs/develop/20261112/`,原PPT第10/11页已填入第一轮配置与结果。本地仅保存提取指标、统计和紧凑证明,不复制原始实验目录。 + +## 验证 + +```bash +python3 -m unittest discover -s scripts/experiments/reuse_eval -p 'test_*.py' -v +cargo test --lib recording +cargo test --lib transport_recording +``` + +本地 HTTP 夹具只检查协议和归档逻辑;真实验收必须运行内部 RP 加真实 TAL/TA,测试性能使用 release。 + +2026-11-12收尾:Python控制测试77项通过;Rust沿用仓库coverage默认跳过配置,累计1,277项通过、15项忽略,99个集成测试目标均完成。原有CLI“离线”用例在默认网络环境停留,终止后以串行及外部HTTP拒绝代理完成剩余目标;不将首次默认命令记为成功。现有过滤口径行覆盖率88.68%,未达到90%门槛,全仓未过滤83.51%。质量缺口与日志记录在收尾目录;本次没有追加远端实验。 diff --git a/scripts/experiments/reuse_eval/cache_size.py b/scripts/experiments/reuse_eval/cache_size.py new file mode 100644 index 0000000..77f4a35 --- /dev/null +++ b/scripts/experiments/reuse_eval/cache_size.py @@ -0,0 +1,135 @@ +#!/usr/bin/env python3 +"""Attribute retained validation bytes from exact DB statistics and a run contract.""" +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import stat + +from common import atomic_json, file_sha256, read_json + +COMPONENTS = { + "roa": "roa_cache_projection", + "child_certificate": "child_certificate_cache_projection", + "publication_point": "publication_point_cache_projection", + "common_vcir": "vcir", + "common_manifest_replay": "manifest_replay_meta", + "common_failed_fetch_identity": "vcir_failed_fetch_reuse_identity", + "transport_prefetch": "transport_prefetch", +} +PROFILES = { + "baseline": (False, False, False, False), + "signature": (False, False, False, True), + "object": (False, True, True, False), + "pp": (True, False, False, False), + "hybrid": (True, True, True, False), +} + + +def profile_from_contract(contract: dict) -> tuple[str, dict]: + cache = contract["cache"] + keys = ("publicationPoint", "roa", "childCertificate", "cryptoSignature", "transportPrefetch") + if any(type(cache.get(key)) is not bool for key in keys): + raise ValueError("contract must explicitly contain boolean cache settings") + if cache["transportPrefetch"]: + raise ValueError("transport prefetch is outside the five-profile matrix") + flags = tuple(cache[key] for key in keys[:4]) + for name, expected in PROFILES.items(): + if flags == expected: + return name, {"roa": cache["roa"], "child_certificate": cache["childCertificate"], + "publication_point": cache["publicationPoint"], "signature": cache["cryptoSignature"]} + raise ValueError("cache combination is outside the five-profile matrix") + + +def file_inventory(path: Path) -> dict: + if path.is_symlink(): + raise ValueError(f"cache sidecar must not be a symlink: {path}") + if not path.exists(): + return {"path": str(path), "exists": False, "files": 0, "file_bytes": 0, "allocated_bytes": 0} + files = [path] if path.is_file() else sorted(path.rglob("*")) + size, allocated, count, inodes = 0, 0, 0, set() + for item in files: + meta = item.lstat() + if stat.S_ISDIR(meta.st_mode): + continue + if not stat.S_ISREG(meta.st_mode): + raise ValueError(f"non-regular cache sidecar: {item}") + size += meta.st_size + count += 1 + identity = (meta.st_dev, meta.st_ino) + if identity not in inodes: + if not hasattr(meta, "st_blocks"): + raise ValueError("allocated-byte measurement requires filesystem block counts") + allocated += meta.st_blocks * 512 + inodes.add(identity) + return {"path": str(path), "exists": True, "files": count, "file_bytes": size, "allocated_bytes": allocated} + + +def account(db: Path, stats_path: Path, contract_path: Path) -> dict: + db = db.resolve() + stats = {} + for line in stats_path.read_text().splitlines(): + key, sep, value = line.partition("=") + if not sep: + continue + if key in stats: + raise ValueError(f"duplicate DB statistics field: {key}") + stats[key] = value + if stats.get("mode") != "exact" or stats.get("logical_bytes_available") != "true": + raise ValueError("cache accounting requires db_stats --exact") + if Path(stats["db"]).resolve() != db: + raise ValueError("DB statistics belong to a different state path") + contract = read_json(contract_path) + profile, enabled = profile_from_contract(contract) + components = {} + for name, cf in COMPONENTS.items(): + item = {"column_family": cf, "required_for_selected_reuse": enabled.get(name, False)} + for field in ("keys", "key_bytes", "value_bytes", "live_sst_size_bytes"): + value = int(stats[f"cf.{cf}.{field}"]) + if value < 0: + raise ValueError("negative DB statistics") + item[field] = value + item["logical_bytes"] = item["key_bytes"] + item["value_bytes"] + components[name] = item + sidecars = { + "signature": file_inventory(db.with_name(db.name + ".crypto-sig-cache")), + "publication_point": file_inventory(db.with_name(db.name + ".pp-cache-index")), + "child_certificate": file_inventory(db.with_name(db.name + ".child-cert-cache-index")), + } + required_cf = sum(item["logical_bytes"] for item in components.values() if item["required_for_selected_reuse"]) + required_files = sum(item["file_bytes"] for name, item in sidecars.items() if enabled[name]) + required = required_cf + required_files + return { + "schema": "rpki-validation-cache-accounting-v1", "db": str(db), "profile": profile, + "validation_contract_sha256": file_sha256(contract_path), "db_stats_sha256": file_sha256(stats_path), + "cache_settings": contract["cache"], "measurement_outside_timed_window": True, + "required_serialized_bytes": required, "required_serialized_mib": required / 1024**2, + "required_cf_key_value_bytes": required_cf, "required_sidecar_file_bytes": required_files, + "all_retained_validation_cf_key_value_bytes": sum(item["logical_bytes"] for item in components.values()), + "all_retained_sidecar_file_bytes": sum(item["file_bytes"] for item in sidecars.values()), + "components": components, "sidecars": sidecars, + "accounting_notes": [ + "Raw repository objects, RRDP state, logs and reports are excluded from validation cache bytes.", + "Disabled reuse may still retain common validation projections; those bytes are listed separately.", + "Separate CF records and index files are actual serialized copies and are counted separately.", + "CF compressed SST file lengths and sidecar allocated blocks are separate measures; shared DB WAL/metadata are not apportioned.", + "This is retained serialized cache size, not in-memory cache usage or a minimal theoretical representation.", + ], + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--db", type=Path, required=True) + parser.add_argument("--db-stats", type=Path, required=True) + parser.add_argument("--contract", type=Path, required=True) + parser.add_argument("--out", type=Path, required=True) + args = parser.parse_args() + result = account(args.db, args.db_stats, args.contract) + atomic_json(args.out, result) + print(json.dumps({key: result[key] for key in ("profile", "required_serialized_bytes", "required_serialized_mib")})) + + +if __name__ == "__main__": + main() diff --git a/scripts/experiments/reuse_eval/campaign.py b/scripts/experiments/reuse_eval/campaign.py new file mode 100644 index 0000000..81d2385 --- /dev/null +++ b/scripts/experiments/reuse_eval/campaign.py @@ -0,0 +1,167 @@ +#!/usr/bin/env python3 +"""Wait for the full correctness pilot, then run three independent repeats.""" +from __future__ import annotations + +import argparse +from collections import defaultdict +import csv +from datetime import datetime, timezone +import json +from pathlib import Path +import signal +import statistics +import time + +from common import atomic_json, file_sha256, read_json +from sequence_matrix import EXPECTED_HOST, PROFILE_FLAGS, run_pilot +import os +import socket + +SCALARS = ("repository_sync_ns", "rp_validation_ns", "update_to_payload_ns", "cpu_ns", + "peak_rss_bytes", "cgroup_memory_peak_bytes", "cache_size_bytes") + + +def require_matrix(summary: dict, scope_hash: str, formal: bool) -> None: + pairs = [(row["profile"], row["step"]) for row in summary["runs"]] + expected = {(profile, step) for profile in PROFILE_FLAGS for step in range(13)} + if (summary.get("status") != "completed" or summary.get("pass") is not True + or len(pairs) != 65 or set(pairs) != expected or any(row.get("pass") is not True for row in summary["runs"]) + or summary.get("scope_sha256") != scope_hash): + raise ValueError("full 65-pair correctness prerequisite is not satisfied") + if formal and (summary.get("performance_ready") is not True or any(not row.get("seven_metrics") for row in summary["runs"])): + raise ValueError("formal matrix lacks all seven directly measured metrics") + restoration = summary.get("restoration", {}) + if any(restoration.get(name, 0) != 0 for name in ("rp187rp", "rp187srv")): + raise ValueError("matrix namespace restoration failed") + if restoration.get("panda_active", True) is not True or restoration.get("panda_container_running", True) is not True: + raise ValueError("matrix original Panda restoration failed") + + +def distribution(values: list[float]) -> dict: + return {"n": len(values), "mean": statistics.mean(values), "stdev": statistics.stdev(values) if len(values) > 1 else 0, + "min": min(values), "max": max(values), "values": values} + + +def aggregate(summaries: list[dict]) -> dict: + if len(summaries) != 3: + raise ValueError("exactly three independent complete repeats are required") + scope = summaries[0]["scope_sha256"] + binary = summaries[0]["tool_sha256"]["binary"] + tools = summaries[0]["tool_sha256"] + for summary in summaries: + require_matrix(summary, scope, formal=True) + if summary["tool_sha256"] != tools: + raise ValueError("formal repeats used different RP binaries") + groups = defaultdict(list) + for repeat, summary in enumerate(summaries, 1): + for profile in PROFILE_FLAGS: + rows = [row for row in summary["runs"] if row["profile"] == profile] + for label, selected in (("cold", [r for r in rows if r["step"] == 0]), + ("incremental", [r for r in rows if 1 <= r["step"] <= 12]), + ("incremental_without_fallback", [r for r in rows if 1 <= r["step"] <= 11]), + ("native_fallback", [r for r in rows if r["step"] == 12])): + metrics = [row["seven_metrics"] for row in selected] + value = {"repeat": repeat, "steps": len(selected), + "means": {key: statistics.mean(m[key] for m in metrics) for key in SCALARS}, + "cache_size_at_end_bytes": max(selected, key=lambda r: r["step"])["seven_metrics"]["cache_size_bytes"], + "hit_ratios": {}} + for layer in ("signature", "roa", "child_certificate", "publication_point"): + numerator = sum(m["cache_hit_ratio"][layer]["hits"] for m in metrics) + denominator = sum(m["cache_hit_ratio"][layer]["queries"] for m in metrics) + value["hit_ratios"][layer] = {"hits": numerator, "queries": denominator, + "ratio": numerator / denominator if denominator else None} + groups[(profile, label)].append(value) + output = [] + for (profile, label), values in groups.items(): + output.append({"profile": profile, "steps": label, "repeats": values, + "metrics": {key: distribution([v["means"][key] for v in values]) for key in SCALARS}, + "hit_ratios": {layer: distribution([v["hit_ratios"][layer]["ratio"] for v in values]) + if all(v["hit_ratios"][layer]["ratio"] is not None for v in values) else None + for layer in ("signature", "roa", "child_certificate", "publication_point")}}) + return {"pass": True, "performance_ready": True, "repeats": 3, "pairs": 195, "scope_sha256": scope, + "binary_sha256": binary, "groups": output, + "limitations": ["109 observed successful repositories; eight declared gaps; not global RPKI coverage", + "one-hour capture; fixed five-minute logical steps; controlled final-step HTTP failure triggers recorded rsync view", + "same 186 host with separate CPU/network namespaces for server and RP; no independent-machine network latency claim", + "baseline first within every repeat; other profiles rotate; OS page cache is not forcibly dropped", + "three independent repeat means are statistical replicates; individual epochs are not independent repeats", + "RSS and cgroup charged/page-cache memory are reported separately; all RP units have the same 5 GiB limit"]} + + +def run(config: dict) -> dict: + if socket.gethostname() != EXPECTED_HOST or os.geteuid() != 0: + raise ValueError("campaign is restricted to root on the designated 186 host") + output = Path(config["out"]).resolve() + if not str(output).startswith("/data/rpki187/20261109/results/"): + raise ValueError("campaign must use the dedicated persistent experiment root") + output.mkdir(parents=True, exist_ok=False) + configurations = config["repeats"] + if len(configurations) != 3 or len({item["out"] for item in configurations}) != 3: + raise ValueError("campaign requires three distinct state/output roots") + scope_hash = configurations[0]["expected_scope_sha256"] + if any(item.get("formal_metrics") is not True or item["expected_scope_sha256"] != scope_hash + or item["expected_binary_sha256"] != configurations[0]["expected_binary_sha256"] for item in configurations): + raise ValueError("campaign repeat contracts differ") + state = {"status": "waiting_for_correctness_pilot", "pass": False, "performance_ready": False, + "config": config, "repeat_summaries": []} + def save(): + state["updated_utc"] = datetime.now(timezone.utc).isoformat() + atomic_json(output / "campaign-status.json", state) + try: + deadline = time.monotonic() + config.get("pilot_wait_secs", 86400) + prerequisite = Path(config["pilot_summary"]) + while True: + if prerequisite.exists(): + pilot = read_json(prerequisite) + state["pilot_progress_pairs"] = len(pilot.get("runs", [])) + if pilot["status"] == "completed": + require_matrix(pilot, scope_hash, formal=False) + state["pilot_summary_sha256"] = file_sha256(prerequisite) + break + if pilot["status"] != "running": + raise ValueError(f"correctness pilot failed: {pilot.get('error', pilot['status'])}") + if time.monotonic() >= deadline: + raise TimeoutError("correctness pilot did not complete before campaign deadline") + save() + time.sleep(30) + summaries = [] + for index, item in enumerate(configurations, 1): + state.update(status="running", active_repeat=index) + save() + summary = run_pilot(item) + require_matrix(summary, scope_hash, formal=True) + summaries.append(summary) + path = Path(item["out"]) / "summary.json" + state["repeat_summaries"].append({"repeat": index, "path": str(path), "sha256": file_sha256(path)}) + save() + report = aggregate(summaries) + atomic_json(output / "campaign-report.json", report) + with (output / "all-steps.csv").open("w", newline="") as file: + writer = csv.DictWriter(file, fieldnames=["repeat", "profile", "step", *SCALARS]) + writer.writeheader() + for repeat, summary in enumerate(summaries, 1): + for row in summary["runs"]: + writer.writerow({"repeat": repeat, "profile": row["profile"], "step": row["step"], + **{key: row["seven_metrics"][key] for key in SCALARS}}) + state.update(status="completed", performance_ready=True) + state["pass"] = True + save() + return state + except BaseException as exc: + state.update(status="failed", error=f"{type(exc).__name__}: {exc}") + save() + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--config", type=Path, required=True) + args = parser.parse_args() + def interrupted(*_): + raise KeyboardInterrupt("campaign interrupted") + signal.signal(signal.SIGTERM, interrupted) + print(json.dumps(run(read_json(args.config)))) + + +if __name__ == "__main__": + main() diff --git a/scripts/experiments/reuse_eval/capture.py b/scripts/experiments/reuse_eval/capture.py new file mode 100644 index 0000000..1b13643 --- /dev/null +++ b/scripts/experiments/reuse_eval/capture.py @@ -0,0 +1,413 @@ +#!/usr/bin/env python3 +"""Record real internal-RP discovery plus minute RRDP observations on one host.""" +from __future__ import annotations + +import argparse +from concurrent.futures import ThreadPoolExecutor, as_completed +import json +import os +from pathlib import Path +import re +import signal +import subprocess +import threading +import tempfile +import time +import urllib.parse +import uuid + +from common import Archive, SCHEMA, atomic_json, file_sha256, now_ms, read_json +from rrdp import notification, payload_view, view_digest + + +class Collector: + def __init__(self, archive: Archive): + self.archive = archive + self.verified: set[str] = set() + self.lock = threading.Lock() + self.sequence = 0 + + def reference(self, ref: dict) -> dict: + path = self.archive.blob_path(ref["sha256"]) + if path.is_file(): + with self.lock: + if ref["sha256"] not in self.verified: + self.archive.verify_blob({"sha256": ref["sha256"], "size": path.stat().st_size}) + self.verified.add(ref["sha256"]) + return {**ref, "available": True, "size": path.stat().st_size, "cache": True} + events = [] + for _ in range(self.archive.limits.get("attempts", 2)): + event = self.archive.fetch(ref["uri"], ref["kind"]) + events.append(event["id"]) + if event["complete"] and event["body"]["sha256"] == ref["sha256"]: + return {**ref, "available": True, "size": event["body"]["size"], "event_ids": events} + return {**ref, "available": False, "event_ids": events, + "error": "reference unavailable or hash mismatch"} + + def observe(self, uri: str, previous: dict | None = None) -> dict: + archive = self.archive + observation = {"id": str(uuid.uuid4()), "uri": uri, "started_ms": now_ms(), "complete": False} + with self.lock: + self.sequence += 1 + observation["sequence"] = self.sequence + if previous and previous.get("complete"): + observation["base_observation_id"] = previous["id"] + try: + event = archive.fetch(uri, "notification", previous.get("http") if previous else None) + observation["http"] = event + if not event["complete"]: + raise ValueError(event["error"]) + parsed = notification(archive.blob_path(event["body"]["sha256"]), uri) + observation.update(session=parsed["session"], serial=parsed["serial"], notification=event["body"]) + # Snapshot first: preserve an independent starting point and fallback. + refs = sorted(parsed["references"], key=lambda r: (r["kind"] != "snapshot", r["serial"])) + deadline = time.monotonic() + archive.limits.get("observation_deadline_secs", 600) + captured = [] + for ref in refs: + if time.monotonic() > deadline: + captured.append({**ref, "available": False, "error": "observation deadline exceeded"}) + else: + captured.append(self.reference(ref)) + refs = captured + observation["references"] = refs + snapshot = next(ref for ref in refs if ref["kind"] == "snapshot") + if not snapshot["available"]: + raise ValueError("current snapshot is missing") + same = previous and previous.get("complete") and previous.get("session") == parsed["session"] + if same and previous["serial"] == parsed["serial"]: + old_snapshot = next(ref for ref in previous["references"] if ref["kind"] == "snapshot") + if old_snapshot["sha256"] != snapshot["sha256"]: + raise ValueError("snapshot changed without session/serial advancement") + observation.update(view=previous["view"], object_count=previous["object_count"], chain="no_change") + else: + view = payload_view(archive.blob_path(snapshot["sha256"]), "snapshot", parsed["session"], parsed["serial"]) + view_hash = view_digest(view) + atomic_json(archive.root / "views" / f"{view_hash}.json", view) + observation.update(view=view_hash, object_count=len(view), chain="initial_snapshot") + if same: + if parsed["serial"] < previous["serial"]: + raise ValueError("serial rollback within the same session") + old_view = read_json(archive.root / "views" / f"{previous['view']}.json") + deltas = {ref["serial"]: ref for ref in refs if ref["kind"] == "delta"} + needed = range(previous["serial"] + 1, parsed["serial"] + 1) + if parsed["serial"] - previous["serial"] > 10000: + raise ValueError("required delta chain exceeds bound") + for serial in needed: + delta = deltas.get(serial) + if not delta or not delta["available"]: + raise ValueError(f"required delta {serial} missing") + old_view = payload_view(archive.blob_path(delta["sha256"]), "delta", parsed["session"], serial, old_view) + if old_view != view: + raise ValueError("applied delta chain differs from snapshot") + observation["chain"] = "delta_matches_snapshot" + elif previous and previous.get("complete"): + observation["chain"] = "session_reset_snapshot" + observation["complete"] = True + except Exception as exc: + observation["error"] = f"{type(exc).__name__}: {exc}" + observation["completed_ms"] = now_ms() + atomic_json(archive.root / "observations" / f"{observation['id']}.json", observation) + print(json.dumps({k: observation.get(k) for k in ("uri", "serial", "complete", "chain", "error")}), flush=True) + return observation + + +def select_epoch(root: Path, registry: dict, cutoff: int) -> dict: + selected, latest, missing, blocked = {}, {}, [], [] + for path in (root / "observations").glob("*.json"): + item = read_json(path) + if item["completed_ms"] > cutoff: + continue + uri = item["uri"] + order = (item["completed_ms"], item.get("sequence", 0)) + if uri not in latest or order > (latest[uri]["completed_ms"], latest[uri].get("sequence", 0)): + latest[uri] = item + if item["complete"] and (uri not in selected or order > (selected[uri]["completed_ms"], selected[uri].get("sequence", 0))): + selected[uri] = item + for uri, entry in registry.items(): + if entry["first_seen_ms"] <= cutoff and uri not in selected: + missing.append(uri) + elif entry["first_seen_ms"] <= cutoff and not latest[uri]["complete"]: + blocked.append(uri) + # Bind real TA HTTP/rsync-object versions and complete rsync module views. + objects, rsync = {}, {} + for path in (root / "events").glob("*.json"): + event = read_json(path) + if not event["complete"] or event["completed_ms"] > cutoff or event["source"] not in ("rpki", "ta_refresh"): + continue + target = rsync if event["transport"] == "rsync" and event["kind"] == "view" else objects + if event["kind"] not in ("object", "view"): + continue + if event["uri"] not in target or target[event["uri"]]["completed_ms"] < event["completed_ms"]: + target[event["uri"]] = event + contract = root / "contract.json" + return {"schema": SCHEMA, "validation_time_ms": cutoff, "complete": not missing and not blocked, + "contract_sha256": file_sha256(contract) if contract.is_file() else None, + "repositories": {u: {k: o[k] for k in ("id", "session", "serial", "notification", "view", "completed_ms")} + for u, o in selected.items()}, + "latest_attempts": {u: {k: o.get(k) for k in ("id", "complete", "completed_ms", "error")} for u, o in latest.items()}, + "missing": sorted(missing), "blocked_latest_attempts": sorted(blocked), "ta_object_events": {u: e["id"] for u, e in objects.items()}, + "rsync_view_events": {u: e["id"] for u, e in rsync.items()}} + + +class Capture: + def __init__(self, config: dict): + self.config = config + poll, step, duration = config.get("poll_secs", 60), config.get("step_secs", 300), config.get("duration_secs", 3600) + if poll < 60 or step < poll or duration < step or duration % step: + raise ValueError("require poll>=60, step>=poll, duration>=step and a whole number of steps") + if not 1 <= config.get("workers", 4) <= 8: + raise ValueError("capture workers must be between 1 and 8") + if len(config["tals"]) != 5 or len(set(config["tals"])) != 5: + raise ValueError("main capture requires five distinct real TAL paths") + if config.get("bootstrap_gap_policy", "abort") not in ("abort", "record-with-gaps"): + raise ValueError("bootstrap_gap_policy must be abort or record-with-gaps") + self.root = Path(config["archive_root"]).resolve() + if self.root.exists() and any(self.root.iterdir()): + raise ValueError("capture root already exists; use a new capture ID") + self.archive = Archive(self.root, config.get("limits")) + self.collector = Collector(self.archive) + self.registry, self.latest, self.seen_events = {}, {}, set() + self.rp = None + self.run_number = 0 + self.stopping = False + self.metadata = {"schema": SCHEMA, "status": "bootstrap", "started_ms": now_ms(), "config": config, + "binary_sha256": file_sha256(Path(config["binary"])), "runs": []} + self.metadata["scripts_sha256"] = {p.name: file_sha256(p) for p in Path(__file__).parent.glob("*.py")} + self.metadata["machine"] = {"uname": list(os.uname()), "cpus": os.cpu_count()} + self.pin_inputs() + self.save() + + def pin_inputs(self) -> None: + tals = [] + for name in self.config["tals"]: + source = Path(name) + data = source.read_bytes() + body = self.archive.put_stream(__import__("io").BytesIO(data)) + target = self.root / "inputs" / source.name + target.parent.mkdir(exist_ok=True) + target.write_bytes(data) + item = {"path": str(target), **body} + # CIR requires an HTTP(S) locator even for file TAL inputs. This is + # an explicit content-addressed label, never a download endpoint. + item["cir_tal_uri"] = f"https://capture.rpki187.invalid/tal/{body['sha256']}/{source.name}" + constraint = source.with_suffix(".constraints") + if constraint.exists(): + target.with_suffix(".constraints").write_bytes(constraint.read_bytes()) + item["constraints_sha256"] = file_sha256(constraint) + tals.append(item) + self.metadata["tals"] = tals + + def save(self) -> None: + atomic_json(self.root / "capture.json", self.metadata) + atomic_json(self.root / "registry.json", self.registry) + + def discover(self) -> None: + for path in (self.root / "events").glob("*.json"): + if path.name in self.seen_events: + continue + event = read_json(path) + self.seen_events.add(path.name) + if event["source"] == "rpki" and event["kind"] == "notification": + self.registry.setdefault(event["uri"], {"first_seen_ms": event["started_ms"]}) + if len(self.registry) > self.config.get("max_repositories", 1000): + raise RuntimeError("repository count limit exceeded") + + def start_rp(self) -> None: + self.archive.guard() + self.run_number += 1 + run = self.root / "discovery" / f"run_{self.run_number:04d}" + run.mkdir(parents=True) + (self.root / "discovery/state").mkdir(parents=True, exist_ok=True) + (run / "ta").mkdir() + ta_versions = [] + for tal in self.metadata["tals"]: + ta_versions.append(self.refresh_ta(Path(tal["path"]), run / "ta")) + command = [self.config["binary"], "--db", str(self.root / "discovery/state/db"), + "--record-transport-dir", str(self.root), "--rsync-mirror-root", str(self.root / "discovery/mirror"), + "--report-json", str(run / "report.json"), "--report-json-compact", + "--validation-contract-out", str(run / "validation-contract.json"), + "--ccr-out", str(run / "result.ccr"), "--cir-enable", "--cir-out", str(run / "input.cir"), + "--analyze", "--analysis-out", str(run / "analysis")] + for tal, ta in zip(self.metadata["tals"], ta_versions): + command += ["--tal-path", tal["path"], "--ta-path", ta["path"], "--cir-tal-uri", tal["cir_tal_uri"]] + command += self.config.get("rp_args", []) + env = dict(os.environ, TMPDIR=str(self.root / "partial")) + self.rp_started = time.monotonic() + with (run / "stdout.log").open("wb") as out, (run / "stderr.log").open("wb") as err: + self.rp = subprocess.Popen(command, stdout=out, stderr=err, env=env, start_new_session=True) + self.metadata["runs"].append({"path": str(run), "command": command, "started_ms": now_ms(), "pid": self.rp.pid, "ta_versions": ta_versions}) + self.save() + + def refresh_ta(self, tal: Path, destination: Path) -> dict: + """Existing internal CLI file mode requires an explicit, genuine TA file. + + Refresh from original TAL endpoints before each run, then let the real + RP verify the DER/SPKI, validity and trust-anchor profile as usual. + """ + uris = [line.strip() for line in tal.read_text().splitlines() + if line.strip().startswith(("https://", "rsync://"))] + uris.sort(key=lambda uri: not uri.startswith("https://")) + for uri in uris: + if uri.startswith("https://"): + event = self.archive.fetch(uri, "object", source="ta_refresh") + ref = event.get("body") + else: + event = {"source": "ta_refresh", "transport": "rsync", "kind": "object", "uri": uri, + "started_ms": now_ms(), "complete": False, "objects": {}} + ref = None + try: + with tempfile.TemporaryDirectory(dir=self.root / "partial") as name: + result = subprocess.run(["rsync", "-rt", "--contimeout=15", "--timeout=30", "--", uri, name + "/"], + capture_output=True, timeout=60) + if result.returncode: + raise ValueError(result.stderr.decode(errors="replace")[:2000]) + path = Path(name) / Path(urllib.parse.urlsplit(uri).path).name + with path.open("rb") as stream: + ref = self.archive.put_stream(stream) + event.update(complete=True, objects={uri: ref}) + except Exception as exc: + event["error"] = f"{type(exc).__name__}: {exc}" + self.archive.event(event) + if event["complete"]: + target = destination / (tal.stem + ".cer") + target.write_bytes(self.archive.blob_path(ref["sha256"]).read_bytes()) + return {"path": str(target), "uri": uri, "event_id": event["id"], **ref} + raise RuntimeError(f"could not download genuine TA from TAL endpoints: {tal}") + + def check_rp(self) -> None: + if self.rp is None: + return + if time.monotonic() - self.rp_started > self.config.get("rp_timeout_secs", 1800): + self.stop_rp() + raise RuntimeError("discovery RP exceeded wall-clock timeout") + status = self.rp.poll() + if status is not None: + run = self.metadata["runs"][-1] + run.update(exit_code=status, completed_ms=now_ms()) + self.rp = None + self.save() + if status != 0: + raise RuntimeError(f"real discovery RP failed: {status}") + stderr = (Path(run["path"]) / "stderr.log").read_text(errors="replace") + anchors = re.findall(r"wrote CIR: .*?trust_anchors=(\d+)", stderr) + if not anchors or int(anchors[-1]) != len(self.metadata["tals"]): + raise RuntimeError("discovery did not produce a CIR with all five genuine trust anchors") + stdout = (Path(run["path"]) / "stdout.log").read_text(errors="replace") + counts = {key: int(value) for key, value in re.findall(r"^(vrps|aspas|rrdp_repos_unique|audit_publication_points)=(\d+)$", stdout, re.MULTILINE)} + run.update(trust_anchors=int(anchors[-1]), counts=counts) + self.save() + + def stop_rp(self) -> None: + if self.rp is not None and self.rp.poll() is None: + os.killpg(self.rp.pid, signal.SIGTERM) + try: + self.rp.wait(timeout=10) + except subprocess.TimeoutExpired: + os.killpg(self.rp.pid, signal.SIGKILL) + self.rp.wait(timeout=10) + if self.metadata["runs"]: + self.metadata["runs"][-1].update(exit_code=self.rp.returncode, completed_ms=now_ms(), stopped_by_controller=True) + self.rp = None + + def run(self) -> None: + workers = self.config.get("workers", 4) + self.start_rp() + while self.rp is not None and not self.stopping: + self.archive.guard() + self.check_rp() + self.discover() + time.sleep(1) + self.discover() + if self.stopping: + raise RuntimeError("capture stopped during bootstrap") + if not self.registry: + raise RuntimeError("internal RP discovered no RRDP repositories") + normal_contract = read_json(Path(self.metadata["runs"][0]["path"]) / "validation-contract.json") + atomic_json(self.root / "contract.json", {"schema": SCHEMA, "binary_sha256": self.metadata["binary_sha256"], + "scripts_sha256": self.metadata["scripts_sha256"], "machine": self.metadata["machine"], + "tals": self.metadata["tals"], "normal_validation_contract": normal_contract, "rp_args": self.config.get("rp_args", [])}) + # Bounded bootstrap retries. A partial starting point is never relabelled complete. + with ThreadPoolExecutor(max_workers=workers) as pool: + for _ in range(self.config.get("bootstrap_attempts", 3)): + pending = {pool.submit(self.collector.observe, uri, self.latest.get(uri)): uri + for uri in self.registry if not self.latest.get(uri, {}).get("complete")} + for future in as_completed(pending): + self.latest[pending[future]] = future.result() + if all(self.latest.get(uri, {}).get("complete") for uri in self.registry): + break + t0 = now_ms() + initial = select_epoch(self.root, self.registry, t0) + atomic_json(self.root / "epochs/epoch_0000.json", initial) + self.metadata.update(bootstrap_complete=initial["complete"], bootstrap_missing=initial["missing"], + bootstrap_blocked_latest_attempts=initial["blocked_latest_attempts"]) + if not initial["complete"] and self.config.get("bootstrap_gap_policy", "abort") == "abort": + self.metadata.update(status="bootstrap_incomplete", missing=initial["missing"]) + self.save() + return + duration = self.config.get("duration_secs", 3600) + poll_secs = self.config.get("poll_secs", 60) + step_secs = self.config.get("step_secs", 300) + self.metadata.update(status="recording" if initial["complete"] else "recording_with_gaps", + t0_ms=t0, end_ms=t0 + duration * 1000) + self.save() + end = time.monotonic() + duration + next_rp = time.monotonic() + step_secs + due = {uri: time.monotonic() + poll_secs for uri in self.registry} + in_flight = {} + while time.monotonic() < end and not self.stopping: + self.archive.guard() + self.check_rp() + self.discover() + moment = time.monotonic() + if moment >= next_rp and self.rp is None: + self.start_rp() + next_rp = moment + step_secs + for uri in self.registry: + due.setdefault(uri, moment) + if uri not in in_flight and moment >= due[uri]: + in_flight[uri] = pool.submit(self.collector.observe, uri, self.latest.get(uri)) + due[uri] = moment + poll_secs + for uri, future in list(in_flight.items()): + if future.done(): + item = future.result() + # Keep the last complete base for chain validation after a failed observation. + if item["complete"]: + self.latest[uri] = item + del in_flight[uri] + self.save() + time.sleep(1) + # Requests have per-body deadlines. Drained responses keep their real completion time. + for future in in_flight.values(): + future.result() + self.stop_rp() + captured_secs = min(duration, max(0, (now_ms() - t0) // 1000)) + for index, offset in enumerate(range(0, captured_secs + 1, step_secs)): + epoch = select_epoch(self.root, self.registry, t0 + offset * 1000) + atomic_json(self.root / "epochs" / f"epoch_{index:04d}.json", epoch) + status = "recorded" if initial["complete"] else "recorded_with_gaps" + self.metadata.update(status="interrupted" if self.stopping else status, finished_ms=now_ms(), repositories=len(self.registry), captured_secs=captured_secs) + self.save() + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--config", type=Path, required=True) + args = parser.parse_args() + capture = Capture(read_json(args.config)) + def stop(*_): + capture.stopping = True + signal.signal(signal.SIGTERM, stop) + signal.signal(signal.SIGINT, stop) + try: + capture.run() + except Exception as exc: + capture.metadata.update(status="failed", error=f"{type(exc).__name__}: {exc}", finished_ms=now_ms()) + raise + finally: + capture.stop_rp() + capture.save() + return 0 if capture.metadata["status"] in ("recorded", "recorded_with_gaps") else 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/experiments/reuse_eval/common.py b/scripts/experiments/reuse_eval/common.py new file mode 100644 index 0000000..eea0304 --- /dev/null +++ b/scripts/experiments/reuse_eval/common.py @@ -0,0 +1,194 @@ +"""Immutable transport capture primitives shared by collection and replay.""" +from __future__ import annotations + +import gzip +import hashlib +import json +import os +from pathlib import Path +import shutil +import tempfile +import time +import urllib.error +import urllib.parse +import urllib.request +import uuid + +SCHEMA = "rpki-transport-capture-v1" +HEADERS = ("etag", "last-modified", "content-type", "content-length", "content-encoding", "date", "location") + + +def now_ms() -> int: + return time.time_ns() // 1_000_000 + + +def atomic_json(path: Path, value: object) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + fd, name = tempfile.mkstemp(prefix=".pending-", dir=path.parent) + try: + with os.fdopen(fd, "w", encoding="utf-8") as stream: + json.dump(value, stream, sort_keys=True, separators=(",", ":"), ensure_ascii=True) + stream.flush() + os.replace(name, path) + finally: + Path(name).unlink(missing_ok=True) + + +def read_json(path: Path) -> object: + return json.loads(path.read_text(encoding="utf-8")) + + +def digest_bytes(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def file_sha256(path: Path) -> str: + with path.open("rb") as stream: + return hashlib.file_digest(stream, "sha256").hexdigest() + + +def origin(uri: str) -> tuple[str, str, int]: + url = urllib.parse.urlsplit(uri) + if url.scheme not in ("http", "https") or not url.hostname or url.username or url.password or url.fragment: + raise ValueError(f"invalid HTTP URI: {uri}") + return url.scheme, url.hostname.lower(), url.port or (443 if url.scheme == "https" else 80) + + +class SameOriginRedirect(urllib.request.HTTPRedirectHandler): + def __init__(self, allowed: tuple[str, str, int]): + self.allowed = allowed + + def redirect_request(self, req, fp, code, msg, headers, newurl): + if origin(newurl) != self.allowed: + raise ValueError(f"cross-origin redirect rejected: {newurl}") + return super().redirect_request(req, fp, code, msg, headers, newurl) + + +class TaRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + if origin(newurl)[0] != "https": + raise ValueError("TA redirect downgraded HTTPS") + return super().redirect_request(req, fp, code, msg, headers, newurl) + + +class Archive: + def __init__(self, root: Path, limits: dict | None = None, *, read_only: bool = False): + self.root = root + self.limits = limits or {} + self.read_only = read_only + self.initial_free = shutil.disk_usage(root.parent).free + if not read_only: + for name in ("blobs/sha256", "events", "partial", "observations", "views", "epochs"): + (root / name).mkdir(parents=True, exist_ok=True) + + def guard(self) -> None: + if self.read_only: + raise ValueError("archive is read-only") + free = shutil.disk_usage(self.root).free + if free < self.limits.get("min_free_bytes", 0): + raise RuntimeError(f"archive disk guard: {free} bytes free") + if self.initial_free - free > self.limits.get("max_growth_bytes", 200 * 1024**3): + raise RuntimeError("capture total disk-growth budget exceeded") + if os.statvfs("/").f_favail < self.limits.get("min_root_free_inodes", 0): + raise RuntimeError("root filesystem inode guard") + + def blob_path(self, sha256: str) -> Path: + if len(sha256) != 64 or any(c not in "0123456789abcdef" for c in sha256): + raise ValueError("invalid SHA-256") + return self.root / "blobs/sha256" / sha256[:2] / sha256 + + def put_stream(self, stream) -> dict: + self.guard() + maximum = self.limits.get("max_body_bytes", 2 * 1024**3) + deadline = time.monotonic() + self.limits.get("body_deadline_secs", 240) + fd, name = tempfile.mkstemp(dir=self.root / "partial") + digest, size = hashlib.sha256(), 0 + try: + with os.fdopen(fd, "wb") as output: + while True: + chunk = stream.read(65536) + if not chunk: + break + size += len(chunk) + if size > maximum or time.monotonic() > deadline: + raise ValueError("body size or wall-clock limit exceeded") + digest.update(chunk) + output.write(chunk) + sha256 = digest.hexdigest() + path = self.blob_path(sha256) + path.parent.mkdir(parents=True, exist_ok=True) + if path.exists(): + Path(name).unlink() + else: + os.replace(name, path) + return {"sha256": sha256, "size": size} + finally: + Path(name).unlink(missing_ok=True) + + def event(self, value: dict) -> dict: + if self.read_only: + raise ValueError("archive is read-only") + value.setdefault("schema", SCHEMA) + value.setdefault("id", str(uuid.uuid4())) + value.setdefault("completed_ms", now_ms()) + atomic_json(self.root / "events" / f"{value['id']}.json", value) + return value + + def fetch(self, uri: str, kind: str, previous: dict | None = None, source: str = "poller") -> dict: + """Keep failed requests; 304 explicitly binds the prior entity hash.""" + self.guard() + allowed = origin(uri) + if allowed[0] != "https" and not self.limits.get("allow_test_http", False): + raise ValueError("live capture requires HTTPS") + event = {"source": source, "transport": "http", "kind": kind, + "uri": uri, "started_ms": now_ms(), "complete": False} + headers = {"User-Agent": "panda-rpki-evaluation-recorder/1", "Accept-Encoding": "identity"} + if previous: + old_headers = previous.get("headers", {}) + if old_headers.get("etag"): + headers["If-None-Match"] = old_headers["etag"] + if old_headers.get("last-modified"): + headers["If-Modified-Since"] = old_headers["last-modified"] + request = urllib.request.Request(uri, headers=headers) + # Ignore machine proxy variables: record direct origin traffic on 186. + redirect = TaRedirect() if kind == "object" else SameOriginRedirect(allowed) + opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), redirect) + try: + try: + response = opener.open(request, timeout=self.limits.get("request_timeout_secs", 30)) + except urllib.error.HTTPError as exc: + response = exc + with response: + event.update(status=response.code, final_uri=response.url, + headers={k: response.headers[k] for k in HEADERS if k in response.headers}) + if response.code == 304: + if not previous or not previous.get("body"): + raise ValueError("304 without a prior body") + if not self.blob_path(previous["body"]["sha256"]).is_file(): + raise ValueError("304 prior body is missing") + event.update(body=previous["body"], prior_event_id=previous["id"], complete=True) + elif response.code == 200: + encoding = response.headers.get("Content-Encoding", "identity").lower() + if encoding not in ("identity", "gzip"): + raise ValueError(f"unsupported content encoding: {encoding}") + body = gzip.GzipFile(fileobj=response) if encoding == "gzip" else response + blob = self.put_stream(body) + if encoding == "identity" and response.headers.get("Content-Length") is not None: + if blob["size"] != int(response.headers["Content-Length"]): + raise ValueError("truncated HTTP entity") + event.update(body=blob, complete=True) + else: + raise ValueError(f"HTTP {response.code}") + except Exception as exc: + event["error"] = f"{type(exc).__name__}: {exc}" + return self.event(event) + + def verify_blob(self, ref: dict) -> None: + path = self.blob_path(ref["sha256"]) + digest, size = hashlib.sha256(), 0 + with path.open("rb") as stream: + for chunk in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(chunk) + size += len(chunk) + if digest.hexdigest() != ref["sha256"] or size != ref["size"]: + raise ValueError(f"corrupt archive blob: {ref['sha256']}") diff --git a/scripts/experiments/reuse_eval/formal_metrics.py b/scripts/experiments/reuse_eval/formal_metrics.py new file mode 100644 index 0000000..2adcce5 --- /dev/null +++ b/scripts/experiments/reuse_eval/formal_metrics.py @@ -0,0 +1,140 @@ +#!/usr/bin/env python3 +"""Validate direct measurement boundaries and preserve seven raw metrics.""" +from __future__ import annotations + +from collections import Counter +from pathlib import Path +import re + +from common import atomic_json, read_json + + +def interval_union(intervals: list[tuple[int, int]]) -> int: + total, left, right = 0, None, None + for start, end in sorted(intervals): + if type(start) is not int or type(end) is not int or start < 0 or end < start: + raise ValueError("invalid sync interval") + if right is None: + left, right = start, end + elif start <= right: + right = max(right, end) + else: + total += right - left + left, right = start, end + return total + (right - left if right is not None else 0) + + +def ratio(hits: int, queries: int, enabled: bool, definition: str) -> dict: + if type(hits) is not int or type(queries) is not int or not 0 <= hits <= queries: + raise ValueError("invalid cache hit denominator") + if not enabled and (hits or queries): + raise ValueError("disabled cache unexpectedly reported queries") + return {"enabled": enabled, "hits": hits, "queries": queries, + "ratio": hits / queries if enabled and queries else None, "definition": definition} + + +def hit_ratios(stage: dict, profile: str) -> dict: + counts, roa = stage["analysis_counts"], stage["roa_validation_cache"] + signature = stage.get("crypto_signature_cache_observe") + stats = list(signature["per_point"].values()) if signature else [] + return { + "signature": ratio(sum(v["verify_skipped"] for v in stats), sum(v["calls"] for v in stats), + profile == "signature", "skipped cryptographic verifications / signature cache calls"), + "roa": ratio(roa["hit_roas"], roa["hit_roas"] + roa["miss_roas"] + roa["blocked_roas"], + profile in ("object", "hybrid"), "reused ROA results / (hits + misses + blocked); context-blocked is a subset of blocked"), + "child_certificate": ratio(counts.get("child_certificate_cache_hit", 0), counts.get("child_certificate_cache_lookup", 0), + profile in ("object", "hybrid"), "reused child-certificate results / child-certificate cache lookups"), + "publication_point": ratio(counts.get("publication_point_cache_reuse_hits", 0), counts.get("publication_point_cache_lookup_total", 0), + profile in ("pp", "hybrid"), "actual publication-point reuse / publication-point cache lookups"), + } + + +def compare_transport_measurements(intervals: list[dict], table: dict, rsync_scope: str) -> dict: + """Compare request spans with the fetch scope recorded by the native table.""" + if rsync_scope not in ("module-root", "publication-point", "host"): + raise ValueError("missing or unsupported measured rsync scope") + + def scope_uri(uri: str) -> str: + if not isinstance(uri, str) or not uri.startswith("rsync://"): + raise ValueError("invalid measured rsync URI") + normalized = uri if uri.endswith("/") else uri + "/" + authority, _, path = normalized[len("rsync://"):].partition("/") + if not authority or any(v in normalized for v in ("?", "#")) or any(v.isspace() for v in normalized): + raise ValueError("invalid measured rsync authority/path") + segments = [v for v in path.split("/") if v] + # Match scoped_rsync_fetch_uri: host scope changes failure deduplication, + # but still fetches the original publication point rather than the host. + if rsync_scope == "module-root" and segments: + return f"rsync://{authority}/{segments[0]}/" + return normalized + + measured = {protocol: set() for protocol in ("rrdp", "rsync")} + proof = [] + for row in intervals: + protocol = row["protocol"] + if protocol not in measured or type(row["success"]) is not bool: + raise ValueError("unrecognized measured protocol or outcome") + uri = scope_uri(row["uri"]) if protocol == "rsync" else row["uri"] + if uri not in table[protocol]: + raise ValueError(f"{protocol} measurement coverage differs from native transport table") + outcome = table[protocol][uri] + if outcome != "Success" and not (isinstance(outcome, dict) and set(outcome) == {"Failure"} + and isinstance(outcome["Failure"], str)): + raise ValueError("invalid native transport outcome") + if row["success"] != (outcome == "Success"): + raise ValueError("measured transport outcome differs from T1") + measured[protocol].add(uri) + proof.append({**row, "scope_uri": uri}) + for protocol in measured: + if measured[protocol] != set(table[protocol]): + raise ValueError(f"{protocol} measurement coverage differs from native transport table") + return {"schema": "rpki-reuse-transport-measurement-v1", "pass": True, + "rsync_scope_policy": rsync_scope, "intervals": proof} + + +def collect(run: Path, benchmark: Path, process: dict, size: dict, profile: str, table: dict) -> dict: + direct = read_json(run / "evaluation.json") + if direct.get("schema_version") != 1 or direct.get("clock") != "Linux CLOCK_MONOTONIC nanoseconds": + raise ValueError("unsupported evaluation clock/schema") + trigger = process["controller_trigger_monotonic_ns"] + began, ready = direct["rp_start_ns"], direct["payload_ready_ns"] + if not 0 < trigger <= began <= ready: + raise ValueError("controller/RP payload clock order mismatch") + intervals = direct["sync_intervals"] + if not intervals or any(not began <= v["start_ns"] <= v["end_ns"] <= ready or type(v["success"]) is not bool for v in intervals): + raise ValueError("sync interval is missing or outside the native run") + transport_proof = compare_transport_measurements( + intervals, table, read_json(run / "contract.json").get("rsyncScopePolicy")) + modes = direct["rrdp_modes"] + if any(v not in ("snapshot", "delta", "no_update") for v in modes.values()): + raise ValueError("unrecognized RRDP mode") + if any(uri not in modes for uri, value in table["rrdp"].items() if value == "Success"): + raise ValueError("successful RRDP mode was not measured") + union = interval_union([(v["start_ns"], v["end_ns"]) for v in intervals]) + if union != direct["sync_wall_union_ns"] or union > ready - began: + raise ValueError("sync union does not match raw intervals") + engine = read_json(benchmark / "engine-timing.json") + if "background write drain" not in engine["boundary"] or engine["wall_ns"] <= 0: + raise ValueError("T2 timing lacks the required background write boundary") + gnu_time = (run / "process-time.txt").read_text() + rss = re.findall(r"Maximum resident set size \(kbytes\):\s*(\d+)", gnu_time) + if len(rss) != 1 or int(rss[0]) <= 0: + raise ValueError("native RP maximum RSS was not measured") + result = { + "schema": "rpki-reuse-seven-metrics-v1", "profile": profile, + "repository_sync_ns": union, "rp_validation_ns": engine["wall_ns"], + "update_to_payload_ns": ready - trigger, + "cache_hit_ratio": hit_ratios(read_json(run / "stage-timing.json"), profile), + "cpu_ns": process["cpu_ns"], "peak_rss_bytes": int(rss[0]) * 1024, + "cgroup_memory_peak_bytes": process["memory_peak_bytes"], + "cache_size_bytes": size["required_serialized_bytes"], + "engine_user_cpu_secs": engine["user_cpu_secs"], "engine_system_cpu_secs": engine["system_cpu_secs"], + "rrdp_modes": dict(Counter(modes.values())), + "boundaries": {"sync": direct["sync_boundary"], "payload": direct["payload_boundary"], + "validation": engine["boundary"], "cpu": "entire T1 RP cgroup including subprocesses; excludes server", + "rss": "GNU time maximum resident set size; Linux wait4 ru_maxrss; separate from cgroup charged memory/page cache", + "cache": "retained required serialized reuse projection records and sidecar files; raw repository and common disabled projections excluded"}, + } + atomic_json(run / "transport-measurement-comparison.json", transport_proof) + atomic_json(run / "seven-metrics.json", result) + return result diff --git a/scripts/experiments/reuse_eval/preflight.py b/scripts/experiments/reuse_eval/preflight.py new file mode 100644 index 0000000..48dcb4b --- /dev/null +++ b/scripts/experiments/reuse_eval/preflight.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +"""Read-only resource checks for the allocated capture host.""" +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import shutil +import subprocess + +from common import atomic_json, now_ms, read_json + + +def preflight(config: dict) -> dict: + root = Path(config["run_root"]).resolve() + if not root.is_dir(): + raise ValueError(f"create allocated run_root before preflight: {root}") + disk = shutil.disk_usage(root) + root_stats = os.statvfs("/") + checks = {"data_free": disk.free >= config.get("limits", {}).get("min_free_bytes", 150 * 1024**3), + "data_utilization": disk.used / disk.total < 0.8, + "root_inode_margin": root_stats.f_favail >= 10000, + "rsync_available": shutil.which("rsync") is not None, + "binary_available": Path(config["binary"]).is_file(), + "all_five_tals": len(config["tals"]) == 5 and all(Path(t).is_file() for t in config["tals"])} + service = subprocess.run(["systemctl", "is-active", "panda-rpki.service"], capture_output=True, text=True, timeout=10) + checks["old_panda_inactive"] = service.stdout.strip() == "inactive" + return {"at_ms": now_ms(), "host": os.uname().nodename, "pass": all(checks.values()), "checks": checks, + "data_total": disk.total, "data_free": disk.free, "root_free_inodes": root_stats.f_favail, + "cpus": os.cpu_count(), "panda_state": service.stdout.strip(), "config": config} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--out", type=Path, required=True) + args = parser.parse_args() + result = preflight(read_json(args.config)) + atomic_json(args.out, result) + print(json.dumps(result)) + return 0 if result["pass"] else 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/experiments/reuse_eval/prepare_replay.py b/scripts/experiments/reuse_eval/prepare_replay.py new file mode 100644 index 0000000..097e5f9 --- /dev/null +++ b/scripts/experiments/reuse_eval/prepare_replay.py @@ -0,0 +1,219 @@ +#!/usr/bin/env python3 +"""Prepare immutable epoch assets and an isolated pair of network namespaces.""" +from __future__ import annotations + +import argparse +import ipaddress +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import urllib.parse + +from common import atomic_json, file_sha256, read_json +from serve import ReplayState + + +def command(*args: str) -> None: + subprocess.run(args, check=True, timeout=30, capture_output=True, text=True) + + +def all_hosts(root: Path) -> list[str]: + hosts = set() + def add(uri): + url = urllib.parse.urlsplit(uri) + host = url.hostname + if not host: + raise ValueError(f"missing host: {uri}") + host = host.encode("idna").decode("ascii").lower() + if ":" in host: + raise ValueError("IPv6 literal URI requires an explicit additional replay mapping") + if not re.fullmatch(r"[a-z0-9.-]+", host): + raise ValueError(f"unsafe hostname: {host}") + hosts.add(host) + for path in (root / "events").glob("*.json"): + add(read_json(path)["uri"]) + for path in (root / "observations").glob("*.json"): + for ref in read_json(path).get("references", []): + add(ref["uri"]) + if len(hosts) > 1000: + raise ValueError("host mapping count bound") + return sorted(hosts) + + +def host_mapping(hosts: list[str]) -> dict[str, str]: + result = {} + for index, host in enumerate(hosts, 1): + try: + address = ipaddress.ip_address(host) + if address.version != 4 or address.is_loopback or address.is_unspecified or address.is_multicast: + raise ValueError("unsupported literal origin address") + result[host] = str(address) + except ValueError as exc: + if re.fullmatch(r"[0-9.]+", host): + raise ValueError(f"invalid/unsupported literal address: {host}") from exc + result[host] = str(ipaddress.ip_address("10.187.1.0") + index) + return result + + +def tls_assets(output: Path, hosts: list[str]) -> dict: + tls = output / "tls" + tls.mkdir(parents=True, exist_ok=True) + host_file = tls / "hosts.json" + if host_file.exists(): + if read_json(host_file) != hosts: + raise ValueError("archive hosts changed after TLS freeze; use a new replay root") + return {"ca": str(tls / "ca.pem"), "cert": str(tls / "server.pem"), "key": str(tls / "server.key")} + if any(tls.iterdir()): + raise ValueError("partial TLS setup exists; inspect it before retrying") + san = [] + for host in hosts: + try: + ipaddress.ip_address(host) + san.append("IP:" + host) + except ValueError: + san.append("DNS:" + host) + ext = tls / "server.ext" + ext.write_text("basicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature,keyEncipherment\nextendedKeyUsage=serverAuth\nsubjectAltName=" + ",".join(san) + "\n") + command("openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout", str(tls / "ca.key"), + "-out", str(tls / "ca.pem"), "-days", "30", "-subj", "/CN=RPKI-187 transport experiment CA", + "-addext", "basicConstraints=critical,CA:TRUE", "-addext", "keyUsage=critical,keyCertSign,cRLSign") + command("openssl", "req", "-new", "-newkey", "rsa:2048", "-nodes", "-keyout", str(tls / "server.key"), + "-out", str(tls / "server.csr"), "-subj", "/CN=RPKI-187 replay") + command("openssl", "x509", "-req", "-in", str(tls / "server.csr"), "-CA", str(tls / "ca.pem"), + "-CAkey", str(tls / "ca.key"), "-CAcreateserial", "-out", str(tls / "server.pem"), + "-days", "30", "-extfile", str(ext)) + for key in (tls / "ca.key", tls / "server.key"): + key.chmod(0o600) + atomic_json(host_file, hosts) + return {"ca": str(tls / "ca.pem"), "cert": str(tls / "server.pem"), "key": str(tls / "server.key")} + + +def rsync_tree(state: ReplayState, output: Path, mapping: dict) -> list[str]: + views, origins = {}, {} + for event in sorted(state.rsync_events, key=lambda e: e["completed_ms"]): + parsed_scope = urllib.parse.urlsplit(event["uri"]) + scope_parts = parsed_scope.path.lstrip("/").split("/") + module = scope_parts[0] + if module in ("", ".", "..") or not re.fullmatch(r"[a-zA-Z0-9_.-]+", module): + raise ValueError("unsafe/missing rsync scope module") + key = (parsed_scope.hostname.lower(), parsed_scope.port or 873) + origins.setdefault(key, set()).add(module) + (output / f"{key[0]}-{key[1]}" / "modules" / module).mkdir(parents=True, exist_ok=True) + if event["kind"] == "view": + for uri in list(views): + if uri.startswith(event["uri"]): + del views[uri] + views.update(event["objects"]) + for uri, ref in views.items(): + parsed = urllib.parse.urlsplit(uri) + parts = parsed.path.lstrip("/").split("/") + if parsed.scheme != "rsync" or parsed.username or parsed.password or parsed.query or parsed.fragment: + raise ValueError("invalid rsync object origin") + if len(parts) < 2 or any(p in ("", ".", "..") or "\x00" in p or "\\" in p for p in parts): + raise ValueError(f"unsafe rsync publication path: {uri}") + hostname, port = parsed.hostname.lower(), parsed.port or 873 + key = (hostname, port) + root = output / f"{hostname}-{port}" + module = parts[0] + if not re.fullmatch(r"[a-zA-Z0-9_.-]+", module): + raise ValueError("unsafe rsync module name") + path = root / "modules" / Path(*parts) + path.parent.mkdir(parents=True, exist_ok=True) + source = state.archive.blob_path(ref["sha256"]) + if source.stat().st_size != ref["size"]: + raise ValueError("rsync blob size mismatch") + if not path.exists(): + # A hard link followed by chmod also changes the archived inode. + shutil.copyfile(source, path) + path.chmod(0o444) + origins.setdefault(key, set()).add(module) + configs = [] + for (hostname, port), modules in origins.items(): + root = output / f"{hostname}-{port}" + config = root / "rsyncd.conf" + lines = [f"address = {mapping[hostname]}", f"port = {port}", "use chroot = no", "read only = yes", + "uid = 65534", "gid = 65534", f"pid file = {root}/rsyncd.pid", f"lock file = {root}/rsyncd.lock", + f"log file = {root}/rsyncd.log", "max connections = 16"] + for module in sorted(modules): + lines += [f"[{module}]", f"path = {root}/modules/{module}"] + config.write_text("\n".join(lines) + "\n") + configs.append(str(config)) + return configs + + +def create_network(mapping: dict) -> None: + existing = subprocess.run(["ip", "netns", "list"], capture_output=True, text=True, check=True, timeout=10).stdout + names = {line.split()[0] for line in existing.splitlines() if line} + if names.intersection({"rp187srv", "rp187rp"}) or Path("/etc/netns/rp187rp").exists(): + raise ValueError("experiment namespace/name already exists; inspect before replacing") + created = [] + try: + for name in ("rp187srv", "rp187rp"): + command("ip", "netns", "add", name) + created.append(name) + command("ip", "-n", "rp187srv", "link", "add", "r187s", "type", "veth", "peer", "name", "r187r", "netns", "rp187rp") + for name, dev, address in (("rp187srv", "r187s", "10.187.0.1/16"), ("rp187rp", "r187r", "10.187.0.2/16")): + command("ip", "-n", name, "addr", "add", address, "dev", dev) + command("ip", "-n", name, "link", "set", dev, "up") + command("ip", "-n", name, "link", "set", "lo", "up") + for address in sorted(set(mapping.values())): + if address in ("10.187.0.1", "10.187.0.2"): + raise ValueError("literal origin collides with namespace gateway") + command("ip", "-n", "rp187srv", "addr", "add", address + "/32", "dev", "lo") + if ipaddress.ip_address(address) not in ipaddress.ip_network("10.187.0.0/16"): + command("ip", "-n", "rp187rp", "route", "add", address + "/32", "via", "10.187.0.1") + folder = Path("/etc/netns/rp187rp") + folder.mkdir(parents=True) + (folder / "hosts").write_text("127.0.0.1 localhost\n" + "".join(f"{address} {host}\n" for host, address in sorted(mapping.items()))) + (folder / "resolv.conf").write_text("nameserver 127.0.0.1\noptions timeout:1 attempts:1\n") + except Exception: + for name in reversed(created): + subprocess.run(["ip", "netns", "delete", name], capture_output=True, timeout=10) + if created and Path("/etc/netns/rp187rp").exists(): + shutil.rmtree("/etc/netns/rp187rp") + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--archive", type=Path, required=True) + parser.add_argument("--epoch", type=Path, required=True) + parser.add_argument("--scope", type=Path) + parser.add_argument("--out", type=Path, required=True) + parser.add_argument("--create-network", action="store_true") + args = parser.parse_args() + if args.scope: + from scope import require_closure + require_closure(args.archive, args.scope) + state = ReplayState(args.archive, args.epoch, args.scope) + hosts = all_hosts(args.archive) + mapping = host_mapping(hosts) + args.out.mkdir(parents=True, exist_ok=True) + tls = tls_assets(args.out, hosts) + epoch_root = args.out / state.epoch_hash + if epoch_root.exists(): + raise ValueError("epoch assets already exist; reuse their manifest or choose a new output") + epoch_root.mkdir() + configs = rsync_tree(state, epoch_root / "rsync", mapping) + http_ports = sorted({key[2] for key in state.entries if key[0] == "http"}) + https_ports = sorted({key[2] for key in state.entries if key[0] == "https"}) + http_ports = sorted(set(http_ports) | {key[2] for key in state.failures if key[0] == "http"}) + https_ports = sorted(set(https_ports) | {key[2] for key in state.failures if key[0] == "https"}) + if set(http_ports).intersection(https_ports): + raise ValueError("HTTP and HTTPS share a port; explicit origin-specific listeners required") + manifest = {"epoch": state.epoch_hash, "archive": str(args.archive), "epoch_path": str(args.epoch), + "hosts": mapping, "tls": tls, "rsync_configs": configs, "http_ports": http_ports, "https_ports": https_ports, + "server_namespace": "rp187srv", "rp_namespace": "rp187rp", "server_cpus": "0", "rp_cpus": "1-3"} + if args.scope: + manifest.update(scope_path=str(args.scope.resolve()), scope_sha256=file_sha256(args.scope)) + atomic_json(epoch_root / "replay.json", manifest) + if args.create_network: + create_network(mapping) + print(json.dumps(manifest)) + + +if __name__ == "__main__": + main() diff --git a/scripts/experiments/reuse_eval/rrdp.py b/scripts/experiments/reuse_eval/rrdp.py new file mode 100644 index 0000000..d9c2d1c --- /dev/null +++ b/scripts/experiments/reuse_eval/rrdp.py @@ -0,0 +1,142 @@ +"""Validate recorded RRDP references and object update semantics without resigning.""" +from __future__ import annotations + +import base64 +import hashlib +import json +from pathlib import Path +import re +import urllib.parse +import xml.etree.ElementTree as ET + +from common import origin + +NS = "{http://www.ripe.net/rpki/rrdp}" +SHA256 = re.compile(r"^[0-9a-fA-F]{64}$") + + +def positive(value: str) -> int: + if not value.isascii() or not value.isdecimal() or int(value) < 1: + raise ValueError(f"invalid positive serial: {value}") + return int(value) + + +def checked_hash(value: str) -> str: + if not SHA256.fullmatch(value): + raise ValueError("invalid reference SHA-256") + return value.lower() + + +def safe_xml(path: Path) -> None: + """Reject non-ASCII/DTD before parsing, without loading a large snapshot.""" + tail = b"" + with path.open("rb") as stream: + for chunk in iter(lambda: stream.read(1024 * 1024), b""): + chunk.decode("ascii") + combined = tail + chunk + if b" dict: + if path.stat().st_size > 8 * 1024**2: + raise ValueError("notification size limit") + safe_xml(path) + root = ET.parse(path).getroot() + if root.tag != NS + "notification" or root.attrib.get("version") != "1": + raise ValueError("invalid notification root/version") + import uuid + session = str(uuid.UUID(root.attrib["session_id"])) + serial = positive(root.attrib["serial"]) + refs, seen, snapshots = [], set(), 0 + for child in root: + if child.tag not in (NS + "snapshot", NS + "delta"): + raise ValueError("unknown notification child") + kind = child.tag.removeprefix(NS) + target = child.attrib["uri"] + if origin(target) != origin(uri): + raise ValueError("cross-origin notification reference") + ref = {"kind": kind, "uri": target, "sha256": checked_hash(child.attrib["hash"])} + if kind == "snapshot": + snapshots += 1 + ref["serial"] = serial + else: + ref["serial"] = positive(child.attrib["serial"]) + if ref["serial"] > serial or ref["serial"] in seen: + raise ValueError("duplicate/future delta serial") + seen.add(ref["serial"]) + refs.append(ref) + if len(refs) > max_refs: + raise ValueError("notification reference limit") + if snapshots != 1: + raise ValueError("notification must contain exactly one snapshot") + return {"session": session, "serial": serial, "references": refs} + + +def object_uri(value: str) -> str: + parsed = urllib.parse.urlsplit(value) + if parsed.scheme != "rsync" or not parsed.hostname or parsed.username or parsed.password or parsed.fragment or parsed.query: + raise ValueError(f"invalid publication URI: {value}") + if not parsed.path or parsed.path.endswith("/"): + raise ValueError("publication URI must name an object") + return value + + +def payload_view(path: Path, kind: str, session: str, serial: int, + base: dict[str, str] | None = None, max_objects: int = 2_000_000) -> dict[str, str]: + safe_xml(path) + view = {} if kind == "snapshot" else dict(base or {}) + iterator = ET.iterparse(path, events=("start", "end")) + _, root = next(iterator) + if (root.tag != NS + kind or root.attrib.get("version") != "1" + or root.attrib.get("session_id", "").lower() != session + or positive(root.attrib["serial"]) != serial): + raise ValueError(f"{kind} session/serial/version mismatch") + seen, depth = set(), 0 + for event, element in iterator: + if event == "start": + depth += 1 + if depth > 1: + raise ValueError("nested RRDP payload element") + continue + if element is root: + break + uri = object_uri(element.attrib["uri"]) + if kind == "snapshot" and uri in seen: + raise ValueError("duplicate URI in RRDP payload") + seen.add(uri) + if len(seen) > max_objects: + raise ValueError("object count limit") + if element.tag == NS + "publish": + previous = element.attrib.get("hash") + if kind == "snapshot" and previous is not None: + raise ValueError("snapshot publish has previous hash") + if kind == "delta": + if previous is None and uri in view: + raise ValueError("delta adds existing object") + if previous is not None and view.get(uri) != checked_hash(previous): + raise ValueError("delta replacement previous hash mismatch") + encoded = "".join((element.text or "").split()) + raw = base64.b64decode(encoded, validate=True) + if not raw: + raise ValueError("empty publish") + view[uri] = hashlib.sha256(raw).hexdigest() + elif element.tag == NS + "withdraw" and kind == "delta": + if view.get(uri) != checked_hash(element.attrib["hash"]): + raise ValueError("delta withdrawal previous hash mismatch") + del view[uri] + else: + raise ValueError("invalid RRDP payload element") + depth -= 1 + element.clear() + root.clear() + return view + + +def view_digest(view: dict[str, str]) -> str: + digest = hashlib.sha256() + for uri, hash_value in sorted(view.items()): + digest.update(json.dumps([uri, hash_value], separators=(",", ":")).encode("ascii")) + digest.update(b"\n") + return digest.hexdigest() diff --git a/scripts/experiments/reuse_eval/run_server.py b/scripts/experiments/reuse_eval/run_server.py new file mode 100644 index 0000000..d4745f3 --- /dev/null +++ b/scripts/experiments/reuse_eval/run_server.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Run HTTP(S) and origin-separated read-only rsync daemons in the server namespace.""" +import argparse +from pathlib import Path +import signal +import subprocess +import sys +import threading + +from common import file_sha256, read_json + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--log", type=Path, required=True) + parser.add_argument("--ready", type=Path, required=True) + args = parser.parse_args() + if args.ready.exists(): + raise ValueError("stale/live readiness file exists; inspect the old server first") + manifest = read_json(args.manifest) + command = [sys.executable, str(Path(__file__).with_name("serve.py")), "--archive", manifest["archive"], + "--epoch", manifest["epoch_path"], "--bind", "0.0.0.0", "--cert", manifest["tls"]["cert"], + "--key", manifest["tls"]["key"], "--log", str(args.log), "--ready", str(args.ready)] + if manifest.get("scope_path"): + if file_sha256(Path(manifest["scope_path"])) != manifest["scope_sha256"]: + raise ValueError("replay scope changed since asset preparation") + command += ["--scope", manifest["scope_path"]] + for scheme in ("http", "https"): + for port in manifest[scheme + "_ports"]: + command += ["--" + scheme + "-port", str(port)] + children = [] + stopped = threading.Event() + signal.signal(signal.SIGTERM, lambda *_: stopped.set()) + signal.signal(signal.SIGINT, lambda *_: stopped.set()) + try: + for config in manifest["rsync_configs"]: + children.append(subprocess.Popen(["rsync", "--daemon", "--no-detach", "--config", config])) + children.append(subprocess.Popen(command)) + while not stopped.wait(0.2): + if any(child.poll() is not None for child in children): + raise RuntimeError("a replay child exited unexpectedly") + finally: + for child in reversed(children): + if child.poll() is None: + child.terminate() + for child in children: + try: + child.wait(timeout=10) + except subprocess.TimeoutExpired: + child.kill() + child.wait(timeout=5) + args.ready.unlink(missing_ok=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/experiments/reuse_eval/scope.py b/scripts/experiments/reuse_eval/scope.py new file mode 100644 index 0000000..d724efb --- /dev/null +++ b/scripts/experiments/reuse_eval/scope.py @@ -0,0 +1,166 @@ +#!/usr/bin/env python3 +"""Declare a fixed successful-repository scope without rewriting the capture.""" +from __future__ import annotations + +import argparse +from pathlib import Path +import re + +from common import atomic_json, file_sha256, read_json + +SCHEMA = "rpki-replay-scope-v1" +COUNTS = {"repositories": 109, "excluded": 8, "epochs": 13, "trust_anchors": 5, "step_ms": 300_000} +TAL_NAMES = {"afrinic.tal", "apnic.tal", "arin.tal", "lacnic.tal", "ripe.tal"} + + +def outside_archive(root: Path, target: Path) -> None: + if target.absolute().is_relative_to(root.absolute()) or target.resolve().is_relative_to(root.resolve()): + raise ValueError("scope and scoped reports must be outside the immutable archive") + + +def describe(root: Path, routes: dict, counts: dict | None = None) -> dict: + """Check metadata eligibility; this deliberately does not claim blob closure.""" + counts = dict(COUNTS if counts is None else counts) + if set(counts) != set(COUNTS) or any(type(n) is not int or n <= 0 for n in counts.values()): + raise ValueError("invalid scope counts") + contract = read_json(root / "contract.json") + capture = read_json(root / "capture.json") + registry = read_json(root / "registry.json") + closure = read_json(root / "closure-report.json") + if closure.get("errors") != []: + raise ValueError("original closure has errors beyond declared coverage gaps") + if len(contract["tals"]) != counts["trust_anchors"]: + raise ValueError("all original trust anchors must remain in scope") + if counts["trust_anchors"] == 5 and {Path(t["path"]).name for t in contract["tals"]} != TAL_NAMES: + raise ValueError("requires the five genuine TAL identities") + sources = {name: file_sha256(root / name) for name in + ("contract.json", "capture.json", "registry.json", "closure-report.json")} + paths = sorted((root / "epochs").glob("epoch_*.json")) + expected_names = [f"epoch_{i:04d}.json" for i in range(counts["epochs"])] + if [p.name for p in paths] != expected_names: + raise ValueError("missing, extra or noncontiguous epochs") + closure_epochs = {e["epoch"]: e for e in closure["epochs"]} + if len(closure_epochs) != counts["epochs"] or len(closure["epochs"]) != counts["epochs"]: + raise ValueError("original closure epoch set mismatch") + if set(routes) - set(expected_names): + raise ValueError("route targets an unknown epoch") + included, excluded, epochs, ta_uris = None, None, [], None + contract_hash = sources["contract.json"] + for index, path in enumerate(paths): + epoch = read_json(path) + present, missing = set(epoch["repositories"]), set(epoch["missing"]) + if (len(present) != counts["repositories"] or len(missing) != counts["excluded"] + or len(missing) != len(epoch["missing"]) or present & missing): + raise ValueError("scope repository/exclusion counts mismatch") + if present | missing != set(registry): + raise ValueError("scope must account for every discovered repository") + if included is None: + included, excluded = present, missing + if present != included or missing != excluded: + raise ValueError("repository scope drifts between epochs") + if epoch["complete"] is not False or epoch["contract_sha256"] != contract_hash: + raise ValueError("original incomplete epoch/contract binding changed") + if epoch.get("blocked_latest_attempts"): + raise ValueError("a selected repository has a blocked latest attempt") + for uri, binding in epoch["repositories"].items(): + latest = epoch["latest_attempts"].get(uri) + if (not latest or latest["complete"] is not True or latest["id"] != binding["id"] + or latest["completed_ms"] != binding["completed_ms"] + or binding["completed_ms"] > epoch["validation_time_ms"]): + raise ValueError("incomplete, stale or future selected observation") + for uri in missing: + if epoch["latest_attempts"].get(uri, {}).get("complete") is not False: + raise ValueError("excluded repository is not a recorded failure") + current_tas = set(epoch["ta_object_events"]) + if len(current_tas) != counts["trust_anchors"] or (ta_uris is not None and current_tas != ta_uris): + raise ValueError("trust-anchor event set changed or was reduced") + ta_uris = current_tas + logical_ms = capture["t0_ms"] + index * counts["step_ms"] + if epoch["validation_time_ms"] != logical_ms: + raise ValueError("logical epoch time mismatch") + original_report = closure_epochs[path.name] + if (original_report.get("errors") != [f"missing repositories: {epoch['missing']}"] + or original_report.get("pass") is not False + or original_report.get("repositories") != counts["repositories"]): + raise ValueError("original closure has unapproved epoch errors") + epoch_routes = routes.get(path.name, {}) + for uri, route in epoch_routes.items(): + if uri not in present or set(route) != {"rsync_uri", "event_id", "http_status"} or route["http_status"] != 503: + raise ValueError("invalid controlled RRDP failure route") + if not re.fullmatch(r"[A-Za-z0-9_-]+", route["event_id"]): + raise ValueError("unsafe event identifier") + if epoch["rsync_view_events"].get(route["rsync_uri"]) != route["event_id"]: + raise ValueError("route is not bound to this epoch's native rsync view") + relative = f"events/{route['event_id']}.json" + event = read_json(root / relative) + if (event["id"] != route["event_id"] or event["uri"] != route["rsync_uri"] + or event.get("source") != "rpki" or event.get("transport") != "rsync" + or event.get("kind") != "view" or event.get("complete") is not True + or event["completed_ms"] > logical_ms + or event["started_ms"] > event["completed_ms"] + or event["completed_ms"] <= logical_ms - counts["step_ms"]): + raise ValueError("route event is incomplete, foreign or outside this step") + sources[relative] = file_sha256(root / relative) + if set(epoch["rsync_view_events"].values()) != {r["event_id"] for r in epoch_routes.values()}: + raise ValueError("every native rsync view requires an explicit route binding") + relative = f"epochs/{path.name}" + sources[relative] = file_sha256(path) + epochs.append({"path": relative, "sha256": sources[relative], "validation_time_ms": logical_ms}) + if capture["end_ms"] != epochs[-1]["validation_time_ms"]: + raise ValueError("capture end does not match the complete target sequence") + return {"schema": SCHEMA, "counts": counts, "source_sha256": sources, "epochs": epochs, + "included_repositories": sorted(included), "excluded_repositories": sorted(excluded), + "trust_anchor_uris": sorted(ta_uris), "routes": routes, + "authorization": "user approved the 109 successful repositories on 2026-11-09", + "coverage": "fixed observed successful repositories; eight gaps remain; not global RPKI coverage", + "failure_policy": "excluded-notifications=503; unknown-entities=404; no upstream; rsync only recorded views", + "route_timing": "controlled immediate RRDP failure; original Internet failure latency is not replayed"} + + +def load_scope(root: Path, scope_path: Path) -> dict: + outside_archive(root, scope_path) + scope = read_json(scope_path) + if scope.get("schema") != SCHEMA: + raise ValueError("unsupported replay scope schema") + expected = describe(root, scope["routes"], scope["counts"]) + if scope != expected: + raise ValueError("scope provenance or membership mismatch") + return scope + + +def select_epoch(root: Path, scope_path: Path, epoch_path: Path) -> dict: + scope = load_scope(root, scope_path) + relative = str(epoch_path.resolve().relative_to(root.resolve())) + if relative not in {e["path"] for e in scope["epochs"]}: + raise ValueError("epoch not selected by this scope") + return scope + + +def require_closure(root: Path, scope_path: Path) -> dict: + scope = load_scope(root, scope_path) + report = read_json(scope_path.with_name("scoped-closure-report.json")) + if (report.get("pass") is not True or report.get("scope_sha256") != file_sha256(scope_path) + or report.get("source_contract_sha256") != scope["source_sha256"]["contract.json"] + or report.get("errors") != [] + or [e.get("epoch") for e in report.get("epochs", [])] != [Path(e["path"]).name for e in scope["epochs"]] + or any(e.get("pass") is not True or e.get("errors") != [] + or e.get("repositories") != scope["counts"]["repositories"] for e in report["epochs"])): + raise ValueError("scoped blob/transition closure is missing, failed or belongs to another scope") + return scope + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--archive", type=Path, required=True) + parser.add_argument("--routes", type=Path, required=True) + parser.add_argument("--out", type=Path, required=True) + args = parser.parse_args() + outside_archive(args.archive, args.out) + if args.out.exists(): + raise ValueError("scope exists; refusing to replace its provenance") + atomic_json(args.out, describe(args.archive, read_json(args.routes))) + print("Scope metadata eligible: 109 repositories, 8 excluded, 13 epochs, 5 TAs; run scoped verify next.") + + +if __name__ == "__main__": + main() diff --git a/scripts/experiments/reuse_eval/sequence_matrix.py b/scripts/experiments/reuse_eval/sequence_matrix.py new file mode 100644 index 0000000..0717217 --- /dev/null +++ b/scripts/experiments/reuse_eval/sequence_matrix.py @@ -0,0 +1,449 @@ +#!/usr/bin/env python3 +"""Full five-profile, thirteen-epoch correctness pilot on the dedicated 186 host. + +This is a pilot controller. Missing sync-union/payload-ready instrumentation +explicitly prevents publishing a seven-metric performance result. +""" +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import re +import shutil +import signal +import socket +import subprocess +import sys +import time +import uuid + +from cache_size import account, profile_from_contract +from common import atomic_json, file_sha256, read_json +from prepare_replay import all_hosts, create_network, host_mapping +from scope import COUNTS, outside_archive, require_closure +from smoke_matrix import cache_counters, command_run, require_comparison, snapshot_pre_state + +PROFILE_FLAGS = { + "baseline": [], "signature": ["--enable-crypto-signature-cache"], + "object": ["--enable-roa-validation-cache", "--enable-child-certificate-validation-cache"], + "pp": ["--enable-publication-point-validation-cache"], + "hybrid": ["--enable-roa-validation-cache", "--enable-child-certificate-validation-cache", + "--enable-publication-point-validation-cache"], +} +EXPECTED_HOST = "iZrj9bs1xzk2i95si3ghnlZ" + + +def compare_profile_contracts(actual: dict, baseline: dict) -> dict: + """Compare policy/time/build and fallback choices across independent caches. + + Fallback hashes bind a strategy's own VCIR history, including its last fresh + validation time. They must match that strategy's T2 exactly; they are not + shared configuration. CIR/reject/CCR comparisons still gate every row. + """ + def selections(contract: dict) -> list[dict]: + rows = contract.get("fallbackReplaySelections", []) + if not isinstance(rows, list): + raise ValueError("fallback bindings must be a list") + uris = [] + for row in rows: + if (not isinstance(row, dict) + or set(row) != {"manifestRsyncUri", "vcirSha256", "reuseIdentitySha256"} + or not isinstance(row["manifestRsyncUri"], str) + or not row["manifestRsyncUri"].startswith("rsync://") + or any(not isinstance(row[k], str) or re.fullmatch(r"[0-9a-f]{64}", row[k]) is None + for k in ("vcirSha256", "reuseIdentitySha256"))): + raise ValueError("invalid fallback cache binding") + uris.append(row["manifestRsyncUri"]) + if uris != sorted(set(uris)): + raise ValueError("fallback bindings must be sorted and unique") + return rows + + left, right = selections(baseline), selections(actual) + shared = lambda contract: {k: v for k, v in contract.items() + if k not in ("cache", "fallbackReplaySelections")} + if shared(actual) != shared(baseline): + raise ValueError("non-cache validation configuration differs from baseline") + if [r["manifestRsyncUri"] for r in left] != [r["manifestRsyncUri"] for r in right]: + raise ValueError("fallback Manifest selections differ from baseline") + return {"schema": "rpki-reuse-cross-profile-contract-v1", "pass": True, + "configuration_match": True, "fallback_manifests_match": True, + "baseline_fallback": left, "actual_fallback": right, + "binding_scope": "exact VCIR/identity hashes within each strategy T1/T2"} + + +def require_t2_fallback_bindings(contract: dict, equivalence: dict) -> None: + expected = contract.get("fallbackReplaySelections", []) + fallback = equivalence.get("fallback", {}) + if (fallback.get("matches") is not True or fallback.get("expected") != expected + or fallback.get("actual") != expected or fallback.get("missing") != [] + or fallback.get("unexpected") != []): + raise ValueError("T1/T2 exact fallback cache bindings differ") + + +def call(command: list[str], **kwargs) -> subprocess.CompletedProcess: + return subprocess.run(command, check=True, capture_output=True, text=True, timeout=kwargs.pop("timeout", 30), **kwargs) + + +def resource_guard(output: Path) -> dict: + free = shutil.disk_usage(output).free + inodes = os.statvfs("/").f_favail + if free < 150 * 1024**3 or inodes < 10_000: + raise ValueError(f"resource guard: data free={free}, root inodes free={inodes}") + return {"data_free_bytes": free, "root_free_inodes": inodes} + + +def systemd_measure(command: list[str], run: Path, env: dict, timeout: int) -> dict: + """Keep the completed cgroup alive until CPUUsageNSec/MemoryPeak are read.""" + unit = "rpki187-pilot-" + uuid.uuid4().hex + env_args = ["/usr/bin/env"] + for name in ("http_proxy", "https_proxy", "all_proxy", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"): + env_args += ["-u", name] + env_args += ["TMPDIR=" + env["TMPDIR"], "LC_ALL=C"] + launcher = ["systemd-run", "--quiet", "--unit", unit, "--service-type=exec", + "-p", "RemainAfterExit=yes", "-p", "MemoryAccounting=yes", "-p", "CPUAccounting=yes", + "-p", "AllowedCPUs=1-3", "-p", "MemoryMax=5G", "-p", f"RuntimeMaxSec={timeout}", + "-p", "StandardOutput=file:" + str(run / "stdout.log"), + "-p", "StandardError=file:" + str(run / "stderr.log"), + "ip", "netns", "exec", "rp187rp"] + env_args + [ + "/usr/bin/time", "-v", "-o", str(run / "process-time.txt")] + command + atomic_json(run / "launcher.json", launcher) + began = time.monotonic_ns() + props = {} + try: + call(launcher) + deadline = time.monotonic() + timeout + while True: + raw = call(["systemctl", "show", unit, "-p", "ActiveState", "-p", "SubState", "-p", "Result", + "-p", "ExecMainStatus", "-p", "ExecMainCode", "-p", "ExecMainExitTimestampMonotonic", + "-p", "CPUUsageNSec", "-p", "MemoryPeak", "-p", "ControlGroup"]).stdout + props = dict(line.split("=", 1) for line in raw.splitlines() if "=" in line) + if props.get("ActiveState") in ("failed", "inactive") or props.get("SubState") == "exited": + break + if time.monotonic() >= deadline: + raise TimeoutError(f"RP unit timed out: {unit}") + time.sleep(0.25) + if (props.get("Result") != "success" or props.get("ExecMainCode") != "1" + or props.get("ExecMainStatus") != "0" or props.get("SubState") != "exited"): + raise RuntimeError(f"RP unit failed: {props}") + cpu, memory = int(props["CPUUsageNSec"]), int(props["MemoryPeak"]) + if cpu < 0 or memory <= 0 or cpu >= 2**63 or memory >= 2**63: + raise ValueError("cgroup accounting is unavailable") + result = {"unit": unit, "properties": props, "cpu_ns": cpu, "memory_peak_bytes": memory, + "controller_observed_wall_ns": time.monotonic_ns() - began, + "controller_trigger_monotonic_ns": began, + "boundary": "entire RP cgroup including subprocesses; excludes replay server; wall includes unit launch/poll"} + atomic_json(run / "process-resource.json", result) + return result + finally: + atomic_json(run / "systemd-final.json", props) + subprocess.run(["systemctl", "stop", unit], capture_output=True, timeout=30, check=True) + + +def tal_arguments(root: Path, contract: dict, epoch: dict, run: Path) -> list[str]: + result, selected = [], set() + archive_blobs = root / "blobs/sha256" + for tal in contract["tals"]: + path = root / "inputs" / Path(tal["path"]).name + if file_sha256(path) != tal["sha256"]: + raise ValueError("pinned TAL changed") + uris = [line.strip() for line in path.read_text().splitlines() if line.strip().startswith(("https://", "rsync://"))] + matches = [uri for uri in uris if uri in epoch["ta_object_events"]] + if len(matches) != 1 or matches[0] in selected: + raise ValueError("TAL must bind exactly one distinct archived TA endpoint") + uri = matches[0] + selected.add(uri) + event = read_json(root / "events" / f"{epoch['ta_object_events'][uri]}.json") + if (event["uri"] != uri or event["complete"] is not True or event["transport"] != "http" + or event["completed_ms"] > epoch["validation_time_ms"]): + raise ValueError("TA event binding failed") + ref = event["body"] + source = archive_blobs / ref["sha256"][:2] / ref["sha256"] + if source.stat().st_size != ref["size"] or file_sha256(source) != ref["sha256"]: + raise ValueError("TA bytes changed") + target = run / "ta" / path.with_suffix(".cer").name + target.parent.mkdir(exist_ok=True) + shutil.copyfile(source, target) + result += ["--tal-path", str(path), "--ta-path", str(target), "--cir-tal-uri", tal["cir_tal_uri"]] + if selected != set(epoch["ta_object_events"]): + raise ValueError("not every real TA is consumed") + return result + + +def rp_command(binary: Path, private: Path, run: Path, manifest: dict, logical_ms: int, + profile: str, tals: list[str], formal_metrics: bool = False) -> list[str]: + logical = datetime.fromtimestamp(logical_ms // 1000, timezone.utc).isoformat().replace("+00:00", "Z") + return [str(binary), "--db", str(private / "state/db"), *tals, "--http-root-cert", manifest["tls"]["ca"], + "--parallel-max-repo-sync-workers-global", "3", "--parallel-phase2-object-workers", "3", + "--rsync-scope", "module-root", "--max-ca-depth", "32", "--http-timeout-secs", "30", "--rsync-timeout-secs", "30", + "--validation-time", logical, "--validation-contract-out", str(run / "contract.json"), + "--report-json", str(run / "report.json"), "--report-json-compact", "--ccr-out", str(run / "result.ccr"), + "--cir-enable", "--cir-out", str(run / "input.cir"), "--rsync-mirror-root", str(private / "mirror"), + "--analyze", "--analysis-out", str(run / "analysis"), *PROFILE_FLAGS[profile]] + ( + ["--evaluation-metrics-out", str(run / "evaluation.json")] if formal_metrics else []) + + +def require_ready(path: Path, server: subprocess.Popen, epoch_hash: str, scope_hash: str) -> dict: + deadline = time.monotonic() + 60 + while time.monotonic() < deadline: + if server.poll() is not None: + raise RuntimeError("replay server exited before readiness") + if path.exists(): + ready = read_json(path) + if ready.get("epoch") != epoch_hash or ready.get("scope") != scope_hash: + raise ValueError("server readiness belongs to a different epoch/scope") + return ready + time.sleep(0.1) + raise TimeoutError("replay server readiness timeout") + + +def require_transport(table: dict, scope: dict, epoch_name: str) -> None: + routes = scope["routes"].get(epoch_name, {}) + if set(table["rrdp"]) != set(scope["included_repositories"]) | set(scope["excluded_repositories"]): + raise ValueError("native RP transport set differs from the declared repository scope") + for uri in scope["included_repositories"]: + outcome = table["rrdp"][uri] + if uri in routes: + if not isinstance(outcome, dict) or "Failure" not in outcome: + raise ValueError("native RP did not reproduce the declared RRDP failure") + if table["rsync"].get(routes[uri]["rsync_uri"]) != "Success": + raise ValueError("native RP did not use the bound successful rsync view") + elif outcome != "Success": + raise ValueError(f"an included RRDP repository failed: {uri}") + for uri in scope["excluded_repositories"]: + if not isinstance(table["rrdp"][uri], dict) or "Failure" not in table["rrdp"][uri]: + raise ValueError("an excluded repository unexpectedly succeeded") + + +def payload_counts(run: Path) -> dict: + # Reading the complete ~300 MB JSON report into Python can consume gigabytes. + # The native comparator/T2 read the canonical artifacts independently. + stdout = (run / "stdout.log").read_text(errors="replace") + pairs = re.findall(r"^(vrps|aspas|audit_publication_points)=(\d+)$", stdout, re.MULTILINE) + values = {key: int(value) for key, value in pairs} + if len(pairs) != 3 or set(values) != {"vrps", "aspas", "audit_publication_points"} or min(values.values()) <= 0: + raise ValueError("full-scope payload counters are missing, duplicated or empty") + return {"vrps": values["vrps"], "aspas": values["aspas"], "publication_points": values["audit_publication_points"]} + + +def run_pilot(config: dict) -> dict: + if socket.gethostname() != EXPECTED_HOST or os.geteuid() != 0: + raise ValueError("pilot execution is restricted to root on the designated 186 host") + root, scope_path, output = (Path(config[k]).resolve() for k in ("archive", "scope", "out")) + outside_archive(root, output) + if not str(output).startswith("/data/rpki187/20261109/results/"): + raise ValueError("pilot outputs must be in the dedicated persistent experiment root") + output.mkdir(parents=True, exist_ok=False) + scope = require_closure(root, scope_path) + if scope["counts"] != COUNTS: + raise ValueError("pilot requires the user-approved 109/8/13/5 scope") + if file_sha256(scope_path) != config["expected_scope_sha256"]: + raise ValueError("scope differs from the reviewed local metadata selection") + source_tools = {name: Path(config[name]).resolve() for name in ("binary", "ccr_compare", "cir_compare", "db_stats")} + if file_sha256(source_tools["binary"]) != config["expected_binary_sha256"]: + raise ValueError("RP binary differs from the reviewed frozen build") + (output / "bin").mkdir() + tools = {} + for name, source in source_tools.items(): + target = output / "bin" / name + shutil.copyfile(source, target) + if file_sha256(target) != file_sha256(source): + raise ValueError("copied measurement tool changed") + target.chmod(0o555) + tools[name] = target + env = {k: v for k, v in os.environ.items() if k.lower() not in ("http_proxy", "https_proxy", "all_proxy")} + script = Path(__file__).resolve().parent + formal = config.get("formal_metrics", False) + if type(formal) is not bool: + raise ValueError("formal_metrics must be boolean") + order = config.get("profile_order", list(PROFILE_FLAGS)) + if len(order) != 5 or set(order) != set(PROFILE_FLAGS) or order[0] != "baseline": + raise ValueError("profile order must cover all five profiles once with baseline first") + summary = {"status": "running", "pass": False, "purpose": "full-109-repository-all5-formal-repeat" if formal else "full-109-repository-all5-correctness-pilot", + "performance_ready": False, "missing_formal_metrics": [] if formal else ["sync-wall-union", "payload-ready-publication"], + "scope_sha256": file_sha256(scope_path), "tool_sha256": {k: file_sha256(p) for k, p in tools.items()}, + "scripts_sha256": {p.name: file_sha256(p) for p in sorted(script.glob("*.py"))}, + "config": config, "runs": [], "initial_resources": resource_guard(output)} + atomic_json(output / "summary.json", summary) + panda_was_active = subprocess.run(["systemctl", "is-active", "--quiet", "panda-rpki.service"]).returncode == 0 + namespaces_owned = False + panda_stopped = False + try: + if panda_was_active: + # Mark before requesting stop: a timed-out client may leave a completed stop job. + panda_stopped = True + call(["systemctl", "stop", "panda-rpki.service"], timeout=120) + container = call(["docker", "inspect", "--format", "{{.State.Running}}", "panda-rpki-validator-1"]).stdout.strip() + if container != "false": + raise ValueError("original Panda container is still running") + competitors = subprocess.run(["pgrep", "-x", "rpki|rpki-client|routinator"], capture_output=True, text=True) + if competitors.returncode == 0: + raise ValueError("competing RP processes are present") + create_network(host_mapping(all_hosts(root))) + namespaces_owned = True + contract = read_json(root / "contract.json") + baseline_contracts = {} + for profile in order: + private = output / profile + (private / "state").mkdir(parents=True) + (private / "tmp").mkdir() + env["TMPDIR"] = str(private / "tmp") + for step, selection in enumerate(scope["epochs"]): + resources = resource_guard(output) + if ({k: file_sha256(p) for k, p in tools.items()} != summary["tool_sha256"] + or {p.name: file_sha256(p) for p in sorted(script.glob("*.py"))} != summary["scripts_sha256"]): + raise ValueError("tools or controller source changed during the pilot") + epoch_path = root / selection["path"] + epoch = read_json(epoch_path) + run = private / f"step_{step:04d}" + run.mkdir() + assets = output / "assets" + epoch_assets = assets / selection["sha256"] + manifest_path = epoch_assets / "replay.json" + if not manifest_path.exists(): + prepared = call([sys.executable, str(script / "prepare_replay.py"), "--archive", str(root), + "--scope", str(scope_path), "--epoch", str(epoch_path), "--out", str(assets)]) + atomic_json(run / "prepare-command.json", {"stdout": prepared.stdout}) + manifest = read_json(manifest_path) + if manifest["epoch"] != selection["sha256"] or manifest["scope_sha256"] != summary["scope_sha256"]: + raise ValueError("prepared replay manifest changed") + ready = run / "server-ready.json" + server_command = ["ip", "netns", "exec", "rp187srv", "taskset", "-c", "0", sys.executable, + str(script / "run_server.py"), "--manifest", str(manifest_path), "--log", + str(run / "server-requests.jsonl"), "--ready", str(ready)] + atomic_json(run / "server-command.json", server_command) + with (run / "server.log").open("wb") as log: + server = subprocess.Popen(server_command, stdout=log, stderr=log, start_new_session=True, env=env) + try: + ready_proof = require_ready(ready, server, selection["sha256"], summary["scope_sha256"]) + atomic_json(run / "server-ready-proof.json", ready_proof) + proof = snapshot_pre_state(private / "state", run / "pre-state") + proof["method"] = "closed-complete-state-copy-before-T1" + atomic_json(run / "pre-state.json", proof) + command = rp_command(tools["binary"], private, run, manifest, epoch["validation_time_ms"], + profile, tal_arguments(root, contract, epoch, run), formal_metrics=formal) + atomic_json(run / "command.json", command) + atomic_json(run / "t1-start.json", {"started_unix_ns": time.time_ns()}) + measured = systemd_measure(command, run, env, config.get("run_timeout_secs", 1800)) + if server.poll() is not None: + raise RuntimeError("replay server exited during T1") + finally: + if server.poll() is None: + os.killpg(server.pid, signal.SIGTERM) + try: + server.wait(timeout=20) + except subprocess.TimeoutExpired: + os.killpg(server.pid, signal.SIGKILL) + server.wait(timeout=10) + actual = read_json(run / "contract.json") + logical = datetime.fromtimestamp(epoch["validation_time_ms"] // 1000, timezone.utc).isoformat().replace("+00:00", "Z") + if (profile_from_contract(actual)[0] != profile or actual["validationTime"] != logical + or actual["binarySha256"] != summary["tool_sha256"]["binary"]): + raise ValueError("effective profile, time or binary mismatch") + if profile == "baseline": + baseline_contracts[step] = actual + atomic_json(run / "contract-comparison.json", + compare_profile_contracts(actual, baseline_contracts[step])) + anchors = re.findall(r"wrote CIR: .*?trust_anchors=(\d+)", (run / "stderr.log").read_text(errors="replace")) + if not anchors or int(anchors[-1]) != 5: + raise ValueError("full five-TA/payload acceptance failed") + counts = payload_counts(run) + baseline = output / "baseline" / run.name + for kind, command in ( + ("ccr", [str(tools["ccr_compare"]), "--source-ccr", str(baseline / "result.ccr"), + "--verification-ccr", str(run / "result.ccr"), "--out-json", str(run / "ccr-comparison.json")]), + ("cir", [str(tools["cir_compare"]), "--ours-cir", str(baseline / "input.cir"), + "--peer-cir", str(run / "input.cir"), "--out-json", str(run / "cir-comparison.json")])): + command_run(command, run / f"{kind}-compare.stdout", run / f"{kind}-compare.stderr", env, 1800) + require_comparison(run / f"{kind}-comparison.json", kind) + command_run([str(tools["db_stats"]), "--db", str(private / "state/db"), "--exact"], + run / "db-stats.txt", run / "db-stats.stderr", env, 1800) + size = account(private / "state/db", run / "db-stats.txt", run / "contract.json") + atomic_json(run / "cache-size.json", size) + benchmark = private / f"benchmark_{step:04d}" + benchmark_command = [str(tools["binary"]), "--validation-benchmark", "--source-run", str(run), + "--source-state", str(private / "state/db"), "--pre-state", + "empty" if step == 0 else str(run / "pre-state/db"), "--out", str(benchmark)] + atomic_json(run / "benchmark-command.json", benchmark_command) + benchmark_process = run / "benchmark-process" + benchmark_process.mkdir() + benchmark_measured = systemd_measure(benchmark_command, benchmark_process, env, config.get("run_timeout_secs", 1800)) + equivalence = read_json(benchmark / "equivalence.json") + require_t2_fallback_bindings(actual, equivalence) + overlay = read_json(benchmark / "input-overlay.json") + if (equivalence.get("pass") is not True or overlay.get("pre_state_files_verified") is not True + or overlay["overlay"].get("background_io_drained") is not True + or overlay["overlay"]["cache_before"] != overlay["overlay"]["cache_after"]): + raise ValueError("T2 equivalence, pre-state or input-drain proof failed") + require_transport(overlay["transport_table"], scope, epoch_path.name) + counters = {"t1": cache_counters(run), "t2": cache_counters(benchmark)} + atomic_json(run / "cache-counters.json", counters) + if counters["t1"] != counters["t2"]: + raise ValueError("T1/T2 hit/miss behavior differs") + metrics = None + if formal: + from formal_metrics import collect + metrics = collect(run, benchmark, measured, size, profile, overlay["transport_table"]) + summary["runs"].append({"profile": profile, "step": step, "path": str(run), "pass": True, + "counts": counts, "resources_before": resources, "process": measured, + "benchmark_process": benchmark_measured, + "engine": read_json(benchmark / "engine-timing.json"), + "cache_size_bytes": size["required_serialized_bytes"], "seven_metrics": metrics}) + atomic_json(output / "summary.json", summary) + # These two controller-created scratch DBs are reproducible; keep all proof files, + # authoritative T1 state, original captures and complete T1 outputs. + shutil.rmtree(run / "pre-state") + shutil.rmtree(benchmark / "state") + summary.update({"status": "completed", "pass": True, "performance_ready": formal}) + except BaseException as exc: + summary.update(status="failed", error=f"{type(exc).__name__}: {exc}") + raise + finally: + restoration = {} + if namespaces_owned: + for name in ("rp187rp", "rp187srv"): + try: + restoration[name] = subprocess.run(["ip", "netns", "delete", name], capture_output=True, timeout=30).returncode + except Exception as exc: + restoration[name] = str(exc) + try: + shutil.rmtree("/etc/netns/rp187rp") + except Exception as exc: + restoration["namespace_hosts_error"] = str(exc) + if panda_stopped: + try: + restored = subprocess.run(["systemctl", "start", "panda-rpki.service"], capture_output=True, timeout=60) + restoration["panda_start_exit"] = restored.returncode + restoration["panda_active"] = subprocess.run(["systemctl", "is-active", "--quiet", "panda-rpki.service"], timeout=15).returncode == 0 + container = subprocess.run(["docker", "inspect", "--format", "{{.State.Running}}", "panda-rpki-validator-1"], + capture_output=True, text=True, timeout=15) + restoration["panda_container_running"] = container.returncode == 0 and container.stdout.strip() == "true" + except Exception as exc: + restoration["panda_restore_error"] = str(exc) + summary["restoration"] = restoration + atomic_json(output / "summary.json", summary) + if (any(restoration.get(name, 0) != 0 for name in ("rp187rp", "rp187srv")) + or "namespace_hosts_error" in restoration or "panda_restore_error" in restoration + or (panda_stopped and (restoration.get("panda_active") is not True + or restoration.get("panda_container_running") is not True))): + summary.update({"pass": False, "status": "restoration_failed"}) + atomic_json(output / "summary.json", summary) + raise RuntimeError("pilot restoration requires attention; see summary.json") + return summary + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--config", type=Path, required=True) + args = parser.parse_args() + def interrupted(*_): + raise KeyboardInterrupt("pilot controller interrupted") + signal.signal(signal.SIGTERM, interrupted) + result = run_pilot(read_json(args.config)) + print(json.dumps({"pass": result["pass"], "runs": len(result["runs"]), "performance_ready": result["performance_ready"]})) + + +if __name__ == "__main__": + main() diff --git a/scripts/experiments/reuse_eval/serve.py b/scripts/experiments/reuse_eval/serve.py new file mode 100644 index 0000000..a3a66e5 --- /dev/null +++ b/scripts/experiments/reuse_eval/serve.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python3 +"""Serve one immutable epoch using archived entity bytes, without upstream access.""" +from __future__ import annotations + +import argparse +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +import json +from pathlib import Path +import signal +import ssl +import threading +import urllib.parse + +from common import Archive, atomic_json, digest_bytes, file_sha256, now_ms, origin, read_json + + +def uri_key(uri: str) -> tuple: + scheme, hostname, port = origin(uri) + parsed = urllib.parse.urlsplit(uri) + return scheme, hostname, port, parsed.path or "/", parsed.query + + +class ReplayState: + def __init__(self, root: Path, epoch_path: Path, scope_path: Path | None = None): + self.archive = Archive(root, read_only=True) + self.epoch_path = epoch_path + self.epoch_hash = digest_bytes(epoch_path.read_bytes()) + self.epoch = read_json(epoch_path) + if self.epoch.get("contract_sha256"): + if file_sha256(root / "contract.json") != self.epoch["contract_sha256"]: + raise ValueError("capture contract hash mismatch") + self.scope = None + self.scope_hash = None + self.failures = {} + if scope_path is not None: + from scope import select_epoch + self.scope = select_epoch(root, scope_path, epoch_path) + self.scope_hash = file_sha256(scope_path) + self.failures = {uri_key(uri): 503 for uri in self.scope["excluded_repositories"]} + self.failures.update({uri_key(uri): route["http_status"] + for uri, route in self.scope["routes"].get(epoch_path.name, {}).items()}) + if not self.epoch["complete"] and self.scope is None: + raise ValueError("cannot serve an incomplete epoch") + self.entries = {} + for uri, binding in self.epoch["repositories"].items(): + observation = read_json(root / "observations" / f"{binding['id']}.json") + if not observation["complete"] or observation["completed_ms"] > self.epoch["validation_time_ms"]: + raise ValueError("incomplete/future observation") + if any(observation[key] != binding[key] for key in ("session", "serial", "notification", "view", "completed_ms")): + raise ValueError("epoch binding mismatch") + self.add(uri, binding["notification"], "application/xml") + for ref in observation["references"]: + if ref["available"]: + self.add(ref["uri"], {"sha256": ref["sha256"], "size": ref["size"]}, "application/xml") + self.rsync_events = [] + for uri, event_id in self.epoch["ta_object_events"].items(): + event = read_json(root / "events" / f"{event_id}.json") + self.check_event(event, uri) + if event["transport"] == "http": + self.add(uri, event["body"], "application/octet-stream") + else: + self.rsync_events.append(event) + for uri, event_id in self.epoch["rsync_view_events"].items(): + event = read_json(root / "events" / f"{event_id}.json") + self.check_event(event, uri) + self.rsync_events.append(event) + + def check_event(self, event: dict, uri: str) -> None: + if event["uri"] != uri or not event["complete"] or event["completed_ms"] > self.epoch["validation_time_ms"]: + raise ValueError("invalid selected transport event") + + def add(self, uri: str, ref: dict, content_type: str) -> None: + key = uri_key(uri) + existing = self.entries.get(key) + if existing and existing["sha256"] != ref["sha256"]: + raise ValueError(f"conflicting contents for one epoch URI: {uri}") + path = self.archive.blob_path(ref["sha256"]) + if not path.is_file() or path.stat().st_size != ref["size"]: + raise ValueError(f"missing/truncated blob: {uri}") + self.entries[key] = {**ref, "content_type": content_type} + + +def handler_for(state: ReplayState, scheme: str, log_path: Path | None = None): + log_lock = threading.Lock() + class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + def log_message(self, *_): + pass + + def do_HEAD(self): + self.handle_entity(head=True) + + def do_GET(self): + self.handle_entity(head=False) + + def handle_entity(self, head: bool): + uri = f"{scheme}://{self.headers.get('Host', '')}{self.path}" + started = now_ms() + ref = None + try: + if not self.path.startswith("/") or self.path.startswith("//"): + raise ValueError("origin-form request required") + ref = state.entries.get(uri_key(uri)) + status = state.failures.get(uri_key(uri), 404 if ref is None else 200) + if status != 200: + ref = None + except ValueError: + status = 400 + etag = f'"sha256:{ref["sha256"]}"' if ref else None + if status == 200 and self.headers.get("If-None-Match") == etag: + status = 304 + self.send_response(status) + self.send_header("Content-Length", str(ref["size"] if status == 200 else 0)) + self.send_header("X-RPKI-Epoch", state.epoch_hash) + if state.scope_hash: + self.send_header("X-RPKI-Scope", state.scope_hash) + if ref: + self.send_header("ETag", etag) + self.send_header("Content-Type", ref["content_type"]) + self.end_headers() + try: + if status == 200 and not head: + with state.archive.blob_path(ref["sha256"]).open("rb") as stream: + while chunk := stream.read(65536): + self.wfile.write(chunk) + except (BrokenPipeError, ConnectionResetError): + pass + if log_path: + event = {"uri": uri, "status": status, "sha256": ref["sha256"] if ref else None, + "epoch": state.epoch_hash, "scope": state.scope_hash, + "controlled_failure": uri_key(uri) in state.failures if status != 400 else False, + "started_ms": started, "completed_ms": now_ms()} + with log_lock, log_path.open("a", encoding="utf-8") as stream: + stream.write(json.dumps(event, separators=(",", ":")) + "\n") + return Handler + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--archive", type=Path, required=True) + parser.add_argument("--epoch", type=Path, required=True) + parser.add_argument("--scope", type=Path) + parser.add_argument("--bind", default="127.0.0.1") + parser.add_argument("--http-port", type=int, action="append", default=[]) + parser.add_argument("--https-port", type=int, action="append", default=[]) + parser.add_argument("--cert", type=Path) + parser.add_argument("--key", type=Path) + parser.add_argument("--log", type=Path, required=True) + parser.add_argument("--ready", type=Path, required=True) + args = parser.parse_args() + if args.scope: + from scope import require_closure + require_closure(args.archive, args.scope) + state = ReplayState(args.archive, args.epoch, args.scope) + if not args.http_port and not args.https_port: + parser.error("at least one server port is required") + servers, listeners = [], [] + pairs = [(scheme, port) for scheme, ports in (("http", args.http_port), ("https", args.https_port)) for port in ports] + for scheme, port in pairs: + server = ThreadingHTTPServer((args.bind, port), handler_for(state, scheme, args.log)) + if scheme == "https": + context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + context.minimum_version = ssl.TLSVersion.TLSv1_2 + context.load_cert_chain(args.cert, args.key) + server.socket = context.wrap_socket(server.socket, server_side=True) + threading.Thread(target=server.serve_forever, daemon=True).start() + servers.append(server) + listeners.append({"scheme": scheme, "address": server.server_address}) + atomic_json(args.ready, {"epoch": state.epoch_hash, "scope": state.scope_hash, + "listeners": listeners, "http_entities": len(state.entries)}) + stopped = threading.Event() + signal.signal(signal.SIGTERM, lambda *_: stopped.set()) + signal.signal(signal.SIGINT, lambda *_: stopped.set()) + stopped.wait() + for server in servers: + server.shutdown() + server.server_close() + args.ready.unlink(missing_ok=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/experiments/reuse_eval/single_formal.py b/scripts/experiments/reuse_eval/single_formal.py new file mode 100644 index 0000000..2a2090c --- /dev/null +++ b/scripts/experiments/reuse_eval/single_formal.py @@ -0,0 +1,228 @@ +#!/usr/bin/env python3 +"""Run one complete formal matrix using a preserved, byte-bound pilot.""" +from __future__ import annotations + +import argparse +import csv +from datetime import datetime, timezone +import json +import math +import os +from pathlib import Path +import signal +import socket +import statistics + +from cache_size import profile_from_contract +from campaign import SCALARS, require_matrix +from common import atomic_json, file_sha256, read_json +from sequence_matrix import (EXPECTED_HOST, PROFILE_FLAGS, compare_profile_contracts, + require_t2_fallback_bindings, resource_guard, run_pilot) +from smoke_matrix import cache_counters, require_comparison + + +def require_row_proofs(row: dict, matrix: Path) -> None: + """Re-read compact proofs; never open the large report/event streams.""" + profile, step = row['profile'], row['step'] + run = matrix / profile / f'step_{step:04d}' + benchmark = matrix / profile / f'benchmark_{step:04d}' + if row.get('pass') is not True or row.get('path') != str(run): + raise ValueError('row identity or success proof differs') + if any(type(row.get('counts', {}).get(k)) is not int or row['counts'][k] <= 0 + for k in ['vrps', 'aspas', 'publication_points']): + raise ValueError('empty or missing payload counts') + require_comparison(run / 'ccr-comparison.json', 'ccr') + require_comparison(run / 'cir-comparison.json', 'cir') + equivalent = read_json(benchmark / 'equivalence.json') + if (equivalent.get('pass') is not True or equivalent.get('inputs_match') is not True + or equivalent.get('ccr', {}).get('stateDigestMatch') is not True): + raise ValueError('T1/T2 input or CCR equivalence failed') + contract = read_json(run / 'contract.json') + baseline = read_json(matrix / 'baseline' / run.name / 'contract.json') + if read_json(run / 'contract-comparison.json') != compare_profile_contracts(contract, baseline): + raise ValueError('cross-profile contract proof differs from recomputation') + require_t2_fallback_bindings(contract, equivalent) + if profile_from_contract(contract)[0] != profile or contract['cache']['transportPrefetch'] is not False: + raise ValueError('effective reuse profile or disabled prefetch differs') + overlay = read_json(benchmark / 'input-overlay.json') + proof = overlay.get('overlay', {}) + if (overlay.get('pre_state_files_verified') is not True or proof.get('background_io_drained') is not True + or proof.get('cache_before') != proof.get('cache_after')): + raise ValueError('pre-T1 cache or frozen-input overlay proof failed') + counters = read_json(run / 'cache-counters.json') + if counters['t1'] != counters['t2'] or counters['t1'] != cache_counters(run) or counters['t2'] != cache_counters(benchmark): + raise ValueError('T1/T2 raw cache hit/miss counters differ') + if read_json(benchmark / 'engine-timing.json') != row['engine']: + raise ValueError('engine timing differs from source') + if read_json(run / 'cache-size.json')['required_serialized_bytes'] != row['cache_size_bytes']: + raise ValueError('cache size differs from source') + + +def require_prerequisite(config: dict) -> dict: + """Bind an existing pilot to this identical RP and unchanged run engine.""" + path = Path(config['pilot_summary']) + if file_sha256(path) != config['expected_pilot_summary_sha256']: + raise ValueError('preserved pilot summary hash differs') + pilot = read_json(path) + repeat = config['repeat'] + require_matrix(pilot, repeat['expected_scope_sha256'], formal=False) + if (repeat.get('formal_metrics') is not True + or repeat.get('profile_order') != list(PROFILE_FLAGS) + or repeat.get('run_timeout_secs') != 1800): + raise ValueError('requires exactly one full formal matrix under the original execution policy') + for key in ['archive', 'scope', 'expected_binary_sha256', 'expected_scope_sha256']: + if repeat[key] != pilot['config'][key]: + raise ValueError('formal input/build differs from preserved pilot: ' + key) + if pilot['tool_sha256'] != config['expected_tools_sha256']: + raise ValueError('preserved pilot tool hashes differ') + for name, digest in config['expected_tools_sha256'].items(): + if file_sha256(Path(repeat[name])) != digest: + raise ValueError('formal tool differs from preserved pilot: ' + name) + if file_sha256(path.parent / 'bin/binary') != repeat['expected_binary_sha256']: + raise ValueError('actual preserved pilot RP bytes differ') + if file_sha256(Path(repeat['scope'])) != repeat['expected_scope_sha256']: + raise ValueError('original repository scope changed') + original_scripts = config['expected_pilot_scripts_sha256'] + if pilot['scripts_sha256'] != original_scripts: + raise ValueError('preserved pilot script hashes differ') + package = Path(__file__).resolve().parent + scripts = {p.name: file_sha256(p) for p in sorted(package.glob('*.py')) if not p.name.startswith('test_')} + if scripts != config['expected_scripts_sha256']: + raise ValueError('frozen single-formal package differs') + if set(scripts) != set(original_scripts) | {'single_formal.py'}: + raise ValueError('unexpected controller additions/removals') + if any(scripts[name] != digest for name, digest in original_scripts.items() if name != 'formal_metrics.py'): + raise ValueError('RP run engine changed; preserved pilot cannot be reused') + expected = [(p, step) for p in PROFILE_FLAGS for step in range(13)] + if [(r['profile'], r['step']) for r in pilot['runs']] != expected: + raise ValueError('preserved pilot order or completeness differs') + for row in pilot['runs']: + require_row_proofs(row, path.parent) + return {'pass': True, 'pilot_summary': str(path), 'pilot_summary_sha256': file_sha256(path), + 'pairs_checked': 65, 'binary_sha256': repeat['expected_binary_sha256'], + 'scope_sha256': repeat['expected_scope_sha256'], + 'reuse_reason': 'same RP/tools/input/policy/resources; only transport measurement collector fixed and single-repeat entry added'} + + +def require_metrics(metrics: dict, profile: str) -> None: + if not isinstance(metrics, dict) or metrics.get('schema') != 'rpki-reuse-seven-metrics-v1' or metrics.get('profile') != profile: + raise ValueError('missing seven-metric schema/profile') + for key in SCALARS: + value = metrics.get(key) + if type(value) not in (int, float) or not math.isfinite(value) or value < 0: + raise ValueError('missing or invalid metric: ' + key) + if any(metrics[key] <= 0 for key in ['rp_validation_ns', 'update_to_payload_ns', 'peak_rss_bytes']): + raise ValueError('validation/payload/RSS must be positive') + enabled = {'signature': profile == 'signature', 'roa': profile in ('object', 'hybrid'), + 'child_certificate': profile in ('object', 'hybrid'), 'publication_point': profile in ('pp', 'hybrid')} + for layer, on in enabled.items(): + r = metrics.get('cache_hit_ratio', {}).get(layer, {}) + hits, queries = r.get('hits'), r.get('queries') + if (r.get('enabled') is not on or type(hits) is not int or type(queries) is not int + or not 0 <= hits <= queries or (not on and (hits or queries)) + or r.get('ratio') != (hits / queries if on and queries else None)): + raise ValueError('cache hit denominator/profile differs: ' + layer) + + +def report(summary: dict) -> dict: + """Descriptive statistics for one trajectory, with no repeat CI claims.""" + require_matrix(summary, summary['scope_sha256'], formal=True) + for row in summary['runs']: + require_metrics(row['seven_metrics'], row['profile']) + selections = {'cold': [0], 'incremental': list(range(1, 13)), + 'before_manifest_fallback': list(range(1, 11)), 'manifest_fallback': [11], 'native_transport_fallback': [12]} + groups = [] + for profile in PROFILE_FLAGS: + for label, steps in selections.items(): + rows = [r for r in summary['runs'] if r['profile'] == profile and r['step'] in steps] + values = [r['seven_metrics'] for r in rows] + group = {'profile': profile, 'steps': label, 'logical_steps': steps, 'n_steps': len(rows), + 'independent_repeats': 1, 'metrics': {}, 'cache_hit_ratio': {}, + 'cache_size_at_end_bytes': max(rows, key=lambda r: r['step'])['seven_metrics']['cache_size_bytes']} + for key in SCALARS: + data = [m[key] for m in values] + group['metrics'][key] = {'mean': statistics.mean(data), 'median': statistics.median(data), + 'min': min(data), 'max': max(data)} + for layer in ['signature', 'roa', 'child_certificate', 'publication_point']: + hits = sum(m['cache_hit_ratio'][layer]['hits'] for m in values) + queries = sum(m['cache_hit_ratio'][layer]['queries'] for m in values) + group['cache_hit_ratio'][layer] = {'hits': hits, 'queries': queries, 'ratio': hits / queries if queries else None} + groups.append(group) + return {'schema': 'rpki-reuse-single-formal-report-v1', 'pass': True, 'performance_ready': True, + 'repeats': 1, 'pairs': 65, 'scope_sha256': summary['scope_sha256'], + 'tool_sha256': summary['tool_sha256'], 'groups': groups, + 'limitations': ['one replay per profile; logical steps are not independent statistical repetitions', + 'same 186 host server/RP; shared storage, page cache and CPU siblings', + '109 successful repository scope plus eight declared gaps; one-hour capture', + 'final controlled RRDP failure exercises the recorded native rsync fallback', + 'all profiles disable transport prefetch; uniform CPU1-3/workers3/5GiB', + 'cache is required serialized CF key/value plus sidecar copies, not whole DB disk usage']} + + +def csv_rows(summary: dict) -> list[dict]: + result = [] + for row in summary['runs']: + metrics = row['seven_metrics'] + require_metrics(metrics, row['profile']) + result.append({'repeat': 1, 'profile': row['profile'], 'step': row['step'], + **{key: metrics[key] for key in SCALARS}, + **{f'{layer}_{key}': metrics['cache_hit_ratio'][layer][key] + for layer in ['signature', 'roa', 'child_certificate', 'publication_point'] + for key in ['hits', 'queries', 'ratio']}}) + return result + + +def run(config: dict) -> dict: + if socket.gethostname() != EXPECTED_HOST or os.geteuid() != 0: + raise ValueError('single formal is restricted to root on the designated 186 host') + output, matrix = Path(config['out']).resolve(), Path(config['repeat']['out']).resolve() + parent = Path('/data/rpki187/20261109/results') + if output.parent != parent or matrix.parent != parent or output == matrix or output.exists() or matrix.exists(): + raise ValueError('single formal requires distinct new empty roots under the dedicated results parent') + resources = resource_guard(parent) + if resources['data_free_bytes'] < config['minimum_available_bytes']: + raise ValueError('insufficient capacity for one matrix plus the unchanged guard') + prerequisite = require_prerequisite(config) + output.mkdir(exist_ok=False) + atomic_json(output / 'pilot-prerequisite.json', prerequisite) + state = {'status': 'running', 'pass': False, 'performance_ready': False, 'config': config, + 'repeats': 1, 'pilot_summary_sha256': prerequisite['pilot_summary_sha256'], 'initial_resources': resources} + + def save() -> None: + state['updated_utc'] = datetime.now(timezone.utc).isoformat() + atomic_json(output / 'single-status.json', state) + + save() + try: + summary = run_pilot(config['repeat']) + result = report(summary) + for row in summary['runs']: + require_row_proofs(row, matrix) + atomic_json(output / 'single-report.json', result) + rows = csv_rows(summary) + with (output / 'all-steps.csv').open('x', newline='') as stream: + writer = csv.DictWriter(stream, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + state.update(status='completed', **{'pass': True}, performance_ready=True, pairs=65, + formal_summary_sha256=file_sha256(matrix / 'summary.json')) + save() + return state + except BaseException as error: + state.update(status='failed', error=f'{type(error).__name__}: {error}') + save() + raise + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--config', type=Path, required=True) + args = parser.parse_args() + def interrupted(*_): + raise KeyboardInterrupt('single formal interrupted') + signal.signal(signal.SIGTERM, interrupted) + print(json.dumps(run(read_json(args.config)))) + + +if __name__ == '__main__': + main() diff --git a/scripts/experiments/reuse_eval/smoke_live.py b/scripts/experiments/reuse_eval/smoke_live.py new file mode 100644 index 0000000..178be5f --- /dev/null +++ b/scripts/experiments/reuse_eval/smoke_live.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 +"""Bounded single-repository protocol smoke; RP cryptographic acceptance is separate.""" +import argparse +import json +from pathlib import Path + +from capture import Collector, select_epoch +from common import Archive, atomic_json, now_ms +from verify import verify + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--notification", required=True) + parser.add_argument("--archive", type=Path, required=True) + args = parser.parse_args() + if args.archive.exists(): + raise ValueError("smoke archive must be new") + archive = Archive(args.archive, {"min_free_bytes": 150 * 1024**3, "min_root_free_inodes": 10000, + "attempts": 1, "request_timeout_secs": 20, "observation_deadline_secs": 180}) + observation = Collector(archive).observe(args.notification) + epoch = select_epoch(args.archive, {args.notification: {"first_seen_ms": 0}}, now_ms()) + atomic_json(args.archive / "epochs/epoch_0000.json", epoch) + result = verify(args.archive) + atomic_json(args.archive / "smoke.json", {"observation": observation, "closure": result, + "real_rp_crypto_acceptance": "not_run_by_this_protocol_smoke"}) + print(json.dumps(result), flush=True) + return 0 if result["pass"] else 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/experiments/reuse_eval/smoke_matrix.py b/scripts/experiments/reuse_eval/smoke_matrix.py new file mode 100644 index 0000000..38b7482 --- /dev/null +++ b/scripts/experiments/reuse_eval/smoke_matrix.py @@ -0,0 +1,187 @@ +#!/usr/bin/env python3 +"""Functional five-profile/two-step real-TA smoke; never a performance benchmark.""" +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import re +import signal +import shutil +import subprocess +import time + +from cache_size import account, profile_from_contract +from common import atomic_json, file_sha256, read_json + + +def command_run(command: list[str], output: Path, error: Path, env: dict, timeout: int = 600) -> dict: + started = time.monotonic() + with output.open("wb") as out, error.open("wb") as err: + child = subprocess.Popen(command, stdout=out, stderr=err, env=env, start_new_session=True) + try: + code = child.wait(timeout=timeout) + except BaseException: + if child.poll() is None: + os.killpg(child.pid, signal.SIGKILL) + child.wait(timeout=10) + raise + if code: + raise RuntimeError(f"command exited {code}; see {error}") + return {"command": command, "exit_code": code, "wall_secs_functional_only": time.monotonic() - started} + + +def require_comparison(path: Path, kind: str) -> None: + # cir_state_compare writes differences but intentionally exits zero. + field = {"cir": "allMatch", "ccr": "stateDigestMatch"}[kind] + if read_json(path).get(field) is not True: + raise ValueError(f"{kind.upper()} semantic comparison failed: {path}") + + +def snapshot_pre_state(state: Path, checkpoint: Path) -> dict: + """Copy closed functional-fixture state before T1, including every sidecar.""" + if checkpoint.exists(): + raise ValueError("pre-step checkpoint already exists") + for path in state.rglob("*"): + if path.is_symlink() or not (path.is_file() or path.is_dir()): + raise ValueError(f"non-regular pre-step state: {path}") + shutil.copytree(state, checkpoint) + files = {str(path.relative_to(checkpoint)): file_sha256(path) + for path in sorted(checkpoint.rglob("*")) if path.is_file()} + return {"created_unix_ns": time.time_ns(), "checkpoint_root": str(checkpoint.resolve()), "files_sha256": files, + "method": "closed-functional-fixture-copy-before-T1"} + + +def cache_counters(run: Path) -> dict: + stage = read_json(run / "stage-timing.json") + signature = stage.get("crypto_signature_cache_observe") + # Exclude elapsed time, byte accounting and storage/index load telemetry. + return {"signature": {"entries_loaded": signature["entries_loaded"], + "entries_total": signature["entries_total"], + "per_point": {point: {k: v for k, v in counts.items() if "nanos" not in k} + for point, counts in signature["per_point"].items()}} + if signature else None, + "roa": {k: v for k, v in stage["roa_validation_cache"].items() if "nanos" not in k}, + "tree_cache": {k: v for k, v in stage["analysis_counts"].items() + if "cache" in k and not any(s in k for s in ("index", "bytes", "persist", "load", "nanos", "_ms"))}} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + for name in ("binary", "ccr-compare", "cir-compare", "db-stats-bin", "profiles", "manifest", "tal", "ta", "out"): + parser.add_argument("--" + name, type=Path, required=True) + parser.add_argument("--with-benchmark", action="store_true", + help="also validate frozen-input T2 with a separate pre-step cache copy") + parser.add_argument("--max-instances", type=int, default=1, + help="bounded functional fixture scope (1..16; default 1)") + args = parser.parse_args() + if not 1 <= args.max_instances <= 16: + raise ValueError("functional fixture scope must be between 1 and 16 instances") + args.out.mkdir(parents=True) + manifest = read_json(args.manifest) + epoch = read_json(Path(manifest["epoch_path"])) + profiles = read_json(args.profiles)["profiles"] + if set(profiles) != {"baseline", "signature", "object", "pp", "hybrid"}: + raise ValueError("requires exactly the confirmed five-profile matrix") + env = {key: value for key, value in os.environ.items() if key.lower() not in ("http_proxy", "https_proxy", "all_proxy")} + summary = {"status": "running", "pass": False, "purpose": "bounded-no-change-functional-smoke-not-performance", + "max_instances": args.max_instances, + "binary_sha256": file_sha256(args.binary), "manifest_sha256": file_sha256(args.manifest), + "tal_sha256": file_sha256(args.tal), "ta_sha256": file_sha256(args.ta), + "constraints_sha256": file_sha256(args.tal.with_suffix(".constraints")) if args.tal.with_suffix(".constraints").exists() else None, + "namespace": os.readlink("/proc/self/ns/net"), "profiles": profiles, "runs": []} + comparator_bins = {"ccr": str(args.ccr_compare), "cir": str(args.cir_compare), "db_stats": str(args.db_stats_bin)} + summary["tool_sha256"] = {key: file_sha256(Path(path)) for key, path in comparator_bins.items()} + baseline_contracts = {} + try: + for profile in ("baseline", "signature", "object", "pp", "hybrid"): + private = args.out / profile + (private / "state").mkdir(parents=True) + (private / "tmp").mkdir() + env["TMPDIR"] = str(private / "tmp") + for step in range(2): + run = private / f"step_{step:04d}" + run.mkdir() + logical_ms = epoch["validation_time_ms"] + step * 300_000 + logical_time = datetime.fromtimestamp(logical_ms // 1000, timezone.utc).isoformat().replace("+00:00", "Z") + db = private / "state/db" + command = [str(args.binary), "--db", str(db), "--tal-path", str(args.tal), "--ta-path", str(args.ta), + "--cir-tal-uri", f"https://capture.rpki187.invalid/tal/{summary['tal_sha256']}/{args.tal.name}", + "--http-root-cert", manifest["tls"]["ca"], "--max-instances", str(args.max_instances), + "--parallel-max-repo-sync-workers-global", "3", "--parallel-phase2-object-workers", "3", + "--validation-time", logical_time, "--validation-contract-out", str(run / "contract.json"), + "--report-json", str(run / "report.json"), "--report-json-compact", + "--ccr-out", str(run / "result.ccr"), "--cir-enable", "--cir-out", str(run / "input.cir"), + "--record-transport-dir", str(run / "transport"), "--rsync-mirror-root", str(private / "mirror"), + "--analyze", "--analysis-out", str(run / "analysis")] + profiles[profile] + atomic_json(run / "command.json", command) + pre_state = "empty" + if args.with_benchmark: + checkpoint = private / "checkpoints" / f"step_{step:04d}" + proof = snapshot_pre_state(private / "state", checkpoint) + atomic_json(run / "pre-state.json", proof) + if step: + pre_state = str(checkpoint / "db") + atomic_json(run / "t1-start.json", {"started_unix_ns": time.time_ns()}) + result = command_run(command, run / "stdout.log", run / "stderr.log", env) + contract = read_json(run / "contract.json") + actual_profile, _ = profile_from_contract(contract) + if profile != actual_profile or contract["validationTime"] != logical_time: + raise ValueError("effective cache profile or logical time differs") + shared = {key: value for key, value in contract.items() if key != "cache"} + if profile == "baseline": + baseline_contracts[step] = shared + elif shared != baseline_contracts[step]: + raise ValueError("non-cache validation contract differs from baseline") + stderr = (run / "stderr.log").read_text(errors="replace") + anchors = re.findall(r"wrote CIR: .*?trust_anchors=(\d+)", stderr) + report = read_json(run / "report.json") + if not anchors or int(anchors[-1]) != 1 or report["tree"]["instances_failed"] != 0 or not 1 <= len(report["publication_points"]) <= args.max_instances: + raise ValueError("real-TA bounded verification failed") + if args.max_instances > 1 and not (report["vrps"] or report["aspas"] or report.get("router_keys")): + raise ValueError("extended functional fixture has no accepted payload") + baseline = args.out / "baseline" / f"step_{step:04d}" + comparisons = [ + [str(args.ccr_compare), "--source-ccr", str(baseline / "result.ccr"), "--verification-ccr", str(run / "result.ccr"), "--out-json", str(run / "ccr-comparison.json")], + [str(args.cir_compare), "--ours-cir", str(baseline / "input.cir"), "--peer-cir", str(run / "input.cir"), "--out-json", str(run / "cir-comparison.json")], + ] + for kind, comparison in zip(("ccr", "cir"), comparisons): + command_run(comparison, run / (kind + "-compare.stdout"), run / (kind + "-compare.stderr"), env) + require_comparison(run / (kind + "-comparison.json"), kind) + command_run([str(args.db_stats_bin), "--db", str(db), "--exact"], run / "db-stats.txt", run / "db-stats.stderr", env) + size = account(db, run / "db-stats.txt", run / "contract.json") + atomic_json(run / "cache-size.json", size) + result.update(profile=profile, step=step, path=str(run), validation_time=logical_time, + cache_size_bytes=size["required_serialized_bytes"], comparisons_pass=True) + if args.with_benchmark: + benchmark = private / f"benchmark_{step:04d}" + benchmark_command = [str(args.binary), "--validation-benchmark", "--source-run", str(run), + "--source-state", str(db), "--pre-state", pre_state, "--out", str(benchmark)] + command_run(benchmark_command, run / "benchmark.stdout", run / "benchmark.stderr", env) + if read_json(benchmark / "equivalence.json")["pass"] is not True: + raise ValueError("T2 input/payload comparison failed") + overlay = read_json(benchmark / "input-overlay.json")["overlay"] + if overlay["cache_before"] != overlay["cache_after"]: + raise ValueError("raw input overlay changed pre-step validation caches") + if overlay.get("background_io_drained") is not True: + raise ValueError("input staging background I/O was not drained before measurement") + counters = {"t1": cache_counters(run), "t2": cache_counters(benchmark)} + atomic_json(run / "benchmark-cache-counters.json", counters) + if counters["t1"] != counters["t2"]: + raise ValueError("T2 cache hit/miss behavior differs from T1") + result["benchmark_functional_pass"] = True + summary["runs"].append(result) + atomic_json(args.out / "summary.json", summary) + summary.update({"status": "completed", "pass": True}) + except Exception as exc: + summary.update(status="failed", error=f"{type(exc).__name__}: {exc}") + raise + finally: + atomic_json(args.out / "summary.json", summary) + print(json.dumps({"pass": summary["pass"], "runs": len(summary["runs"]), "purpose": summary["purpose"]})) + + +if __name__ == "__main__": + main() diff --git a/scripts/experiments/reuse_eval/smoke_rp.py b/scripts/experiments/reuse_eval/smoke_rp.py new file mode 100644 index 0000000..3ced25c --- /dev/null +++ b/scripts/experiments/reuse_eval/smoke_rp.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python3 +"""One real-TA publication-point RP smoke inside the prepared replay namespace.""" +import argparse +from datetime import datetime, timezone +import hashlib +import json +import os +from pathlib import Path +import re +import subprocess +import time + +from common import atomic_json, read_json + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--binary", type=Path, required=True) + parser.add_argument("--tal", type=Path, required=True) + parser.add_argument("--ta", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--out", type=Path, required=True) + parser.add_argument("--disable-rrdp", action="store_true", help="Force real rsync for a separately identified transport fixture") + args = parser.parse_args() + args.out.mkdir(parents=True) + (args.out / "tmp").mkdir() + manifest = read_json(args.manifest) + epoch = read_json(Path(manifest["epoch_path"])) + validation_time = datetime.fromtimestamp(epoch["validation_time_ms"] // 1000, timezone.utc).isoformat().replace("+00:00", "Z") + command = ["/usr/bin/time", "-v", str(args.binary), "--db", str(args.out / "db"), "--tal-path", str(args.tal), + "--cir-tal-uri", f"https://capture.rpki187.invalid/tal/{hashlib.sha256(args.tal.read_bytes()).hexdigest()}/{args.tal.name}", + "--ta-path", str(args.ta), "--http-root-cert", manifest["tls"]["ca"], "--max-instances", "1", + "--validation-time", validation_time, "--report-json", str(args.out / "report.json"), + "--report-json-compact", "--ccr-out", str(args.out / "result.ccr"), + "--cir-enable", "--cir-out", str(args.out / "input.cir"), + "--record-transport-dir", str(args.out / "transport"), "--rsync-mirror-root", str(args.out / "mirror")] + if args.disable_rrdp: + command.append("--disable-rrdp") + env = {key: value for key, value in os.environ.items() if key.lower() not in ("http_proxy", "https_proxy", "all_proxy")} + env["TMPDIR"] = str(args.out / "tmp") + started = time.monotonic() + with (args.out / "stdout.log").open("wb") as out, (args.out / "stderr.log").open("wb") as err: + result = subprocess.run(command, stdout=out, stderr=err, env=env, timeout=900) + log = (args.out / "stderr.log").read_text(errors="replace") + anchors = re.findall(r"wrote CIR: .*?trust_anchors=(\d+)", log) + report = read_json(args.out / "report.json") if (args.out / "report.json").exists() else {} + proof = {"exit_code": result.returncode, "wall_secs": time.monotonic() - started, + "profile": "functional_smoke_not_performance", "command": command, + "binary_sha256": hashlib.sha256(args.binary.read_bytes()).hexdigest(), + "ta_sha256": hashlib.sha256(args.ta.read_bytes()).hexdigest(), "ta_mode": "pinned genuine TA checked against real TAL", + "network_namespace": os.readlink("/proc/self/ns/net"), "validation_time": validation_time, + "trust_anchors": int(anchors[-1]) if anchors else 0, "tree": report.get("tree"), + "publication_points": len(report.get("publication_points", []))} + events = [read_json(path) for path in (args.out / "transport/events").glob("*.json")] + proof["forced_rsync_fixture"] = args.disable_rrdp + proof["successful_transport_events"] = {kind: sum(event["complete"] and event["transport"] == kind for event in events) + for kind in ("http", "rsync")} + proof["pass"] = (result.returncode == 0 and proof["trust_anchors"] == 1 and proof["publication_points"] == 1 + and report["tree"]["instances_failed"] == 0) + if args.disable_rrdp: + proof["pass"] = proof["pass"] and proof["successful_transport_events"]["rsync"] > 0 and not proof["successful_transport_events"]["http"] + atomic_json(args.out / "smoke-proof.json", proof) + print(json.dumps(proof), flush=True) + return 0 if proof["pass"] else 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/experiments/reuse_eval/test_cache_size.py b/scripts/experiments/reuse_eval/test_cache_size.py new file mode 100644 index 0000000..03d7da1 --- /dev/null +++ b/scripts/experiments/reuse_eval/test_cache_size.py @@ -0,0 +1,86 @@ +"""Check strategy attribution without treating the whole DB as validation cache.""" +import json +from pathlib import Path +import tempfile +import unittest + +from cache_size import COMPONENTS, account, file_inventory + + +class CacheSizeTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.db = self.root / "state" + self.db.mkdir() + self.stats = self.root / "stats.txt" + lines = [f"db={self.db}", "mode=exact", "logical_bytes_available=true"] + for cf in COMPONENTS.values(): + lines += [f"cf.{cf}.{key}={value}" for key, value in + (("keys", 2), ("key_bytes", 10), ("value_bytes", 90), ("live_sst_size_bytes", 55))] + # Large public object data must never enter the validation cache total. + lines += ["cf.raw_by_hash.value_bytes=900000000", "db.files.total_size_bytes=999999999"] + self.stats.write_text("\n".join(lines)) + self.contract = self.root / "contract.json" + + def contract_for(self, **changes): + cache = dict(publicationPoint=False, roa=False, childCertificate=False, cryptoSignature=False, transportPrefetch=False) + cache.update(changes) + self.contract.write_text(json.dumps({"cache": cache})) + + def test_baseline_reports_common_retention_separately(self): + self.contract_for() + report = account(self.db, self.stats, self.contract) + self.assertEqual(report["required_serialized_bytes"], 0) + self.assertEqual(report["all_retained_validation_cf_key_value_bytes"], 700) + self.assertEqual(report["profile"], "baseline") + + def test_hybrid_counts_selected_projections_and_real_index_copy(self): + self.contract_for(publicationPoint=True, roa=True, childCertificate=True) + index = self.root / "state.pp-cache-index" + index.mkdir() + (index / "current.idx").write_bytes(b"index copy") + child = self.root / "state.child-cert-cache-index" + child.mkdir() + (child / "pp.idx").write_bytes(b"child index") + # A disabled but retained signature sidecar must be exposed, not attributed to Hybrid. + (self.root / "state.crypto-sig-cache").write_bytes(b"stale signature") + report = account(self.db, self.stats, self.contract) + self.assertEqual(report["required_serialized_bytes"], 321) + self.assertEqual(report["required_cf_key_value_bytes"], 300) + self.assertEqual(report["all_retained_sidecar_file_bytes"], 36) + self.assertGreaterEqual(report["sidecars"]["publication_point"]["allocated_bytes"], 10) + + def test_signature_counts_file_without_object_or_pp_projections(self): + self.contract_for(cryptoSignature=True) + (self.root / "state.crypto-sig-cache").write_bytes(b"serialized signature conclusions") + report = account(self.db, self.stats, self.contract) + self.assertEqual(report["profile"], "signature") + self.assertEqual(report["required_cf_key_value_bytes"], 0) + self.assertEqual(report["required_serialized_bytes"], len(b"serialized signature conclusions")) + + def test_rejects_estimates_other_db_and_out_of_matrix_contract(self): + self.contract_for() + text = self.stats.read_text() + self.stats.write_text(text.replace("mode=exact", "mode=estimate")) + with self.assertRaisesRegex(ValueError, "--exact"): + account(self.db, self.stats, self.contract) + self.stats.write_text(text) + with self.assertRaisesRegex(ValueError, "different state"): + account(self.root / "other", self.stats, self.contract) + for changes in ({"transportPrefetch": True}, {"roa": True}, {"cryptoSignature": "false"}): + self.contract_for(**changes) + with self.assertRaises(ValueError): + account(self.db, self.stats, self.contract) + + def test_sidecar_symlink_never_scans_another_profiles_files(self): + (self.root / "outside").mkdir() + path = self.root / "state.pp-cache-index" + path.symlink_to(self.root / "outside", target_is_directory=True) + with self.assertRaisesRegex(ValueError, "symlink"): + file_inventory(path) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/experiments/reuse_eval/test_campaign.py b/scripts/experiments/reuse_eval/test_campaign.py new file mode 100644 index 0000000..b87d278 --- /dev/null +++ b/scripts/experiments/reuse_eval/test_campaign.py @@ -0,0 +1,55 @@ +import copy +import unittest + +from campaign import SCALARS, aggregate, require_matrix +from sequence_matrix import PROFILE_FLAGS + + +def fixture(repeat): + rows = [] + for profile in PROFILE_FLAGS: + for step in range(13): + ratios = {name: {"hits": 0, "queries": 0, "ratio": None} + for name in ("signature", "roa", "child_certificate", "publication_point")} + metrics = {key: repeat * 10 + step for key in SCALARS} + metrics["cache_hit_ratio"] = ratios + rows.append({"profile": profile, "step": step, "pass": True, "seven_metrics": metrics}) + return {"status": "completed", "pass": True, "performance_ready": True, "scope_sha256": "scope", + "tool_sha256": {"binary": "binary", "ccr_compare": "comparator"}, "runs": rows, + "restoration": {"rp187rp": 0, "rp187srv": 0, "panda_active": True, "panda_container_running": True}} + + +class CampaignTests(unittest.TestCase): + def test_three_repeat_means_are_replicates_instead_of_individual_epochs(self): + result = aggregate([fixture(n) for n in (1, 2, 3)]) + self.assertEqual(result["pairs"], 195) + regular = next(g for g in result["groups"] if g["profile"] == "baseline" and g["steps"] == "incremental_without_fallback") + self.assertEqual(regular["metrics"]["rp_validation_ns"]["values"], [16, 26, 36]) + self.assertEqual(regular["metrics"]["rp_validation_ns"]["n"], 3) + self.assertEqual(regular["metrics"]["rp_validation_ns"]["stdev"], 10) + self.assertIsNone(regular["hit_ratios"]["signature"]) + + def test_duplicate_missing_pairs_and_changed_build_or_restore_are_rejected(self): + original = fixture(1) + for altered in ("duplicate", "scope", "restore", "metrics"): + summary = copy.deepcopy(original) + if altered == "duplicate": + summary["runs"][-1] = summary["runs"][0] + elif altered == "scope": + summary["scope_sha256"] = "different" + elif altered == "restore": + summary["restoration"]["panda_container_running"] = False + else: + summary["runs"][0]["seven_metrics"] = None + with self.subTest(altered=altered), self.assertRaises(ValueError): + require_matrix(summary, "scope", formal=True) + different = fixture(3) + different["tool_sha256"]["binary"] = "changed" + with self.assertRaises(ValueError): + aggregate([fixture(1), fixture(2), different]) + with self.assertRaises(ValueError): + aggregate([fixture(1)]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/experiments/reuse_eval/test_capture.py b/scripts/experiments/reuse_eval/test_capture.py new file mode 100644 index 0000000..510677b --- /dev/null +++ b/scripts/experiments/reuse_eval/test_capture.py @@ -0,0 +1,310 @@ +"""Protocol-focused tests; no public network or genuine TA substitutes as evidence.""" +import base64 +import gzip +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +import io +import json +from pathlib import Path +import tempfile +import threading +import sys +import time +import unittest +from unittest.mock import Mock, patch + +from capture import Capture, Collector, select_epoch +from common import Archive, atomic_json, digest_bytes, file_sha256, now_ms +from rrdp import notification, payload_view, view_digest +from verify import verify + +SESSION = "11111111-1111-4111-8111-111111111111" +OTHER_SESSION = "22222222-2222-4222-8222-222222222222" +OBJECT = "rsync://repo.example/module/a.roa" +OTHER_OBJECT = "rsync://repo.example/module/b.roa" + + +def publish(uri, data, previous=None): + attr = f' hash="{digest_bytes(previous)}"' if previous is not None else "" + return f'{base64.b64encode(data).decode()}' + + +def xml(kind, serial, content, session=SESSION): + return (f'<{kind} xmlns="http://www.ripe.net/rpki/rrdp" version="1" session_id="{session}" serial="{serial}">' + f'{content}').encode() + + +class CaptureTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.resources = {} + self.requests = [] + resources, requests = self.resources, self.requests + class Handler(BaseHTTPRequestHandler): + def log_message(self, *_): + pass + def do_GET(self): + requests.append((self.path, self.headers.get("If-None-Match"))) + resource = resources.get(self.path) + if resource is None: + self.send_error(404) + return + body, headers = resource + status = 304 if headers.get("ETag") == self.headers.get("If-None-Match") and headers.get("ETag") else headers.get("status", 200) + self.send_response(status) + for key, value in headers.items(): + if key not in ("status", "Content-Length"): + self.send_header(key, value) + self.send_header("Content-Length", headers.get("Content-Length", str(len(body)))) + self.end_headers() + if status != 304: + self.wfile.write(body) + self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + self.thread = threading.Thread(target=self.server.serve_forever, daemon=True) + self.thread.start() + self.addCleanup(self.server.server_close) + self.addCleanup(self.server.shutdown) + self.base = f"http://127.0.0.1:{self.server.server_port}" + self.uri = self.base + "/notification.xml" + self.archive = Archive(Path(self.tmp.name) / "archive", {"allow_test_http": True, "attempts": 1, "request_timeout_secs": 1}) + self.collector = Collector(self.archive) + + def install(self, serial, snapshot, deltas=None, session=SESSION, etag=None): + self.resources["/snapshot.xml"] = (snapshot, {}) + content = f'' + for number, body in (deltas or {}).items(): + self.resources[f"/delta-{number}.xml"] = (body, {}) + content += f'' + self.resources["/notification.xml"] = (xml("notification", serial, content, session), {"ETag": etag} if etag else {}) + + def initial(self): + self.install(1, xml("snapshot", 1, publish(OBJECT, b"a")), etag='"one"') + observation = self.collector.observe(self.uri) + self.assertTrue(observation["complete"], observation) + return observation + + def test_initial_and_304_reuse_exact_body(self): + first = self.initial() + second = self.collector.observe(self.uri, first) + self.assertTrue(second["complete"]) + self.assertEqual(second["http"]["status"], 304) + self.assertEqual(first["notification"], second["notification"]) + self.assertEqual(second["chain"], "no_change") + self.assertEqual(sum(path == "/snapshot.xml" for path, _ in self.requests), 1) + + def test_multiple_delta_replacement_and_withdrawal_match_snapshot(self): + first = self.initial() + d2 = xml("delta", 2, publish(OBJECT, b"changed", b"a") + publish(OTHER_OBJECT, b"b")) + d3 = xml("delta", 3, f'') + self.install(3, xml("snapshot", 3, publish(OBJECT, b"changed")), {2: d2, 3: d3}) + final = self.collector.observe(self.uri, first) + self.assertTrue(final["complete"], final) + self.assertEqual(final["chain"], "delta_matches_snapshot") + self.assertTrue(self.archive.blob_path(first["notification"]["sha256"]).exists()) + + def test_missing_required_delta_rejects_observation(self): + first = self.initial() + self.install(3, xml("snapshot", 3, publish(OBJECT, b"a")), {3: xml("delta", 3, "")}) + result = self.collector.observe(self.uri, first) + self.assertFalse(result["complete"]) + self.assertIn("required delta 2 missing", result["error"]) + + def test_wrong_previous_hash_rejects_delta(self): + first = self.initial() + self.install(2, xml("snapshot", 2, publish(OBJECT, b"new")), + {2: xml("delta", 2, publish(OBJECT, b"new", b"wrong"))}) + self.assertIn("previous hash mismatch", self.collector.observe(self.uri, first)["error"]) + + def test_delta_snapshot_disagreement_rejects_observation(self): + first = self.initial() + self.install(2, xml("snapshot", 2, publish(OBJECT, b"other")), + {2: xml("delta", 2, publish(OBJECT, b"new", b"a"))}) + self.assertIn("differs from snapshot", self.collector.observe(self.uri, first)["error"]) + + def test_session_reset_uses_real_new_snapshot(self): + first = self.initial() + self.install(1, xml("snapshot", 1, publish(OTHER_OBJECT, b"b"), OTHER_SESSION), session=OTHER_SESSION) + result = self.collector.observe(self.uri, first) + self.assertTrue(result["complete"], result) + self.assertEqual(result["chain"], "session_reset_snapshot") + + def test_snapshot_reference_hash_mismatch_is_not_complete(self): + self.initial() + self.resources["/snapshot.xml"] = (b"corrupt", {}) + # New archive prevents a valid previously saved body satisfying the reference. + other = Archive(Path(self.tmp.name) / "other", self.archive.limits) + self.assertFalse(Collector(other).observe(self.uri)["complete"]) + + def test_same_serial_changed_snapshot_rejected(self): + first = self.initial() + self.install(1, xml("snapshot", 1, publish(OBJECT, b"changed"))) + self.assertIn("without session/serial", self.collector.observe(self.uri, first)["error"]) + + def test_old_optional_delta_failure_is_reported_but_initial_usable(self): + self.install(2, xml("snapshot", 2, publish(OBJECT, b"a")), {1: xml("delta", 1, "")}) + del self.resources["/delta-1.xml"] + result = self.collector.observe(self.uri) + self.assertTrue(result["complete"], result) + self.assertFalse(next(r for r in result["references"] if r["kind"] == "delta")["available"]) + + def test_304_without_prior_entity_is_failure(self): + self.resources["/x"] = (b"", {"status": 304}) + result = self.archive.fetch(self.base + "/x", "notification") + self.assertFalse(result["complete"]) + + def test_http_gzip_preserves_decoded_entity(self): + raw = b"signed content" + self.resources["/gzip"] = (gzip.compress(raw), {"Content-Encoding": "gzip"}) + result = self.archive.fetch(self.base + "/gzip", "snapshot") + self.assertTrue(result["complete"], result) + self.assertEqual(result["body"]["sha256"], digest_bytes(raw)) + + def test_truncated_body_is_failure(self): + self.resources["/short"] = (b"short", {"Content-Length": "100"}) + self.assertFalse(self.archive.fetch(self.base + "/short", "snapshot")["complete"]) + + def test_cross_origin_redirect_never_follows(self): + self.resources["/redirect"] = (b"", {"status": 302, "Location": "http://localhost:1/forbidden"}) + result = self.archive.fetch(self.base + "/redirect", "notification") + self.assertFalse(result["complete"]) + self.assertIn("cross-origin", result["error"]) + + def test_cross_origin_reference_rejected(self): + body = xml("notification", 1, f'') + ref = self.archive.put_stream(io.BytesIO(body)) + with self.assertRaisesRegex(ValueError, "cross-origin"): + notification(self.archive.blob_path(ref["sha256"]), self.uri) + + def test_future_completion_never_used_for_earlier_epoch(self): + first = self.initial() + registry = {self.uri: {"first_seen_ms": 0}} + early = select_epoch(self.archive.root, registry, first["completed_ms"] - 1) + self.assertFalse(early["complete"]) + exact = select_epoch(self.archive.root, registry, first["completed_ms"]) + self.assertTrue(exact["complete"]) + self.assertEqual(exact["repositories"][self.uri]["id"], first["id"]) + + def test_latest_failure_cannot_silently_turn_into_a_successful_noop_epoch(self): + first = self.initial() + self.resources.pop("/notification.xml") + failed = self.collector.observe(self.uri, first) + self.assertFalse(failed["complete"]) + epoch = select_epoch(self.archive.root, {self.uri: {"first_seen_ms": 0}}, now_ms()) + self.assertFalse(epoch["complete"]) + self.assertEqual(epoch["blocked_latest_attempts"], [self.uri]) + self.assertEqual(epoch["repositories"][self.uri]["id"], first["id"]) + + def test_closure_verifier_detects_corrupt_blob(self): + first = self.initial() + epoch = select_epoch(self.archive.root, {self.uri: {"first_seen_ms": 0}}, now_ms()) + atomic_json(self.archive.root / "epochs/epoch_0000.json", epoch) + self.assertTrue(verify(self.archive.root)["pass"]) + self.archive.blob_path(first["notification"]["sha256"]).write_bytes(b"corrupt") + self.assertFalse(verify(self.archive.root)["pass"]) + + def test_epoch_rejects_changed_capture_policy_contract(self): + self.initial() + contract = self.archive.root / "contract.json" + atomic_json(contract, {"tals": [], "policy": "fixed"}) + epoch = select_epoch(self.archive.root, {self.uri: {"first_seen_ms": 0}}, now_ms()) + atomic_json(self.archive.root / "epochs/epoch_0000.json", epoch) + self.assertTrue(verify(self.archive.root)["pass"]) + atomic_json(contract, {"tals": [], "policy": "different"}) + self.assertFalse(verify(self.archive.root)["pass"]) + + def test_zero_exit_with_only_four_anchors_never_qualifies_main_capture(self): + tals = [] + for index in range(5): + path = Path(self.tmp.name) / f"fixture-{index}.tal" + path.write_text(f"https://fixture.example/{index}.cer\n\nunit-test-input\n") + tals.append(str(path)) + capture = Capture({"archive_root": str(Path(self.tmp.name) / "main"), "binary": sys.executable, "tals": tals}) + run = capture.root / "unit-run" + run.mkdir() + (run / "stderr.log").write_text("wrote CIR: unit (objects=1, trust_anchors=4, total_ms=1)\n") + (run / "stdout.log").write_text("vrps=100\n") + capture.metadata["runs"] = [{"path": str(run)}] + capture.rp = Mock() + capture.rp.poll.return_value = 0 + capture.rp_started = time.monotonic() + with self.assertRaisesRegex(RuntimeError, "all five"): + capture.check_rp() + + def test_ta_refresh_event_is_bound_to_the_epoch(self): + ref = self.archive.put_stream(io.BytesIO(b"unit TA entity")) + uri = "https://ta.example/real-endpoint.cer" + event = self.archive.event({"source": "ta_refresh", "transport": "http", "kind": "object", "uri": uri, + "started_ms": now_ms(), "complete": True, "body": ref}) + epoch = select_epoch(self.archive.root, {}, now_ms()) + self.assertEqual(epoch["ta_object_events"][uri], event["id"]) + + def test_gap_recording_keeps_incomplete_epochs_and_strict_default_gate(self): + # Exercise controller policy only; the real five-TA acceptance is remote. + tals = [] + for index in range(5): + tal = Path(self.tmp.name) / f"policy-{index}.tal" + tal.write_text(f"https://fixture.example/{index}.cer\n\nunit-input\n") + tals.append(str(tal)) + for policy in ("abort", "record-with-gaps"): + with self.subTest(policy=policy): + config = {"archive_root": str(Path(self.tmp.name) / policy), "binary": sys.executable, + "tals": tals, "duration_secs": 300, "bootstrap_attempts": 1} + if policy != "abort": + config["bootstrap_gap_policy"] = policy + capture = Capture(config) + run = capture.root / "controller-unit-run" + run.mkdir() + atomic_json(run / "validation-contract.json", {"test_only": True}) + capture.start_rp = lambda: capture.metadata["runs"].append({"path": str(run)}) + capture.discover = lambda: capture.registry.update({self.base + "/unreachable.xml": {"first_seen_ms": 0}}) + clock = Mock() + clock.monotonic.side_effect = iter(range(0, 10000, 1000)) + with patch("capture.time", clock): + capture.run() + expected = "bootstrap_incomplete" if policy == "abort" else "recorded_with_gaps" + self.assertEqual(capture.metadata["status"], expected) + self.assertFalse(capture.metadata["bootstrap_complete"]) + self.assertEqual(capture.metadata["bootstrap_missing"], [self.base + "/unreachable.xml"]) + epoch = json.loads((capture.root / "epochs/epoch_0000.json").read_text()) + self.assertFalse(epoch["complete"]) + self.assertFalse(verify(capture.root)["pass"]) + self.assertEqual("t0_ms" in capture.metadata, policy != "abort") + + def test_ta_refresh_tries_next_original_uri_and_pins_exact_entity(self): + # A controller unit test; genuine SPKI/crypto acceptance is covered by the remote RP smoke. + capture = Capture.__new__(Capture) + capture.archive, capture.root = self.archive, self.archive.root + tal = Path(self.tmp.name) / "test.tal" + tal.write_text("https://ta.example/unavailable.cer\nhttps://ta.example/current.cer\n\nunit-input\n") + destination = Path(self.tmp.name) / "ta" + destination.mkdir() + ref = self.archive.put_stream(io.BytesIO(b"exact downloaded TA bytes")) + calls = [] + def download(uri, kind, previous=None, source="poller"): + calls.append(uri) + return self.archive.event({"source": source, "transport": "http", "kind": kind, "uri": uri, + "started_ms": now_ms(), "complete": len(calls) == 2, "body": ref}) + capture.archive.fetch = download + result = capture.refresh_ta(tal, destination) + self.assertEqual(calls, ["https://ta.example/unavailable.cer", "https://ta.example/current.cer"]) + self.assertEqual(Path(result["path"]).read_bytes(), b"exact downloaded TA bytes") + self.assertEqual(result["sha256"], ref["sha256"]) + + def test_dtd_and_duplicate_snapshot_objects_rejected(self): + for body in (b']>', + xml("snapshot", 1, publish(OBJECT, b"a") + publish(OBJECT, b"b"))): + ref = self.archive.put_stream(io.BytesIO(body)) + with self.assertRaises(ValueError): + payload_view(self.archive.blob_path(ref["sha256"]), "snapshot", SESSION, 1) + + def test_blob_path_traversal_and_size_guard(self): + with self.assertRaises(ValueError): + self.archive.blob_path("../escape") + small = Archive(Path(self.tmp.name) / "small", {"max_body_bytes": 2}) + with self.assertRaises(ValueError): + small.put_stream(io.BytesIO(b"large")) + self.assertFalse(list((small.root / "partial").iterdir())) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/experiments/reuse_eval/test_formal_metrics.py b/scripts/experiments/reuse_eval/test_formal_metrics.py new file mode 100644 index 0000000..fb982ad --- /dev/null +++ b/scripts/experiments/reuse_eval/test_formal_metrics.py @@ -0,0 +1,106 @@ +from pathlib import Path +import tempfile +import unittest + +from common import atomic_json +from formal_metrics import collect, hit_ratios, interval_union + + +class FormalMetricsTests(unittest.TestCase): + def test_parallel_sync_union_and_reversed_bounds(self): + self.assertEqual(interval_union([(20, 40), (0, 10), (5, 25), (50, 55)]), 45) + self.assertEqual(interval_union([]), 0) + with self.assertRaises(ValueError): + interval_union([(5, 4)]) + + def test_hybrid_denominators_keep_layers_separate_and_do_not_double_count_context(self): + stage = {"analysis_counts": {"child_certificate_cache_hit": 7, "child_certificate_cache_lookup": 10, + "publication_point_cache_reuse_hits": 9, "publication_point_cache_lookup_total": 20}, + "roa_validation_cache": {"hit_roas": 50, "miss_roas": 20, "blocked_roas": 30, "context_blocked_roas": 15}} + ratios = hit_ratios(stage, "hybrid") + self.assertEqual(ratios["roa"]["ratio"], 0.5) + self.assertEqual(ratios["child_certificate"]["ratio"], 0.7) + self.assertEqual(ratios["publication_point"]["ratio"], 0.45) + self.assertIsNone(ratios["signature"]["ratio"]) + stage["analysis_counts"]["publication_point_cache_reuse_hits"] = 21 + with self.assertRaises(ValueError): + hit_ratios(stage, "hybrid") + + def test_seven_metrics_fail_closed_on_clock_coverage_and_background_boundary(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + run, benchmark = root / "run", root / "t2" + run.mkdir(); benchmark.mkdir() + direct = {"schema_version": 1, "clock": "Linux CLOCK_MONOTONIC nanoseconds", + "rp_start_ns": 20, "payload_ready_ns": 100, "sync_wall_union_ns": 40, + "sync_intervals": [{"protocol": "rrdp", "uri": "good", "start_ns": 30, "end_ns": 60, "success": True}, + {"protocol": "rsync", "uri": "rsync://failed/repo/pp/", "start_ns": 50, "end_ns": 70, "success": False}], + "rrdp_modes": {"good": "delta"}, "sync_boundary": "native union", "payload_boundary": "atomic CCR"} + atomic_json(run / "evaluation.json", direct) + atomic_json(run / "contract.json", {"rsyncScopePolicy": "module-root"}) + stage = {"analysis_counts": {}, "roa_validation_cache": {"hit_roas": 0, "miss_roas": 0, "blocked_roas": 0}} + atomic_json(run / "stage-timing.json", stage) + engine = {"boundary": "validation with background write drain", "wall_ns": 15, "user_cpu_secs": 0.1, "system_cpu_secs": 0.1} + atomic_json(benchmark / "engine-timing.json", engine) + (run / "process-time.txt").write_text("Maximum resident set size (kbytes): 1234\n") + process = {"controller_trigger_monotonic_ns": 10, "cpu_ns": 500, "memory_peak_bytes": 9999} + table = {"rrdp": {"good": "Success"}, "rsync": {"rsync://failed/repo/": {"Failure": "captured gap"}}} + result = collect(run, benchmark, process, {"required_serialized_bytes": 0}, "baseline", table) + self.assertEqual(result["update_to_payload_ns"], 90) + self.assertEqual(result["repository_sync_ns"], 40) + self.assertEqual(result["peak_rss_bytes"], 1234 * 1024) + self.assertTrue((run / "transport-measurement-comparison.json").exists()) + with self.assertRaises(ValueError): + collect(run, benchmark, {**process, "controller_trigger_monotonic_ns": 21}, {"required_serialized_bytes": 0}, "baseline", table) + with self.assertRaises(ValueError): + collect(run, benchmark, process, {"required_serialized_bytes": 0}, "baseline", {**table, "rrdp": {}}) + atomic_json(benchmark / "engine-timing.json", {**engine, "boundary": "missing drain"}) + with self.assertRaises(ValueError): + collect(run, benchmark, process, {"required_serialized_bytes": 0}, "baseline", table) + + def test_transport_scope_mapping_preserves_each_raw_success_and_failure(self): + from formal_metrics import compare_transport_measurements + rows = [{"protocol": "rsync", "uri": "rsync://host:873/repo/a/0/", "success": True}, + {"protocol": "rsync", "uri": "rsync://host:873/repo/b/", "success": True}, + {"protocol": "rsync", "uri": "rsync://gap/repo/pp/", "success": False}, + {"protocol": "rrdp", "uri": "https://host/notification.xml", "success": True}] + table = {"rrdp": {"https://host/notification.xml": "Success"}, + "rsync": {"rsync://host:873/repo/": "Success", "rsync://gap/repo/": {"Failure": "gap"}}} + proof = compare_transport_measurements(rows, table, "module-root") + self.assertTrue(proof["pass"]) + self.assertEqual([r["uri"] for r in proof["intervals"]], [r["uri"] for r in rows]) + self.assertEqual([r["scope_uri"] for r in proof["intervals"][:2]], ["rsync://host:873/repo/"] * 2) + self.assertEqual([r["success"] for r in proof["intervals"]], [True, True, False, True]) + + def test_transport_scope_mapping_rejects_missing_extra_wrong_or_conflicting_rows(self): + from formal_metrics import compare_transport_measurements + good = {"protocol": "rsync", "uri": "rsync://host/repo/pp/", "success": True} + table = {"rrdp": {}, "rsync": {"rsync://host/repo/": "Success"}} + cases = [[], [{**good, "uri": "rsync://other/repo/pp/"}], + [{**good, "uri": "rsync://host/repository/pp/"}], + [good, {**good, "uri": "rsync://host/other/pp/"}], + [good, {**good, "success": False}], [{**good, "success": 1}], + [{**good, "protocol": "unknown"}]] + for rows in cases: + with self.subTest(rows=rows), self.assertRaises(ValueError): + compare_transport_measurements(rows, table, "module-root") + for outcome in ["Skipped", {}, {"Failure": None}]: + with self.subTest(outcome=outcome), self.assertRaises(ValueError): + compare_transport_measurements([good], {"rrdp": {}, "rsync": {"rsync://host/repo/": outcome}}, "module-root") + + def test_publication_and_host_scope_keep_fetch_uri_and_reject_unknown_policy(self): + from formal_metrics import compare_transport_measurements + row = {"protocol": "rsync", "uri": "rsync://host/repo/pp/", "success": True} + exact = {"rrdp": {}, "rsync": {row["uri"]: "Success"}} + module = {"rrdp": {}, "rsync": {"rsync://host/repo/": "Success"}} + for scope in ["publication-point", "host"]: + self.assertTrue(compare_transport_measurements([row], exact, scope)["pass"]) + with self.assertRaises(ValueError): + compare_transport_measurements([row], module, scope) + for scope in [None, "", "unknown"]: + with self.assertRaises(ValueError): + compare_transport_measurements([row], exact, scope) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/experiments/reuse_eval/test_replay.py b/scripts/experiments/reuse_eval/test_replay.py new file mode 100644 index 0000000..40b1de1 --- /dev/null +++ b/scripts/experiments/reuse_eval/test_replay.py @@ -0,0 +1,114 @@ +from http.server import ThreadingHTTPServer +import io +import json +from pathlib import Path +import tempfile +import threading +import unittest +import urllib.error +import urllib.request + +from common import Archive, atomic_json, now_ms +from prepare_replay import host_mapping, rsync_tree, tls_assets +from serve import ReplayState, handler_for, uri_key + + +class ReplayTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.archive = Archive(self.root / "archive") + self.ref = self.archive.put_stream(io.BytesIO(b"original notification bytes")) + self.observation = {"id": "observation", "uri": "https://rp.example/notification.xml", "complete": True, + "session": "session", "serial": 1, "notification": self.ref, "view": "view", "completed_ms": 1, + "references": []} + atomic_json(self.archive.root / "observations/observation.json", self.observation) + self.epoch = {"complete": True, "validation_time_ms": 2, "repositories": { + self.observation["uri"]: {k: self.observation[k] for k in ("id", "session", "serial", "notification", "view", "completed_ms")}}, + "ta_object_events": {}, "rsync_view_events": {}} + self.epoch_path = self.archive.root / "epochs/epoch_0000.json" + atomic_json(self.epoch_path, self.epoch) + + def test_uri_identity_preserves_query_and_normalizes_default_origin(self): + self.assertEqual(uri_key("https://RP.EXAMPLE:443/a?x=1"), uri_key("https://rp.example/a?x=1")) + self.assertNotEqual(uri_key("https://rp.example/a?x=1"), uri_key("https://rp.example/a?x=2")) + self.assertNotEqual(uri_key("https://rp.example:8443/a"), uri_key("https://rp.example/a")) + + def test_running_state_does_not_drift_when_epoch_file_changes(self): + state = ReplayState(self.archive.root, self.epoch_path) + self.observation["notification"] = self.archive.put_stream(io.BytesIO(b"future version")) + atomic_json(self.archive.root / "observations/observation.json", self.observation) + self.assertEqual(state.entries[uri_key("https://rp.example/notification.xml")]["sha256"], self.ref["sha256"]) + + def test_http_exact_bytes_conditional_and_unknown_uri(self): + state = ReplayState(self.archive.root, self.epoch_path) + server = ThreadingHTTPServer(("127.0.0.1", 0), handler_for(state, "https")) + self.addCleanup(server.server_close) + self.addCleanup(server.shutdown) + threading.Thread(target=server.serve_forever, daemon=True).start() + opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) + actual = f"http://127.0.0.1:{server.server_port}" + def request(path, **headers): + return opener.open(urllib.request.Request(actual + path, headers={"Host": "rp.example", **headers}), timeout=3) + with request("/notification.xml") as response: + self.assertEqual(response.read(), b"original notification bytes") + etag = response.headers["ETag"] + with self.assertRaises(urllib.error.HTTPError) as exc: + request("/notification.xml", **{"If-None-Match": etag}) + self.assertEqual(exc.exception.code, 304) + with self.assertRaises(urllib.error.HTTPError) as exc: + request("/missing.xml") + self.assertEqual(exc.exception.code, 404) + + def test_incomplete_and_future_bindings_are_rejected(self): + self.epoch["complete"] = False + atomic_json(self.epoch_path, self.epoch) + with self.assertRaises(ValueError): + ReplayState(self.archive.root, self.epoch_path) + self.epoch["complete"] = True + self.epoch["validation_time_ms"] = 0 + atomic_json(self.epoch_path, self.epoch) + with self.assertRaisesRegex(ValueError, "future"): + ReplayState(self.archive.root, self.epoch_path) + + def test_rsync_same_module_on_different_hosts_is_separated(self): + state = ReplayState(self.archive.root, self.epoch_path) + state.rsync_events = [{"completed_ms": 1, "kind": "view", "uri": f"rsync://{host}/repo/", + "objects": {f"rsync://{host}/repo/a.roa": self.ref}} for host in ("a.example", "b.example")] + mapping = host_mapping(["a.example", "b.example"]) + self.assertNotEqual(mapping["a.example"], mapping["b.example"]) + configs = rsync_tree(state, self.root / "rsync", mapping) + self.assertEqual(len(configs), 2) + for path in configs: + file = Path(path).parent / "modules/repo/a.roa" + self.assertEqual(file.read_bytes(), b"original notification bytes") + + def test_newer_rsync_scope_preserves_deletions(self): + state = ReplayState(self.archive.root, self.epoch_path) + state.rsync_events = [{"completed_ms": 1, "kind": "view", "uri": "rsync://a.example/repo/", + "objects": {"rsync://a.example/repo/a.roa": self.ref}}, + {"completed_ms": 2, "kind": "view", "uri": "rsync://a.example/repo/", "objects": {}}] + configs = rsync_tree(state, self.root / "rsync", host_mapping(["a.example"])) + self.assertEqual(len(configs), 1) + self.assertFalse(list((Path(configs[0]).parent / "modules/repo").iterdir())) + + def test_rsync_path_traversal_is_rejected(self): + state = ReplayState(self.archive.root, self.epoch_path) + state.rsync_events = [{"completed_ms": 1, "kind": "view", "uri": "rsync://a.example/repo/", + "objects": {"rsync://a.example/repo/../../escape": self.ref}}] + with self.assertRaisesRegex(ValueError, "unsafe"): + rsync_tree(state, self.root / "rsync", host_mapping(["a.example"])) + + def test_tls_assets_are_stable_and_do_not_accept_new_hosts_silently(self): + hosts = ["a.example", "b.example"] + first = tls_assets(self.root / "replay", hosts) + content = Path(first["ca"]).read_bytes() + second = tls_assets(self.root / "replay", hosts) + self.assertEqual(content, Path(second["ca"]).read_bytes()) + with self.assertRaises(ValueError): + tls_assets(self.root / "replay", hosts + ["c.example"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/experiments/reuse_eval/test_scope.py b/scripts/experiments/reuse_eval/test_scope.py new file mode 100644 index 0000000..7b652a6 --- /dev/null +++ b/scripts/experiments/reuse_eval/test_scope.py @@ -0,0 +1,257 @@ +import base64 +from email.message import Message +import io +from pathlib import Path +import tempfile +import unittest +from unittest.mock import Mock + +from common import Archive, atomic_json, file_sha256, read_json +from prepare_replay import host_mapping, rsync_tree +from rrdp import payload_view, view_digest +from scope import describe, load_scope, require_closure +from serve import ReplayState, handler_for, uri_key +from verify import verify + + +class ScopeTests(unittest.TestCase): + """Synthetic protocol/eligibility tests; never real-TA or performance evidence.""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.base = Path(self.tmp.name) + self.root = self.base / "archive" + self.archive = Archive(self.root) + self.uri = "https://rp.example/notification.xml" + self.excluded = "https://gap.example/notification.xml" + self.ta_uri = "https://ta.example/root.cer" + self.counts = {"repositories": 1, "excluded": 1, "epochs": 2, "trust_anchors": 1, "step_ms": 300_000} + tal = self.archive.put_stream(io.BytesIO(b"unit TAL")) + (self.root / "inputs").mkdir() + (self.root / "inputs/test.tal").write_bytes(b"unit TAL") + atomic_json(self.root / "contract.json", {"tals": [{**tal, "path": "test.tal"}]}) + atomic_json(self.root / "capture.json", {"t0_ms": 300_000, "end_ms": 600_000}) + atomic_json(self.root / "registry.json", {self.uri: {}, self.excluded: {}}) + self.body = b"exact unit publication bytes" + snapshot = (b'' + b'' + base64.b64encode(self.body) + b'') + snap = self.archive.put_stream(io.BytesIO(snapshot)) + note = self.archive.put_stream(io.BytesIO( + (f'' + f'').encode())) + self.view = payload_view(self.archive.blob_path(snap["sha256"]), "snapshot", "11111111-1111-4111-8111-111111111111", 1) + digest = view_digest(self.view) + atomic_json(self.root / f"views/{digest}.json", self.view) + ta_body = self.archive.put_stream(io.BytesIO(b"unit TA")) + atomic_json(self.root / "events/ta.json", {"id": "ta", "uri": self.ta_uri, "complete": True, + "completed_ms": 1, "transport": "http", "kind": "object", "body": ta_body}) + self.epoch_paths = [] + reports = [] + for i in range(2): + obs = {"id": f"obs{i}", "uri": self.uri, "complete": True, "completed_ms": i * 300_000 + 2, + "started_ms": i * 300_000 + 1, "session": "11111111-1111-4111-8111-111111111111", "serial": 1, "notification": note, + "view": digest, "references": [{**snap, "kind": "snapshot", "uri": "https://rp.example/snapshot.xml", + "serial": 1, "available": True}]} + atomic_json(self.root / f"observations/{obs['id']}.json", obs) + epoch = {"complete": False, "validation_time_ms": (i + 1) * 300_000, + "contract_sha256": file_sha256(self.root / "contract.json"), "missing": [self.excluded], + "blocked_latest_attempts": [], "repositories": {self.uri: {k: obs[k] for k in + ("id", "session", "serial", "notification", "view", "completed_ms")}}, + "latest_attempts": {self.uri: {k: obs[k] for k in ("id", "complete", "completed_ms")}, + self.excluded: {"complete": False}}, + "ta_object_events": {self.ta_uri: "ta"}, "rsync_view_events": {}} + path = self.root / f"epochs/epoch_{i:04d}.json" + atomic_json(path, epoch) + self.epoch_paths.append(path) + reports.append({"epoch": path.name, "pass": False, "repositories": 1, + "errors": [f"missing repositories: {[self.excluded]}"]}) + atomic_json(self.root / "closure-report.json", {"pass": False, "errors": [], "epochs": reports}) + self.scope_path = self.base / "scope/scope.json" + + def scope(self, routes=None): + result = describe(self.root, routes or {}, self.counts) + atomic_json(self.scope_path, result) + return result + + def fingerprint(self): + return {str(p.relative_to(self.root)): (file_sha256(p), p.stat().st_mode) + for p in self.root.rglob("*") if p.is_file()} + + def native_route(self): + scope_uri = "rsync://rp.example/repo/" + obj = self.archive.put_stream(io.BytesIO(self.body)) + event = {"id": "native", "uri": scope_uri, "complete": True, "source": "rpki", "kind": "view", + "transport": "rsync", "started_ms": 400_000, "completed_ms": 500_000, + "objects": {"rsync://rp.example/repo/a.roa": obj}} + atomic_json(self.root / "events/native.json", event) + epoch = read_json(self.epoch_paths[1]) + epoch["rsync_view_events"] = {scope_uri: "native"} + atomic_json(self.epoch_paths[1], epoch) + return {self.epoch_paths[1].name: {self.uri: {"rsync_uri": scope_uri, "event_id": "native", "http_status": 503}}} + + def request(self, state, uri, etag=None): + handler = handler_for(state, "https").__new__(handler_for(state, "https")) + handler.path = "/" + uri.split("/", 3)[3] + handler.headers = Message() + handler.headers["Host"] = uri.split("/", 3)[2] + if etag: + handler.headers["If-None-Match"] = etag + handler.wfile = io.BytesIO() + handler.send_response, handler.send_header, handler.end_headers = Mock(), Mock(), Mock() + handler.handle_entity(head=False) + return handler.send_response.call_args.args[0], handler.wfile.getvalue() + + def test_scope_verify_keeps_original_incomplete_and_all_source_bytes(self): + before = self.fingerprint() + self.scope() + self.assertEqual(load_scope(self.root, self.scope_path)["counts"], self.counts) + result = verify(self.root, self.scope_path) + self.assertTrue(result["pass"], result) + self.assertFalse(result["original_complete"]) + self.assertEqual(len(result["epochs"]), 2) + self.assertEqual(self.fingerprint(), before) + + def test_scope_and_report_cannot_overwrite_original(self): + self.scope() + with self.assertRaisesRegex(ValueError, "outside"): + load_scope(self.root, self.root / "scope.json") + with self.assertRaisesRegex(ValueError, "outside"): + verify(self.root, self.scope_path, self.root / "closure-report.json") + with self.assertRaisesRegex(ValueError, "overwrite scope"): + verify(self.root, self.scope_path, self.scope_path) + (self.root / "escape.json").symlink_to(self.base / "outside.json") + with self.assertRaisesRegex(ValueError, "outside"): + verify(self.root, self.scope_path, self.root / "escape.json") + + def test_no_scope_still_rejects_incomplete_epoch(self): + with self.assertRaisesRegex(ValueError, "incomplete"): + ReplayState(self.root, self.epoch_paths[0]) + self.scope() + state = ReplayState(self.root, self.epoch_paths[0], self.scope_path) + self.assertEqual(self.request(state, self.ta_uri), (200, b"unit TA")) + self.assertEqual(self.request(state, self.excluded), (503, b"")) + self.assertEqual(self.request(state, "https://unknown.example/a"), (404, b"")) + + def test_unavailable_blob_fails_scoped_closure_without_modifying_original_report(self): + self.scope() + before = file_sha256(self.root / "closure-report.json") + ta = read_json(self.root / "events/ta.json") + self.archive.blob_path(ta["body"]["sha256"]).unlink() + result = verify(self.root, self.scope_path) + self.assertFalse(result["pass"]) + self.assertTrue(result["errors"]) + self.assertEqual(file_sha256(self.root / "closure-report.json"), before) + + def test_server_requires_successful_independent_scoped_closure(self): + self.scope() + with self.assertRaises(FileNotFoundError): + require_closure(self.root, self.scope_path) + verify(self.root, self.scope_path) + require_closure(self.root, self.scope_path) + path = self.scope_path.with_name("scoped-closure-report.json") + report = read_json(path) + report["scope_sha256"] = "0" * 64 + atomic_json(path, report) + with self.assertRaisesRegex(ValueError, "closure"): + require_closure(self.root, self.scope_path) + + def test_source_or_scope_tampering_rejected(self): + scope = self.scope() + scope["included_repositories"] = [] + atomic_json(self.scope_path, scope) + with self.assertRaisesRegex(ValueError, "provenance"): + load_scope(self.root, self.scope_path) + self.scope() + atomic_json(self.root / "contract.json", {"tals": []}) + with self.assertRaisesRegex(ValueError, "trust anchors"): + load_scope(self.root, self.scope_path) + + def test_new_epoch_missing_epoch_or_shifted_time_rejected(self): + for change in ("extra", "missing", "time"): + with self.subTest(change=change): + path = self.epoch_paths[1] + original = read_json(path) + if change == "extra": + atomic_json(self.root / "epochs/epoch_0002.json", original) + elif change == "missing": + path.unlink() + else: + atomic_json(path, {**original, "validation_time_ms": 600_001}) + with self.assertRaises(ValueError): + self.scope() + (self.root / "epochs/epoch_0002.json").unlink(missing_ok=True) + atomic_json(path, original) + + def test_failed_latest_future_binding_and_lost_ta_rejected(self): + path = self.epoch_paths[1] + original = read_json(path) + for change in ("latest", "future", "ta", "scope"): + epoch = read_json(path) + if change == "latest": + epoch["latest_attempts"][self.uri]["complete"] = False + elif change == "future": + epoch["repositories"][self.uri]["completed_ms"] = 600_001 + epoch["latest_attempts"][self.uri]["completed_ms"] = 600_001 + elif change == "ta": + epoch["ta_object_events"] = {} + else: + epoch["repositories"]["https://changed.example/n"] = epoch["repositories"].pop(self.uri) + atomic_json(path, epoch) + with self.subTest(change=change), self.assertRaises(ValueError): + self.scope() + atomic_json(path, original) + + def test_non_coverage_closure_error_cannot_be_waived(self): + report = read_json(self.root / "closure-report.json") + report["epochs"][1]["errors"].append("bad delta hash") + atomic_json(self.root / "closure-report.json", report) + with self.assertRaisesRegex(ValueError, "unapproved"): + self.scope() + + def test_native_route_only_applies_to_bound_epoch_and_never_returns_304(self): + routes = self.native_route() + self.scope(routes) + early = ReplayState(self.root, self.epoch_paths[0], self.scope_path) + final = ReplayState(self.root, self.epoch_paths[1], self.scope_path) + self.assertEqual(self.request(early, self.uri)[0], 200) + etag = '"sha256:' + final.entries[uri_key(self.uri)]["sha256"] + '"' + self.assertEqual(self.request(final, self.uri, etag), (503, b"")) + self.assertEqual(len(early.rsync_events), 0) + self.assertEqual(len(final.rsync_events), 1) + self.assertTrue(verify(self.root, self.scope_path)["pass"]) + + def test_native_route_rejects_future_foreign_or_unbound_event(self): + routes = self.native_route() + original = read_json(self.root / "events/native.json") + for change in ({"completed_ms": 600_001}, {"source": "derived"}, {"complete": False}): + atomic_json(self.root / "events/native.json", {**original, **change}) + with self.subTest(change=change), self.assertRaises(ValueError): + self.scope(routes) + atomic_json(self.root / "events/native.json", original) + with self.assertRaisesRegex(ValueError, "explicit route"): + self.scope() + + def test_rsync_assets_do_not_change_or_share_archived_inode(self): + self.scope(self.native_route()) + state = ReplayState(self.root, self.epoch_paths[1], self.scope_path) + before = self.fingerprint() + configs = rsync_tree(state, self.base / "rsync", host_mapping(["rp.example"])) + target = Path(configs[0]).parent / "modules/repo/a.roa" + source = self.archive.blob_path(state.rsync_events[0]["objects"]["rsync://rp.example/repo/a.roa"]["sha256"]) + self.assertEqual(target.read_bytes(), self.body) + self.assertNotEqual(target.stat().st_ino, source.stat().st_ino) + self.assertEqual(self.fingerprint(), before) + + def test_readonly_archive_never_creates_directories_or_events(self): + root = self.base / "missing" + archive = Archive(root, read_only=True) + self.assertFalse(root.exists()) + with self.assertRaisesRegex(ValueError, "read-only"): + archive.put_stream(io.BytesIO(b"no")) + with self.assertRaisesRegex(ValueError, "read-only"): + archive.event({}) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/experiments/reuse_eval/test_sequence_matrix.py b/scripts/experiments/reuse_eval/test_sequence_matrix.py new file mode 100644 index 0000000..f1b67d4 --- /dev/null +++ b/scripts/experiments/reuse_eval/test_sequence_matrix.py @@ -0,0 +1,166 @@ +from pathlib import Path +import copy +import tempfile +import unittest +from unittest.mock import Mock, patch + +from common import atomic_json, read_json +from sequence_matrix import PROFILE_FLAGS, compare_profile_contracts, payload_counts, require_ready, require_t2_fallback_bindings, require_transport, rp_command, run_pilot, systemd_measure + + +class SequenceMatrixTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + + def test_commands_preserve_protocol_state_and_use_full_scope(self): + private = self.root / "object" + manifest = {"tls": {"ca": "/fixture/ca.pem"}} + command1 = rp_command(Path("/fixture/rpki"), private, private / "step_0000", manifest, + 1794218084957, "object", ["--tal-path", "/fixture/a.tal", "--ta-path", "/fixture/a.cer"]) + command2 = rp_command(Path("/fixture/rpki"), private, private / "step_0001", manifest, + 1794218384957, "object", ["--tal-path", "/fixture/a.tal", "--ta-path", "/fixture/a.cer"]) + self.assertEqual(command1[command1.index("--db") + 1], command2[command2.index("--db") + 1]) + self.assertNotIn("--max-instances", command1) + self.assertNotIn("--disable-rrdp", command1) + self.assertNotIn("--enable-crypto-signature-cache", command1) + self.assertEqual(command2[command2.index("--validation-time") + 1], "2026-11-09T09:59:44Z") + self.assertEqual(set(PROFILE_FLAGS), {"baseline", "signature", "object", "pp", "hybrid"}) + self.assertEqual(PROFILE_FLAGS["baseline"], []) + self.assertEqual(set(PROFILE_FLAGS["hybrid"]), set(PROFILE_FLAGS["object"] + PROFILE_FLAGS["pp"])) + + def test_native_route_and_scope_must_match_actual_outcomes(self): + scope = {"included_repositories": ["good", "fallback"], "excluded_repositories": ["gap"], + "routes": {"epoch_0012.json": {"fallback": {"rsync_uri": "rsync://native/repo/"}}}} + table = {"rrdp": {"good": "Success", "fallback": {"Failure": "recorded"}, "gap": {"Failure": "excluded"}}, + "rsync": {"rsync://native/repo/": "Success"}} + require_transport(table, scope, "epoch_0012.json") + for key, value in (("fallback", "Success"), ("good", {"Failure": "new failure"}), ("gap", "Success")): + changed = {"rrdp": {**table["rrdp"], key: value}, "rsync": table["rsync"]} + with self.subTest(key=key), self.assertRaises(ValueError): + require_transport(changed, scope, "epoch_0012.json") + with self.assertRaises(ValueError): + require_transport({**table, "rsync": {}}, scope, "epoch_0012.json") + with self.assertRaises(ValueError): + require_transport({**table, "rrdp": {**table["rrdp"], "unbound": "Success"}}, scope, "epoch_0012.json") + + def test_full_payload_counts_do_not_require_loading_the_report(self): + stdout = self.root / "stdout.log" + stdout.write_text("vrps=1046609\naspas=4046\naudit_publication_points=56142\n") + self.assertEqual(payload_counts(self.root), {"vrps": 1046609, "aspas": 4046, "publication_points": 56142}) + for body in ("vrps=0\naspas=1\naudit_publication_points=1\n", "vrps=1\n", + "vrps=1\nvrps=2\naspas=1\naudit_publication_points=1\n"): + stdout.write_text(body) + with self.assertRaises(ValueError): + payload_counts(self.root) + + def test_readiness_rejects_wrong_scope_or_dead_server(self): + ready = self.root / "ready.json" + atomic_json(ready, {"epoch": "epoch", "scope": "scope"}) + server = Mock() + server.poll.return_value = None + self.assertEqual(require_ready(ready, server, "epoch", "scope")["epoch"], "epoch") + with self.assertRaisesRegex(ValueError, "different"): + require_ready(ready, server, "epoch", "another-scope") + server.poll.return_value = 1 + with self.assertRaisesRegex(RuntimeError, "exited"): + require_ready(ready, server, "epoch", "scope") + + def test_cgroup_measurement_retains_accounting_then_stops_only_own_unit(self): + properties = "\n".join(["ActiveState=active", "SubState=exited", "Result=success", "ExecMainCode=1", + "ExecMainStatus=0", "CPUUsageNSec=1000000000", "MemoryPeak=2000000"]) + with patch("sequence_matrix.call", side_effect=[Mock(), Mock(stdout=properties)]) as call_mock, \ + patch("sequence_matrix.subprocess.run") as stop_mock: + result = systemd_measure(["/fixture/rpki", "--db", "/fixture/state/db"], self.root, {"TMPDIR": "/fixture/tmp"}, 5) + self.assertEqual(result["cpu_ns"], 1000000000) + self.assertEqual(result["memory_peak_bytes"], 2000000) + launcher = call_mock.call_args_list[0].args[0] + self.assertIn("RemainAfterExit=yes", launcher) + self.assertIn("AllowedCPUs=1-3", launcher) + self.assertIn("MemoryMax=5G", launcher) + self.assertIn("rp187rp", launcher) + self.assertEqual(stop_mock.call_args.args[0], ["systemctl", "stop", result["unit"]]) + self.assertEqual(read_json(self.root / "process-resource.json")["cpu_ns"], 1000000000) + + def test_failed_cgroup_sample_does_not_publish_valid_metrics_and_is_stopped(self): + props = "ActiveState=failed\nSubState=failed\nResult=oom-kill\nExecMainStatus=9\n" + with patch("sequence_matrix.call", side_effect=[Mock(), Mock(stdout=props)]), \ + patch("sequence_matrix.subprocess.run") as stop_mock: + with self.assertRaisesRegex(RuntimeError, "failed"): + systemd_measure(["/fixture/rpki"], self.root, {"TMPDIR": "/fixture/tmp"}, 5) + self.assertFalse((self.root / "process-resource.json").exists()) + self.assertTrue((self.root / "systemd-final.json").exists()) + self.assertEqual(stop_mock.call_args.args[0][:2], ["systemctl", "stop"]) + + def test_pilot_never_executes_on_an_unassigned_machine(self): + with patch("sequence_matrix.socket.gethostname", return_value="unassigned"), \ + patch("sequence_matrix.call") as call_mock: + with self.assertRaisesRegex(ValueError, "designated 186"): + run_pilot({}) + call_mock.assert_not_called() + + def test_cross_profile_contract_allows_different_cache_histories_only(self): + baseline = {"cache": {"publicationPoint": False}, "validationTime": "2026-11-09T10:49:44Z", + "binarySha256": "33" * 32, "policy": {"strict": True}, + "fallbackReplaySelections": [{"manifestRsyncUri": "rsync://example/repo/a.mft", + "vcirSha256": "11" * 32, "reuseIdentitySha256": "22" * 32}]} + actual = copy.deepcopy(baseline) + actual["cache"]["publicationPoint"] = True + actual["fallbackReplaySelections"][0].update(vcirSha256="44" * 32, reuseIdentitySha256="55" * 32) + proof = compare_profile_contracts(actual, baseline) + self.assertTrue(proof["pass"]) + self.assertEqual(proof["baseline_fallback"], baseline["fallbackReplaySelections"]) + self.assertEqual(proof["actual_fallback"], actual["fallbackReplaySelections"]) + for field, value in [("validationTime", "2026-11-09T10:44:44Z"), + ("binarySha256", "66" * 32), ("policy", {"strict": False}), + ("unexpectedPolicyField", True)]: + bad = copy.deepcopy(actual) + bad[field] = value + with self.subTest(field=field), self.assertRaisesRegex(ValueError, "configuration"): + compare_profile_contracts(bad, baseline) + for mutation in [lambda rows: rows.clear(), + lambda rows: rows.append(copy.deepcopy(rows[0])), + lambda rows: rows[0].update(manifestRsyncUri="rsync://example/repo/b.mft"), + lambda rows: rows[0].update(vcirSha256="bad"), + lambda rows: rows[0].update(reuseIdentitySha256=""), + lambda rows: rows[0].update(extra=True)]: + bad = copy.deepcopy(actual) + mutation(bad["fallbackReplaySelections"]) + with self.assertRaises(ValueError): + compare_profile_contracts(bad, baseline) + self.assertEqual(actual["fallbackReplaySelections"][0]["vcirSha256"], "44" * 32) + + def test_cross_profile_contract_checks_no_fallback_and_ordering(self): + self.assertTrue(compare_profile_contracts({"cache": {}}, {"cache": {}})["pass"]) + a = {"manifestRsyncUri": "rsync://example/a.mft", "vcirSha256": "11" * 32, + "reuseIdentitySha256": "22" * 32} + b = {**a, "manifestRsyncUri": "rsync://example/b.mft"} + for rows in [[b, a], [a, a], None, {}, "bad"]: + with self.subTest(rows=rows), self.assertRaises(ValueError): + compare_profile_contracts({"fallbackReplaySelections": rows}, {}) + + def test_t2_must_use_its_own_exact_cache_binding(self): + selected = [{"manifestRsyncUri": "rsync://example/a.mft", "vcirSha256": "11" * 32, + "reuseIdentitySha256": "22" * 32}] + contract = {"fallbackReplaySelections": selected} + equivalence = {"fallback": {"matches": True, "expected": copy.deepcopy(selected), + "actual": copy.deepcopy(selected), "missing": [], "unexpected": []}} + require_t2_fallback_bindings(contract, equivalence) + for part in ("expected", "actual"): + for field in ("manifestRsyncUri", "vcirSha256", "reuseIdentitySha256"): + bad = copy.deepcopy(equivalence) + bad["fallback"][part][0][field] = "different" + with self.subTest(part=part, field=field), self.assertRaises(ValueError): + require_t2_fallback_bindings(contract, bad) + for field, value in [("matches", False), ("missing", selected), ("unexpected", selected)]: + bad = copy.deepcopy(equivalence) + bad["fallback"][field] = value + with self.subTest(field=field), self.assertRaises(ValueError): + require_t2_fallback_bindings(contract, bad) + with self.assertRaises(ValueError): + require_t2_fallback_bindings(contract, {}) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/experiments/reuse_eval/test_single_formal.py b/scripts/experiments/reuse_eval/test_single_formal.py new file mode 100644 index 0000000..d819231 --- /dev/null +++ b/scripts/experiments/reuse_eval/test_single_formal.py @@ -0,0 +1,141 @@ +import copy +import json +from pathlib import Path +import tempfile +import unittest +from unittest.mock import patch + +from campaign import SCALARS +from common import file_sha256 +from sequence_matrix import PROFILE_FLAGS +import single_formal as single + + +def matrix_fixture(): + rows = [] + for profile in PROFILE_FLAGS: + enabled = {'signature': profile == 'signature', 'roa': profile in ('object', 'hybrid'), + 'child_certificate': profile in ('object', 'hybrid'), 'publication_point': profile in ('pp', 'hybrid')} + for step in range(13): + ratios = {layer: {'enabled': on, 'hits': step if on else 0, 'queries': step + 1 if on else 0, + 'ratio': step / (step + 1) if on else None} for layer, on in enabled.items()} + metrics = {'schema': 'rpki-reuse-seven-metrics-v1', 'profile': profile, + **{key: 1000 + step for key in SCALARS}, 'cache_hit_ratio': ratios} + rows.append({'profile': profile, 'step': step, 'pass': True, 'seven_metrics': metrics}) + return {'status': 'completed', 'pass': True, 'performance_ready': True, 'scope_sha256': 'scope', + 'tool_sha256': {'binary': 'binary'}, 'runs': rows, + 'restoration': {'rp187rp': 0, 'rp187srv': 0, 'panda_active': True, 'panda_container_running': True}} + + +class SingleFormalTests(unittest.TestCase): + def test_one_repeat_keeps_all_65_measurements_and_no_repeat_confidence_claims(self): + summary = matrix_fixture() + result = single.report(summary) + self.assertEqual((result['repeats'], result['pairs']), (1, 65)) + self.assertEqual(len(result['groups']), 25) + warm = next(g for g in result['groups'] if g['profile'] == 'pp' and g['steps'] == 'incremental') + self.assertEqual(warm['independent_repeats'], 1) + self.assertEqual(warm['n_steps'], 12) + self.assertEqual(warm['metrics']['rp_validation_ns']['mean'], 1006.5) + self.assertNotIn('stdev', warm['metrics']['rp_validation_ns']) + self.assertEqual(warm['cache_hit_ratio']['publication_point'], {'hits': 78, 'queries': 90, 'ratio': 78 / 90}) + + def test_csv_has_65_unique_rows_and_raw_hit_denominators(self): + rows = single.csv_rows(matrix_fixture()) + self.assertEqual(len(rows), 65) + self.assertEqual(len({(r['repeat'], r['profile'], r['step']) for r in rows}), 65) + self.assertEqual(rows[-1]['publication_point_hits'], 12) + self.assertEqual(rows[-1]['publication_point_queries'], 13) + self.assertTrue(all(r['repeat'] == 1 for r in rows)) + + def test_missing_metric_nonfinite_and_wrong_layer_are_rejected(self): + for case in ['missing', 'nan', 'negative', 'wrong-layer', 'zero-payload']: + summary = matrix_fixture() + metric = summary['runs'][0]['seven_metrics'] + if case == 'missing': + del metric['repository_sync_ns'] + elif case == 'nan': + metric['cpu_ns'] = float('nan') + elif case == 'negative': + metric['cache_size_bytes'] = -1 + elif case == 'zero-payload': + metric['update_to_payload_ns'] = 0 + else: + metric['cache_hit_ratio']['signature'].update(hits=1, queries=1, ratio=1) + with self.subTest(case=case), self.assertRaises(ValueError): + single.report(summary) + + def test_missing_duplicate_and_unrestored_matrices_cannot_finish(self): + for case in ['missing', 'duplicate', 'restore', 'not-formal']: + summary = matrix_fixture() + if case == 'missing': + summary['runs'].pop() + elif case == 'duplicate': + summary['runs'][-1] = summary['runs'][0] + elif case == 'restore': + summary['restoration']['panda_active'] = False + else: + summary['performance_ready'] = False + with self.subTest(case=case), self.assertRaises(ValueError): + single.report(summary) + + def prerequisite_fixture(self, root): + tools = {} + for name in ['binary', 'ccr_compare', 'cir_compare', 'db_stats']: + path = root / name + path.write_text(name) + tools[name] = str(path) + scope = root / 'scope.json' + scope.write_text('{}') + build = {name: file_sha256(Path(path)) for name, path in tools.items()} + repeat = dict(tools, archive=str(root / 'archive'), scope=str(scope), expected_binary_sha256=build['binary'], + expected_scope_sha256=file_sha256(scope), formal_metrics=True, + profile_order=list(PROFILE_FLAGS), run_timeout_secs=1800) + package = Path(single.__file__).parent + scripts = {p.name: file_sha256(p) for p in package.glob('*.py') if not p.name.startswith('test_')} + previous = {k: v for k, v in scripts.items() if k != 'single_formal.py'} + previous['formal_metrics.py'] = 'old-collector' + pilot = matrix_fixture() + pilot.update(config=repeat.copy(), tool_sha256=build, scope_sha256=repeat['expected_scope_sha256'], scripts_sha256=previous) + pilot['config']['formal_metrics'] = False + path = root / 'pilot/summary.json' + path.parent.mkdir() + (path.parent / 'bin').mkdir() + (path.parent / 'bin/binary').write_text('binary') + path.write_text(json.dumps(pilot)) + config = {'pilot_summary': str(path), 'expected_pilot_summary_sha256': file_sha256(path), + 'repeat': repeat, 'expected_tools_sha256': build, 'expected_pilot_scripts_sha256': previous, + 'expected_scripts_sha256': scripts} + return config + + def test_preserved_pilot_reused_only_with_identical_inputs_build_and_65_proofs(self): + with tempfile.TemporaryDirectory() as temp: + config = self.prerequisite_fixture(Path(temp)) + with patch.object(single, 'require_row_proofs') as proofs: + result = single.require_prerequisite(config) + self.assertTrue(result['pass']) + self.assertEqual(proofs.call_count, 65) + self.assertEqual(result['pairs_checked'], 65) + + def test_changed_pilot_scope_binary_order_engine_or_disabled_formal_rejected(self): + for case in ['pilot-hash', 'scope', 'binary', 'order', 'engine', 'formal-off']: + with self.subTest(case=case), tempfile.TemporaryDirectory() as temp: + config = self.prerequisite_fixture(Path(temp)) + if case == 'pilot-hash': + config['expected_pilot_summary_sha256'] = 'other' + elif case == 'scope': + config['repeat']['scope'] = str(Path(temp) / 'other') + elif case == 'binary': + Path(config['repeat']['binary']).write_text('changed') + elif case == 'order': + config['repeat']['profile_order'] = ['baseline'] + elif case == 'engine': + config['expected_scripts_sha256']['sequence_matrix.py'] = 'changed' + else: + config['repeat']['formal_metrics'] = False + with patch.object(single, 'require_row_proofs'), self.assertRaises(ValueError): + single.require_prerequisite(config) + + +if __name__ == '__main__': + unittest.main() diff --git a/scripts/experiments/reuse_eval/test_smoke_matrix.py b/scripts/experiments/reuse_eval/test_smoke_matrix.py new file mode 100644 index 0000000..3b5b4cd --- /dev/null +++ b/scripts/experiments/reuse_eval/test_smoke_matrix.py @@ -0,0 +1,65 @@ +"""Regression for comparator tools whose successful exit only means they wrote a report.""" +import json +from pathlib import Path +import tempfile +import unittest + +from smoke_matrix import cache_counters, require_comparison, snapshot_pre_state + + +class SemanticGateTests(unittest.TestCase): + def test_checkpoint_includes_signature_and_mmap_sidecars_without_shared_writes(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + state = root / "state" + (state / "db").mkdir(parents=True) + (state / "db/000001.sst").write_bytes(b"old-db") + for suffix in (".crypto-sig-cache", ".pp-cache-index", ".child-cert-cache-index"): + (state / ("db" + suffix)).write_bytes(b"old-sidecar") + proof = snapshot_pre_state(state, root / "checkpoint") + self.assertEqual(len(proof["files_sha256"]), 4) + (state / "db.crypto-sig-cache").write_bytes(b"post-step-success") + self.assertEqual((root / "checkpoint/db.crypto-sig-cache").read_bytes(), b"old-sidecar") + + def test_signature_gate_checks_loaded_entries_and_per_point_hits(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + stage = {"crypto_signature_cache_observe": {"entries_loaded": 0, "entries_total": 1, + "per_point": {"crl": {"calls": 1, "would_hit": 0, "verify_executed": 1, + "verify_skipped": 0, "verify_nanos_on_new_key": 100}}}, + "roa_validation_cache": {"hit_roas": 0, "lookup_nanos": 10}, + "analysis_counts": {"roa_validation_cache_context_gate_nanos": 100, + "publication_point_cache_reuse_nonzero_ms_total": 2, + "publication_point_cache_reuse_nonzero_ms_hits": 1, + "child_certificate_cache_hit": 5}} + path = root / "stage-timing.json" + path.write_text(json.dumps(stage)) + cold = cache_counters(root) + stage["analysis_counts"]["roa_validation_cache_context_gate_nanos"] = 200 + stage["analysis_counts"]["publication_point_cache_reuse_nonzero_ms_total"] = 3 + stage["analysis_counts"]["publication_point_cache_reuse_nonzero_ms_hits"] = 2 + path.write_text(json.dumps(stage)) + self.assertEqual(cold, cache_counters(root)) + stage["analysis_counts"]["child_certificate_cache_hit"] = 6 + path.write_text(json.dumps(stage)) + self.assertNotEqual(cold, cache_counters(root)) + stage["analysis_counts"]["child_certificate_cache_hit"] = 5 + stage["crypto_signature_cache_observe"]["entries_loaded"] = 1 + path.write_text(json.dumps(stage)) + self.assertNotEqual(cold, cache_counters(root)) + self.assertNotIn("lookup_nanos", cold["roa"]) + + def test_zero_exit_difference_report_is_rejected(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "comparison.json" + for kind, field in (("cir", "allMatch"), ("ccr", "stateDigestMatch")): + for value in (False, None, "true", 1): + path.write_text(json.dumps({field: value})) + with self.assertRaisesRegex(ValueError, "semantic comparison failed"): + require_comparison(path, kind) + path.write_text(json.dumps({field: True})) + require_comparison(path, kind) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/experiments/reuse_eval/verify.py b/scripts/experiments/reuse_eval/verify.py new file mode 100644 index 0000000..5769562 --- /dev/null +++ b/scripts/experiments/reuse_eval/verify.py @@ -0,0 +1,156 @@ +#!/usr/bin/env python3 +"""Check blob integrity, selected observation closure and time boundaries.""" +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +from common import Archive, atomic_json, file_sha256, read_json +from rrdp import notification, payload_view, view_digest + + +def verify(root: Path, scope_path: Path | None = None, report_path: Path | None = None) -> dict: + scope = None + if scope_path is not None: + from scope import load_scope, outside_archive + scope = load_scope(root, scope_path) + report_path = report_path or scope_path.with_name("scoped-closure-report.json") + outside_archive(root, report_path) + if report_path.resolve() == scope_path.resolve(): + raise ValueError("scoped report cannot overwrite scope") + archive = Archive(root, read_only=True) + checked, errors, epochs = {}, [], [] + def check(ref): + if ref["sha256"] in checked and checked[ref["sha256"]] != ref["size"]: + raise ValueError("inconsistent blob size references") + if ref["sha256"] not in checked: + archive.verify_blob(ref) + checked[ref["sha256"]] = ref["size"] + # Check even unselected successful content and preserved failed/partial views. + events = {} + for path in (root / "events").glob("*.json"): + event = read_json(path) + events[event["id"]] = event + try: + if event.get("body"): + check(event["body"]) + for ref in event.get("objects", {}).values(): + check(ref) + except Exception as exc: + errors.append({"event": event["id"], "error": str(exc)}) + observations = {p.stem: read_json(p) for p in (root / "observations").glob("*.json")} + contract_hash = None + if (root / "contract.json").exists(): + contract_hash = file_sha256(root / "contract.json") + try: + contract = read_json(root / "contract.json") + for tal in contract["tals"]: + check(tal) + pinned = root / "inputs" / Path(tal["path"]).name + if file_sha256(pinned) != tal["sha256"]: + raise ValueError("pinned TAL content mismatch") + if tal.get("constraints_sha256") and file_sha256(pinned.with_suffix(".constraints")) != tal["constraints_sha256"]: + raise ValueError("pinned constraints mismatch") + except Exception as exc: + errors.append({"contract": "contract.json", "error": str(exc)}) + # Independently recheck every accepted transition, including minute states + # between selected five-minute epochs. Never just trust the collector's label. + for item in observations.values(): + if not item["complete"] or not item.get("base_observation_id"): + continue + try: + base = observations[item["base_observation_id"]] + if not base["complete"] or base["uri"] != item["uri"] or base["completed_ms"] > item["started_ms"]: + raise ValueError("invalid observation predecessor") + if base["session"] != item["session"]: + if item["chain"] != "session_reset_snapshot": + raise ValueError("session reset not recorded") + continue + if item["serial"] < base["serial"]: + raise ValueError("serial rollback") + view = read_json(root / "views" / f"{base['view']}.json") + if item["serial"] - base["serial"] > 10000: + raise ValueError("delta chain size bound") + deltas = {r["serial"]: r for r in item["references"] if r["kind"] == "delta"} + for serial in range(base["serial"] + 1, item["serial"] + 1): + ref = deltas[serial] + if not ref["available"]: + raise ValueError("required delta missing") + check({"sha256": ref["sha256"], "size": ref["size"]}) + view = payload_view(archive.blob_path(ref["sha256"]), "delta", item["session"], serial, view) + if view_digest(view) != item["view"]: + raise ValueError("delta transition view mismatch") + except Exception as exc: + errors.append({"observation": item["id"], "error": str(exc)}) + views_checked = set() + for path in sorted((root / "epochs").glob("epoch_*.json")): + epoch = read_json(path) + epoch_errors = [] + if epoch.get("contract_sha256") != contract_hash: + epoch_errors.append("capture contract hash mismatch") + if not epoch["complete"] and scope is None: + epoch_errors.append(f"missing repositories: {epoch['missing']}") + if epoch.get("blocked_latest_attempts"): + epoch_errors.append(f"latest observations failed: {epoch['blocked_latest_attempts']}") + for uri, binding in epoch["repositories"].items(): + try: + observation = observations[binding["id"]] + if not observation["complete"] or observation["completed_ms"] > epoch["validation_time_ms"]: + raise ValueError("incomplete/future observation selected") + for key in ("uri", "session", "serial", "notification", "view", "completed_ms"): + expected = uri if key == "uri" else binding[key] + if observation[key] != expected: + raise ValueError(f"observation binding mismatch: {key}") + check(observation["notification"]) + parsed = notification(archive.blob_path(observation["notification"]["sha256"]), uri) + if parsed["session"] != binding["session"] or parsed["serial"] != binding["serial"]: + raise ValueError("notification binding mismatch") + refs = {(r["kind"], r["serial"], r["uri"], r["sha256"]) for r in parsed["references"]} + recorded = {(r["kind"], r["serial"], r["uri"], r["sha256"]) for r in observation["references"]} + if refs != recorded: + raise ValueError("notification reference list mismatch") + for ref in observation["references"]: + if ref["available"]: + check({"sha256": ref["sha256"], "size": ref["size"]}) + snapshot = next(r for r in observation["references"] if r["kind"] == "snapshot") + identity = (snapshot["sha256"], binding["view"]) + if identity not in views_checked: + view = payload_view(archive.blob_path(snapshot["sha256"]), "snapshot", binding["session"], binding["serial"]) + if view_digest(view) != binding["view"]: + raise ValueError("snapshot view digest mismatch") + if read_json(root / "views" / f"{binding['view']}.json") != view: + raise ValueError("stored view differs from snapshot") + views_checked.add(identity) + except Exception as exc: + epoch_errors.append({"uri": uri, "error": str(exc)}) + for uri, event_id in list(epoch["ta_object_events"].items()) + list(epoch["rsync_view_events"].items()): + event = events.get(event_id) + if not event or event["uri"] != uri or not event["complete"] or event["completed_ms"] > epoch["validation_time_ms"]: + epoch_errors.append({"event": event_id, "error": "missing/incomplete/future transport view"}) + epochs.append({"epoch": path.name, "repositories": len(epoch["repositories"]), "pass": not epoch_errors, "errors": epoch_errors}) + if not epochs: + errors.append({"error": "no epochs"}) + result = {"pass": not errors and all(e["pass"] for e in epochs), "checked_blobs": len(checked), + "events": len(events), "observations": len(observations), "epochs": epochs, "errors": errors} + if scope is not None: + result.update(scope_sha256=file_sha256(scope_path), source_contract_sha256=contract_hash, + coverage=scope["coverage"], excluded_repositories=scope["excluded_repositories"], + original_complete=False) + atomic_json(report_path or root / "closure-report.json", result) + return result + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--archive", type=Path, required=True) + parser.add_argument("--scope", type=Path) + parser.add_argument("--out", type=Path) + args = parser.parse_args() + result = verify(args.archive, args.scope, args.out) + print(json.dumps(result)) + return 0 if result["pass"] else 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/analysis/evaluation.rs b/src/analysis/evaluation.rs new file mode 100644 index 0000000..c0cfaac --- /dev/null +++ b/src/analysis/evaluation.rs @@ -0,0 +1,289 @@ +//! Opt-in experiment boundaries. Normal runs never install a collector. +use serde::Serialize; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex, RwLock}; + +static ACTIVE: RwLock>>> = RwLock::new(None); + +pub fn monotonic_ns() -> Result { + #[cfg(target_os = "linux")] + { + let mut value = libc::timespec { + tv_sec: 0, + tv_nsec: 0, + }; + // CLOCK_MONOTONIC is shared by processes on the same Linux host. + if unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut value) } != 0 { + return Err(std::io::Error::last_os_error().to_string()); + } + return u64::try_from(value.tv_sec) + .ok() + .and_then(|secs| secs.checked_mul(1_000_000_000)) + .and_then(|secs| secs.checked_add(value.tv_nsec as u64)) + .ok_or_else(|| "monotonic clock out of range".to_string()); + } + #[cfg(not(target_os = "linux"))] + Err("evaluation metrics require the Linux CLOCK_MONOTONIC clock".to_string()) +} + +#[derive(Clone, Serialize)] +struct SyncInterval { + protocol: &'static str, + uri: String, + start_ns: u64, + end_ns: u64, + success: bool, +} + +#[derive(Default)] +struct Measurements { + intervals: Vec, + payload_ready_ns: Option, + error: Option, + rrdp_modes: std::collections::BTreeMap, +} + +/// Sum the union, including failed attempts, rather than parallel durations. +fn union_ns(intervals: &[(u64, u64)]) -> Result { + let mut sorted = intervals.to_vec(); + sorted.sort_unstable(); + let mut current: Option<(u64, u64)> = None; + let mut total = 0u64; + for (start, end) in sorted { + if end < start { + return Err("sync interval has reversed clock bounds".to_string()); + } + match current { + Some((left, right)) if start <= right => current = Some((left, right.max(end))), + Some((left, right)) => { + total += right - left; + current = Some((start, end)); + } + None => current = Some((start, end)), + } + } + if let Some((left, right)) = current { + total += right - left; + } + Ok(total) +} + +pub struct EvaluationSession { + data: Arc>, + out: PathBuf, + start_ns: u64, +} + +impl EvaluationSession { + pub fn install(out: &Path) -> Result { + if out.exists() || out.is_symlink() { + return Err("evaluation output must be a new file".to_string()); + } + let mut active = ACTIVE + .write() + .map_err(|_| "evaluation collector lock poisoned")?; + if active.is_some() { + return Err("another evaluation collector is active".to_string()); + } + let data = Arc::new(Mutex::new(Measurements::default())); + let start_ns = monotonic_ns()?; + *active = Some(data.clone()); + Ok(Self { + data, + out: out.to_path_buf(), + start_ns, + }) + } + + /// The complete CCR (including VRP, ASPA and router-key payloads) becomes + /// visible by one same-directory rename. No fsync/disk durability is claimed. + pub fn publish_payload(&self, path: &Path, bytes: &[u8]) -> Result<(), String> { + atomic_write(path, bytes)?; + let ready = monotonic_ns()?; + let mut data = self + .data + .lock() + .map_err(|_| "evaluation collector lock poisoned")?; + if data.payload_ready_ns.replace(ready).is_some() { + return Err("payload was published more than once".to_string()); + } + Ok(()) + } + + pub fn write(&self) -> Result<(), String> { + let data = self + .data + .lock() + .map_err(|_| "evaluation collector lock poisoned")?; + if let Some(error) = &data.error { + return Err(error.clone()); + } + let ready = data + .payload_ready_ns + .ok_or("complete payload publication was not observed")?; + if data.intervals.is_empty() { + return Err("no native repository sync interval was observed".to_string()); + } + if ready < self.start_ns + || data + .intervals + .iter() + .any(|v| v.start_ns < self.start_ns || v.end_ns > ready) + { + return Err("sync/payload clock ordering failed".to_string()); + } + let bounds: Vec<_> = data + .intervals + .iter() + .map(|v| (v.start_ns, v.end_ns)) + .collect(); + let value = serde_json::json!({ + "schema_version": 1, "clock": "Linux CLOCK_MONOTONIC nanoseconds", + "rp_start_ns": self.start_ns, "payload_ready_ns": ready, + "payload_boundary": "complete result.ccr published by same-directory atomic rename; includes encoding; no fsync durability claim", + "sync_boundary": "union of native RRDP/rsync execution including fetch, protocol parse/apply, current-store projection and failed attempts; excludes discovery gaps and frozen T2 hydration", + "sync_wall_union_ns": union_ns(&bounds)?, "sync_intervals": data.intervals, + "rrdp_modes": data.rrdp_modes, + }); + atomic_write( + &self.out, + &serde_json::to_vec_pretty(&value).map_err(|e| e.to_string())?, + ) + } +} + +impl Drop for EvaluationSession { + fn drop(&mut self) { + if let Ok(mut active) = ACTIVE.write() { + if active + .as_ref() + .is_some_and(|value| Arc::ptr_eq(value, &self.data)) + { + *active = None; + } + } + } +} + +pub fn record_rrdp_mode(uri: &str, mode: &'static str) { + if let Ok(active) = ACTIVE.read() { + if let Some(data) = active.as_ref() { + if let Ok(mut data) = data.lock() { + data.rrdp_modes.insert(uri.to_string(), mode); + } + } + } +} + +pub struct SyncSpan { + data: Arc>, + protocol: &'static str, + uri: String, + start_ns: u64, + success: bool, +} + +pub fn sync_span(protocol: &'static str, uri: &str) -> Option { + let data = ACTIVE.read().ok()?.clone()?; + match monotonic_ns() { + Ok(start_ns) => Some(SyncSpan { + data, + protocol, + uri: uri.to_string(), + start_ns, + success: false, + }), + Err(error) => { + if let Ok(mut value) = data.lock() { + value.error = Some(error); + } + None + } + } +} + +impl SyncSpan { + pub fn set_success(&mut self) { + self.success = true; + } +} + +impl Drop for SyncSpan { + fn drop(&mut self) { + if let Ok(mut data) = self.data.lock() { + match monotonic_ns() { + Ok(end_ns) => data.intervals.push(SyncInterval { + protocol: self.protocol, + uri: self.uri.clone(), + start_ns: self.start_ns, + end_ns, + success: self.success, + }), + Err(error) => data.error = Some(error), + } + } + } +} + +fn atomic_write(path: &Path, bytes: &[u8]) -> Result<(), String> { + let parent = path + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .unwrap_or_else(|| Path::new(".")); + std::fs::create_dir_all(parent).map_err(|e| e.to_string())?; + let mut file = tempfile::NamedTempFile::new_in(parent).map_err(|e| e.to_string())?; + file.write_all(bytes) + .and_then(|_| file.flush()) + .map_err(|e| e.to_string())?; + file.persist(path).map_err(|e| e.to_string())?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn overlapping_parallel_intervals_count_once_including_failures() { + assert_eq!( + union_ns(&[(20, 40), (0, 10), (5, 25), (50, 55), (10, 15)]).unwrap(), + 45 + ); + assert_eq!(union_ns(&[]).unwrap(), 0); + assert!(union_ns(&[(4, 3)]).is_err()); + } + #[test] + fn publication_and_failed_span_are_bound_to_same_clock() { + let root = tempfile::tempdir().unwrap(); + let data = Arc::new(Mutex::new(Measurements::default())); + let session = EvaluationSession { + data: data.clone(), + out: root.path().join("metrics.json"), + start_ns: monotonic_ns().unwrap(), + }; + { + let _failed = SyncSpan { + data, + protocol: "rrdp", + uri: "https://example.test/notification.xml".to_string(), + start_ns: monotonic_ns().unwrap(), + success: false, + }; + } + session + .publish_payload(&root.path().join("result.ccr"), b"complete payload") + .unwrap(); + session.write().unwrap(); + let value: serde_json::Value = + serde_json::from_slice(&std::fs::read(root.path().join("metrics.json")).unwrap()) + .unwrap(); + assert_eq!(value["sync_intervals"][0]["success"], false); + assert!( + value["payload_ready_ns"].as_u64().unwrap() >= value["rp_start_ns"].as_u64().unwrap() + ); + assert_eq!( + std::fs::read(root.path().join("result.ccr")).unwrap(), + b"complete payload" + ); + } +} diff --git a/src/analysis/mod.rs b/src/analysis/mod.rs index fca4906..93fecff 100644 --- a/src/analysis/mod.rs +++ b/src/analysis/mod.rs @@ -1 +1,2 @@ +pub mod evaluation; pub mod timing; diff --git a/src/bin/db_stats.rs b/src/bin/db_stats.rs index 4be7ef8..03041d7 100644 --- a/src/bin/db_stats.rs +++ b/src/bin/db_stats.rs @@ -4,9 +4,10 @@ use std::path::{Path, PathBuf}; use rocksdb::{DB, IteratorMode, Options}; use rpki::storage::{ - ALL_COLUMN_FAMILY_NAMES, CF_MANIFEST_REPLAY_META, CF_RAW_BY_HASH, CF_REPOSITORY_VIEW, + ALL_COLUMN_FAMILY_NAMES, CF_CHILD_CERTIFICATE_CACHE_PROJECTION, CF_MANIFEST_REPLAY_META, + CF_PUBLICATION_POINT_CACHE_PROJECTION, CF_RAW_BY_HASH, CF_REPOSITORY_VIEW, CF_ROA_CACHE_PROJECTION, CF_RRDP_SOURCE, CF_RRDP_SOURCE_MEMBER, CF_RRDP_URI_OWNER, - CF_TRANSPORT_PREFETCH, CF_VCIR, column_family_descriptors, + CF_TRANSPORT_PREFETCH, CF_VCIR, CF_VCIR_FAILED_FETCH_REUSE_IDENTITY, column_family_descriptors, }; #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -99,7 +100,7 @@ Output: Output groups: - current_repository_view: repository_view + raw_by_hash - - current_validation_state: vcir + manifest_replay_meta + roa_cache_projection + transport_prefetch + - current_validation_state: vcir + manifest_replay_meta + failed-fetch identity + ROA/child-certificate/PP projections + transport_prefetch - current_rrdp_state: rrdp_source + rrdp_source_member + rrdp_uri_owner " ) @@ -183,9 +184,13 @@ fn collect_db_file_stats(db_path: &Path) -> Result CfGroup { match cf_name { CF_REPOSITORY_VIEW | CF_RAW_BY_HASH => CfGroup::CurrentRepositoryView, - CF_VCIR | CF_MANIFEST_REPLAY_META | CF_ROA_CACHE_PROJECTION | CF_TRANSPORT_PREFETCH => { - CfGroup::CurrentValidationState - } + CF_VCIR + | CF_MANIFEST_REPLAY_META + | CF_VCIR_FAILED_FETCH_REUSE_IDENTITY + | CF_ROA_CACHE_PROJECTION + | CF_CHILD_CERTIFICATE_CACHE_PROJECTION + | CF_PUBLICATION_POINT_CACHE_PROJECTION + | CF_TRANSPORT_PREFETCH => CfGroup::CurrentValidationState, CF_RRDP_SOURCE | CF_RRDP_SOURCE_MEMBER | CF_RRDP_URI_OWNER => CfGroup::CurrentRrdpState, _ => CfGroup::LegacyCompatibility, } @@ -262,7 +267,8 @@ fn main() -> Result<(), Box> { opts.create_if_missing(false); opts.create_missing_column_families(false); - let db = DB::open_cf_descriptors(&opts, &db_path, column_family_descriptors())?; + let db = + DB::open_cf_descriptors_read_only(&opts, &db_path, column_family_descriptors(), false)?; println!("db={}", db_path.display()); println!("mode={}", mode_label(mode)); @@ -386,6 +392,13 @@ mod tests { CfGroup::CurrentValidationState ); assert_eq!(cf_group(CF_RRDP_SOURCE), CfGroup::CurrentRrdpState); + for name in [ + CF_VCIR_FAILED_FETCH_REUSE_IDENTITY, + CF_CHILD_CERTIFICATE_CACHE_PROJECTION, + CF_PUBLICATION_POINT_CACHE_PROJECTION, + ] { + assert_eq!(cf_group(name), CfGroup::CurrentValidationState); + } assert_eq!(cf_group(CF_RRDP_URI_OWNER), CfGroup::CurrentRrdpState); assert_eq!(cf_group("unknown_legacy"), CfGroup::LegacyCompatibility); } diff --git a/src/cli.rs b/src/cli.rs index a30084b..7aa1713 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -175,6 +175,8 @@ pub struct CliArgs { pub http_timeout_secs: u64, pub http_root_cert_paths: Vec, + pub record_transport_dir: Option, + pub evaluation_metrics_out: Option, pub rsync_timeout_secs: u64, pub rsync_mirror_root: Option, pub rsync_scope_policy: RsyncScopePolicy, @@ -196,6 +198,7 @@ Usage: {bin} --db --tal-url [--tal-url ...] [options] {bin} --db --tal-path --ta-path [--tal-path --ta-path ...] [options] {bin} --verification-only --verification-source-run --verification-source-state --verification-out [options] + {bin} --validation-benchmark --source-run --source-state --pre-state --out Options: --verification-only Revalidate the latest successful run without validation caches or network access @@ -238,6 +241,7 @@ Options: --enable-transport-request-prefetch Experimental: prefetch previous run transport repo requests before tree traversal --ccr-out Write CCR DER ContentInfo to this path (optional) + --evaluation-metrics-out Experimental native sync intervals and atomic CCR publication clock (Linux) --vrps-csv-out Write VRP compare-view CSV directly from validation output (optional; requires --vaps-csv-out) --vaps-csv-out Write VAP compare-view CSV directly from validation output (optional; requires --vrps-csv-out) --compare-view-trust-anchor @@ -295,6 +299,8 @@ Options: --disable-rrdp Disable RRDP and synchronize only via rsync --rsync-command Use this rsync command instead of the default rsync binary --http-timeout-secs HTTP fetch timeout seconds (default: 20) + --record-transport-dir + Archive raw HTTP/RRDP and rsync inputs for experiments (default: off) --http-root-cert Extra PEM root certificate trusted by HTTPS fetches (repeatable) --rsync-timeout-secs rsync I/O timeout seconds (default: 60) --rsync-mirror-root Persist rsync mirrors under this directory (default: disabled) @@ -368,6 +374,8 @@ pub fn parse_args(argv: &[String]) -> Result { let mut rsync_command: Option = None; let mut http_timeout_secs: u64 = 30; let mut http_root_cert_paths: Vec = Vec::new(); + let mut record_transport_dir: Option = None; + let mut evaluation_metrics_out: Option = None; let mut rsync_timeout_secs: u64 = 30; let mut rsync_mirror_root: Option = None; let mut rsync_scope_policy = RsyncScopePolicy::default(); @@ -564,10 +572,10 @@ pub fn parse_args(argv: &[String]) -> Result { let v = argv .get(i) .ok_or("--dead-repo-blacklist-fail-threshold requires a value")?; - dead_repo_blacklist_fail_threshold = Some( - v.parse::() - .map_err(|_| format!("invalid --dead-repo-blacklist-fail-threshold: {v}"))?, - ); + dead_repo_blacklist_fail_threshold = + Some(v.parse::().map_err(|_| { + format!("invalid --dead-repo-blacklist-fail-threshold: {v}") + })?); } "--db" => { i += 1; @@ -764,6 +772,25 @@ pub fn parse_args(argv: &[String]) -> Result { .parse::() .map_err(|_| format!("invalid --http-timeout-secs: {v}"))?; } + "--evaluation-metrics-out" => { + i += 1; + let value = argv + .get(i) + .ok_or("--evaluation-metrics-out requires a value")?; + if evaluation_metrics_out + .replace(PathBuf::from(value)) + .is_some() + { + return Err("duplicate --evaluation-metrics-out".to_string()); + } + } + "--record-transport-dir" => { + i += 1; + let v = argv + .get(i) + .ok_or("--record-transport-dir requires a value")?; + record_transport_dir = Some(PathBuf::from(v)); + } "--http-root-cert" => { i += 1; let v = argv.get(i).ok_or("--http-root-cert requires a value")?; @@ -881,6 +908,8 @@ pub fn parse_args(argv: &[String]) -> Result { || rsync_local_dir.is_some() || rsync_command.is_some() || !http_root_cert_paths.is_empty() + || record_transport_dir.is_some() + || evaluation_metrics_out.is_some() || payload_replay_archive.is_some() || payload_replay_locks.is_some() || payload_base_archive.is_some() @@ -1169,7 +1198,7 @@ pub fn parse_args(argv: &[String]) -> Result { if dead_repo_blacklist_fail_threshold.is_some() && dead_repo_blacklist_path.is_none() { return Err( - "--dead-repo-blacklist-fail-threshold requires --dead-repo-blacklist".to_string() + "--dead-repo-blacklist-fail-threshold requires --dead-repo-blacklist".to_string(), ); } if let Some(path) = dead_repo_blacklist_path { @@ -1177,13 +1206,14 @@ pub fn parse_args(argv: &[String]) -> Result { if fail_threshold == 0 { return Err("--dead-repo-blacklist-fail-threshold must be >= 1".to_string()); } - parallel_phase1_cfg.dead_repo_blacklist = - Some(crate::parallel::dead_repo_blacklist::DeadRepoBlacklistConfig { + parallel_phase1_cfg.dead_repo_blacklist = Some( + crate::parallel::dead_repo_blacklist::DeadRepoBlacklistConfig { path, fail_threshold, capacity: crate::parallel::dead_repo_blacklist::DEAD_REPO_BLACKLIST_DEFAULT_CAPACITY, - }); + }, + ); } Ok(CliArgs { @@ -1242,6 +1272,8 @@ pub fn parse_args(argv: &[String]) -> Result { rsync_command, http_timeout_secs, http_root_cert_paths, + record_transport_dir, + evaluation_metrics_out, rsync_timeout_secs, rsync_mirror_root, rsync_scope_policy, @@ -1981,6 +2013,7 @@ fn run_ccr_task( shared: &PostValidationShared, ccr_out_path: Option<&Path>, produced_at: time::OffsetDateTime, + evaluation: Option<&crate::analysis::evaluation::EvaluationSession>, ) -> Result { let mut ccr_build_ms = None; let mut ccr_build_breakdown = None; @@ -2015,7 +2048,14 @@ fn run_ccr_task( ccr_build_ms = Some(started.elapsed().as_millis() as u64); ccr_build_breakdown = build_breakdown; let started = std::time::Instant::now(); - write_ccr_file(path, &ccr).map_err(|e| e.to_string())?; + if let Some(session) = evaluation { + let bytes = + crate::ccr::encode_content_info(&crate::ccr::CcrContentInfo::new(ccr.clone())) + .map_err(|e| e.to_string())?; + session.publish_payload(path, &bytes)?; + } else { + write_ccr_file(path, &ccr).map_err(|e| e.to_string())?; + } ccr_write_ms = Some(started.elapsed().as_millis() as u64); eprintln!("wrote CCR: {}", path.display()); } @@ -2285,7 +2325,37 @@ fn transport_prefetch_for_verification_contract( } pub fn run(argv: &[String]) -> Result<(), String> { + if argv.get(1).map(String::as_str) == Some("--validation-benchmark") { + return crate::replay::validation_benchmark::run(argv); + } + run_internal(argv, None) +} + +pub(crate) fn run_validation_benchmark( + argv: &[String], + prepared: &mut crate::replay::validation_benchmark::PreparedBenchmark, +) -> Result<(), String> { + run_internal(argv, Some(prepared)) +} + +fn run_internal( + argv: &[String], + mut benchmark: Option<&mut crate::replay::validation_benchmark::PreparedBenchmark>, +) -> Result<(), String> { let mut args = parse_args(argv)?; + if args.evaluation_metrics_out.is_some() + && (benchmark.is_some() + || args.ccr_out_path.is_none() + || args.payload_replay_archive.is_some() + || args.payload_base_archive.is_some()) + { + return Err("evaluation metrics require a native run with --ccr-out".to_string()); + } + let evaluation = args + .evaluation_metrics_out + .as_deref() + .map(crate::analysis::evaluation::EvaluationSession::install) + .transpose()?; let mut prepared_verification = if args.verification_only { let prepared = crate::verification_only::prepare_verification( args.verification_source_run_dir @@ -2357,6 +2427,12 @@ pub fn run(argv: &[String]) -> Result<(), String> { let validation_time = time::OffsetDateTime::from_unix_timestamp(validation_time.unix_timestamp()) .map_err(|error| format!("normalize validation time failed: {error}"))?; + if let Some(prepared) = benchmark.as_deref() { + prepared.validate_effective(&args, &policy, validation_time)?; + // Unlike verification-only output replay, T2 must perform the same + // fresh checks as T1 before naturally falling back to pre-step VCIR. + // Forcing the selected VCIR would skip failed Manifest validation. + } let http_root_certificates_pem = args .http_root_cert_paths .iter() @@ -2366,7 +2442,12 @@ pub fn run(argv: &[String]) -> Result<(), String> { }) .collect::, _>>()?; - let store = if let Some(prepared) = prepared_verification.as_mut() { + let store = if let Some(prepared) = benchmark.as_deref_mut() { + prepared + .store + .take() + .expect("benchmark scratch store must be available") + } else if let Some(prepared) = prepared_verification.as_mut() { prepared .store .take() @@ -2473,6 +2554,10 @@ pub fn run(argv: &[String]) -> Result<(), String> { store.as_ref(), ); let validation_started = std::time::Instant::now(); + let benchmark_clock = benchmark + .as_deref() + .map(|prepared| prepared.clock()) + .transpose()?; let crypto_sig_cache = if args.crypto_signature_cache_observe_only || args.enable_crypto_signature_cache { let cache_file = crate::crypto_sig_cache::default_cache_file_path(&args.db_path); @@ -2486,7 +2571,25 @@ pub fn run(argv: &[String]) -> Result<(), String> { None }; let collect_current_repo_objects = false; - let out = if args.verification_only { + let out = if let Some(prepared) = benchmark.as_deref() { + let http = + crate::replay::validation_benchmark::FrozenHttpFetcher(Arc::clone(&prepared.table)); + let rsync = crate::replay::validation_benchmark::FrozenRsyncFetcher { + table: Arc::clone(&prepared.table), + scope: args.rsync_scope_policy, + }; + run_online_validation_with_fetchers( + Arc::clone(&store), + &policy, + &args, + &http, + &rsync, + validation_time, + &config, + collect_current_repo_objects, + timing.as_ref().map(|(_, handle)| handle), + )? + } else if args.verification_only { let http = crate::verification_only::NetworkDisabledHttpFetcher; let rsync = crate::fetch::current_repository::CurrentRepositoryViewRsyncFetcher::new( Arc::clone(&store), @@ -2620,6 +2723,7 @@ pub fn run(argv: &[String]) -> Result<(), String> { let http = BlockingHttpFetcher::new(HttpFetcherConfig { timeout: std::time::Duration::from_secs(args.http_timeout_secs.max(1)), extra_root_certificates_pem: http_root_certificates_pem.clone(), + recording_root: args.record_transport_dir.clone(), ..HttpFetcherConfig::default() }) .map_err(|e| e.to_string())?; @@ -2639,6 +2743,7 @@ pub fn run(argv: &[String]) -> Result<(), String> { let http = BlockingHttpFetcher::new(HttpFetcherConfig { timeout: std::time::Duration::from_secs(args.http_timeout_secs.max(1)), extra_root_certificates_pem: http_root_certificates_pem.clone(), + recording_root: args.record_transport_dir.clone(), ..HttpFetcherConfig::default() }) .map_err(|e| e.to_string())?; @@ -2649,6 +2754,7 @@ pub fn run(argv: &[String]) -> Result<(), String> { .unwrap_or_else(|| PathBuf::from("rsync")), timeout: std::time::Duration::from_secs(args.rsync_timeout_secs.max(1)), mirror_root: args.rsync_mirror_root.clone(), + recording_root: args.record_transport_dir.clone(), scope_policy: args.rsync_scope_policy, ..SystemRsyncConfig::default() }); @@ -2665,6 +2771,25 @@ pub fn run(argv: &[String]) -> Result<(), String> { )? }; + let early_benchmark_pp_refresh = + if benchmark.is_some() && args.enable_publication_point_validation_cache { + store + .refresh_publication_point_cache_mmap_index() + .map_err(|error| format!("benchmark PP cache persist failed: {error}"))? + } else { + None + }; + if benchmark.is_some() { + if let Some(cache) = crypto_sig_cache.as_ref() { + cache.persist()?; + } + } + if let (Some(prepared), Some(clock)) = (benchmark.as_deref(), benchmark_clock) { + store + .drain_validation_benchmark_io() + .map_err(|error| error.to_string())?; + prepared.write_measurement(clock)?; + } let validation_ms = validation_started.elapsed().as_millis() as u64; let mut shared = PostValidationShared::from_run_output(out); let vcir_storage_summary_enabled = vcir_storage_summary_enabled(); @@ -2804,6 +2929,7 @@ pub fn run(argv: &[String]) -> Result<(), String> { shared, args.ccr_out_path.as_deref(), ccr_produced_at, + evaluation.as_ref(), ) }); let compare_view_handle = scope.spawn(|| { @@ -2912,7 +3038,9 @@ pub fn run(argv: &[String]) -> Result<(), String> { cir_total_ms = Some(summary.timing.total_ms); eprintln!( "wrote CIR: {} (objects={}, trust_anchors={}, build_cir_ms={}, write_cir_ms={}, total_ms={})", - cir_out_path.expect("cir path present when cir enabled").display(), + cir_out_path + .expect("cir path present when cir enabled") + .display(), summary.object_count, summary.trust_anchor_count, summary.timing.build_cir_ms, @@ -2932,7 +3060,9 @@ pub fn run(argv: &[String]) -> Result<(), String> { &total_started, store.as_ref(), ); - let publication_point_cache_index_refresh = if args.enable_publication_point_validation_cache + let publication_point_cache_index_refresh = if benchmark.is_some() { + early_benchmark_pp_refresh + } else if args.enable_publication_point_validation_cache || args.publication_point_cache_observe_only { match store.refresh_publication_point_cache_mmap_index() { @@ -2953,7 +3083,11 @@ pub fn run(argv: &[String]) -> Result<(), String> { }; let publication_point_cache_index_load = store.publication_point_cache_mmap_index_load_stats(); let crypto_signature_cache_observe = crypto_sig_cache.as_ref().map(|cache| { - if let Err(e) = cache.persist() { + if let Err(e) = if benchmark.is_some() { + Ok(()) + } else { + cache.persist() + } { crate::progress_log::emit( "crypto_signature_cache_persist", serde_json::json!({ @@ -3136,6 +3270,9 @@ pub fn run(argv: &[String]) -> Result<(), String> { eprintln!("analysis: wrote {}", pb_path.display()); } + if let Some(session) = evaluation.as_ref() { + session.write()?; + } print_summary_from_shared(validation_time, &shared); if let Some(prepared) = prepared_verification.as_ref() { std::fs::create_dir_all(&prepared.artifacts.compare_dir).map_err(|error| { diff --git a/src/cli/tests.rs b/src/cli/tests.rs index 0ae1ea7..66a399f 100644 --- a/src/cli/tests.rs +++ b/src/cli/tests.rs @@ -38,6 +38,46 @@ fn parse_help_returns_usage() { assert!(!err.contains("--parallel-phase2 "), "{err}"); } +#[test] +fn parse_transport_recording_is_opt_in_and_not_verification_only() { + let mut argv: Vec = [ + "rpki", + "--db", + "db", + "--tal-url", + "https://example.test/root.tal", + ] + .into_iter() + .map(String::from) + .collect(); + assert!(parse_args(&argv).unwrap().record_transport_dir.is_none()); + argv.extend(["--record-transport-dir".into(), "archive".into()]); + assert_eq!( + parse_args(&argv).unwrap().record_transport_dir, + Some(PathBuf::from("archive")) + ); + let argv: Vec = [ + "rpki", + "--verification-only", + "--verification-source-run", + "/run/run_0002", + "--verification-source-state", + "/run/state", + "--verification-out", + "/verification/check_0002", + "--record-transport-dir", + "/archive", + ] + .into_iter() + .map(String::from) + .collect(); + assert!( + parse_args(&argv) + .unwrap_err() + .contains("conflicting normal-run options") + ); +} + #[test] fn parse_accepts_explicit_ta_constraints_for_known_tal() { let dir = tempfile::tempdir().expect("tmpdir"); @@ -2235,6 +2275,7 @@ fn run_ccr_task_uses_accumulator_when_phase2_output_contains_reuse_sources() { &shared, Some(&ccr_path), time::OffsetDateTime::now_utc(), + None, ) .expect("run ccr task"); @@ -2322,3 +2363,49 @@ fn build_repo_sync_stats_aggregates_phase_and_terminal_state() { 50 ); } + +#[test] +fn evaluation_metrics_require_explicit_path_and_reject_verification_mode() { + let command = [ + "rpki", + "--db", + "state", + "--tal-path", + "root.tal", + "--ta-path", + "root.cer", + "--ccr-out", + "result.ccr", + "--evaluation-metrics-out", + "metrics.json", + ] + .map(str::to_string); + assert_eq!( + parse_args(&command).unwrap().evaluation_metrics_out, + Some(PathBuf::from("metrics.json")) + ); + let mut duplicate = command.to_vec(); + duplicate.extend([ + "--evaluation-metrics-out".to_string(), + "other.json".to_string(), + ]); + assert!(parse_args(&duplicate).unwrap_err().contains("duplicate")); + let verification = [ + "rpki", + "--verification-only", + "--verification-source-run", + "source", + "--verification-source-state", + "state", + "--verification-out", + "out", + "--evaluation-metrics-out", + "metrics.json", + ] + .map(str::to_string); + assert!( + parse_args(&verification) + .unwrap_err() + .contains("conflicting") + ); +} diff --git a/src/fetch/http.rs b/src/fetch/http.rs index 117cb25..ebc9e8d 100644 --- a/src/fetch/http.rs +++ b/src/fetch/http.rs @@ -56,6 +56,8 @@ pub struct HttpFetcherConfig { pub user_agent: String, /// Extra PEM trust anchors for HTTPS transport tests or private RRDP endpoints. pub extra_root_certificates_pem: Vec>, + /// Explicit raw transport recording; disabled for normal runs. + pub recording_root: Option, } impl Default for HttpFetcherConfig { @@ -66,6 +68,7 @@ impl Default for HttpFetcherConfig { large_body_timeout: Duration::from_secs(180), user_agent: resolve_http_user_agent(std::env::var(HTTP_USER_AGENT_ENV).ok()), extra_root_certificates_pem: Vec::new(), + recording_root: None, } } } @@ -77,6 +80,7 @@ impl Default for HttpFetcherConfig { /// - fetching RRDP notification/snapshot files (RFC 8182 §3.4) #[derive(Clone, Debug)] pub struct BlockingHttpFetcher { + archive: Option, short_client: Client, large_body_client: Client, retry_short_client: Client, @@ -89,6 +93,11 @@ pub struct BlockingHttpFetcher { impl BlockingHttpFetcher { pub fn new(config: HttpFetcherConfig) -> Result { + let archive = config + .recording_root + .as_deref() + .map(crate::recording::TransportArchive::open) + .transpose()?; let short_timeout = config.timeout; let large_body_timeout = std::cmp::max(config.large_body_timeout, config.timeout); let connect_timeout = std::cmp::min(config.connect_timeout, config.timeout); @@ -141,6 +150,7 @@ impl BlockingHttpFetcher { .build() .map_err(|e| e.to_string())?; Ok(Self { + archive, short_client, large_body_client, retry_short_client, @@ -176,11 +186,17 @@ impl BlockingHttpFetcher { timeout: Duration, user_agent: String, ) -> Result { - Ok(Self::client_builder(config, connect_timeout, timeout, user_agent)? - .redirect(reqwest::redirect::Policy::none())) + Ok( + Self::client_builder(config, connect_timeout, timeout, user_agent)? + .redirect(reqwest::redirect::Policy::none()), + ) } pub fn fetch_bytes(&self, uri: &str) -> Result, String> { + let mut capture = self + .archive + .as_ref() + .map(|a| a.begin("http", "object", uri)); let started = std::time::Instant::now(); let (client, timeout_profile, timeout_value) = self.client_for_uri(uri); let resp = client.get(uri).send().map_err(|e| { @@ -201,6 +217,9 @@ impl BlockingHttpFetcher { let status = resp.status(); let headers = resp.headers().clone(); + if let Some(record) = capture.as_mut() { + record.response(&resp); + } if !status.is_success() { let body_preview = resp .text() @@ -239,6 +258,10 @@ impl BlockingHttpFetcher { match resp.bytes() { Ok(bytes) => { + if let Some(record) = capture.as_mut() { + record.body(&bytes)?; + record.finish()?; + } let duration_ms = started.elapsed().as_millis() as u64; if (duration_ms as f64) / 1000.0 >= crate::progress_log::slow_threshold_secs() { crate::progress_log::emit( @@ -411,15 +434,9 @@ impl BlockingHttpFetcher { uri: &str, notification_origin: &RrdpOrigin, ) -> Result, RrdpFetchError> { - let (response, _profile, _timeout) = self.rrdp_response(resource, uri, notification_origin)?; - let status = response.status(); - if !status.is_success() { - return Err(RrdpFetchError::Fetch(format!("http status {status}"))); - } - response - .bytes() - .map(|b| b.to_vec()) - .map_err(|e| RrdpFetchError::Fetch(format!("http read body failed: {e}"))) + let mut bytes = Vec::new(); + self.rrdp_fetch_to_writer(resource, uri, notification_origin, &mut bytes)?; + Ok(bytes) } fn rrdp_fetch_to_writer( @@ -429,14 +446,30 @@ impl BlockingHttpFetcher { notification_origin: &RrdpOrigin, out: &mut dyn Write, ) -> Result { - let (mut response, _profile, _timeout) = self.rrdp_response(resource, uri, notification_origin)?; + let mut capture = self + .archive + .as_ref() + .map(|a| a.begin("http", &resource.to_string(), uri)); + let (mut response, _profile, _timeout) = + self.rrdp_response(resource, uri, notification_origin)?; + if let Some(record) = capture.as_mut() { + record.response(&response); + } let status = response.status(); if !status.is_success() { return Err(RrdpFetchError::Fetch(format!("http status {status}"))); } - response - .copy_to(out) - .map_err(|e| RrdpFetchError::Fetch(format!("http stream body failed: {e}"))) + if let Some(record) = capture.as_mut() { + let size = record + .copy(&mut response, out) + .map_err(RrdpFetchError::Fetch)?; + record.finish().map_err(RrdpFetchError::Fetch)?; + Ok(size) + } else { + response + .copy_to(out) + .map_err(|e| RrdpFetchError::Fetch(format!("http stream body failed: {e}"))) + } } } @@ -446,6 +479,10 @@ impl Fetcher for BlockingHttpFetcher { } fn fetch_to_writer(&self, uri: &str, out: &mut dyn Write) -> Result { + let mut capture = self + .archive + .as_ref() + .map(|a| a.begin("http", "object", uri)); let started = std::time::Instant::now(); let (client, timeout_profile, timeout_value) = self.client_for_uri(uri); let resp = client.get(uri).send().map_err(|e| { @@ -466,6 +503,9 @@ impl Fetcher for BlockingHttpFetcher { let status = resp.status(); let headers = resp.headers().clone(); + if let Some(record) = capture.as_mut() { + record.response(&resp); + } if !status.is_success() { let body_preview = resp .text() @@ -503,7 +543,15 @@ impl Fetcher for BlockingHttpFetcher { } let mut resp = resp; - match resp.copy_to(out) { + let result = if let Some(record) = capture.as_mut() { + record.copy(&mut resp, out).and_then(|size| { + record.finish()?; + Ok(size) + }) + } else { + resp.copy_to(out).map_err(|e| e.to_string()) + }; + match result { Ok(bytes) => { let duration_ms = started.elapsed().as_millis() as u64; if (duration_ms as f64) / 1000.0 >= crate::progress_log::slow_threshold_secs() { @@ -629,6 +677,46 @@ mod tests { assert_eq!(got, b"hello"); } + #[test] + fn transport_recording_covers_http_bytes_stream_and_failure() { + let root = tempfile::tempdir().unwrap(); + let http = BlockingHttpFetcher::new(HttpFetcherConfig { + timeout: Duration::from_secs(2), + recording_root: Some(root.path().into()), + ..HttpFetcherConfig::default() + }) + .unwrap(); + let uri = spawn_one_shot_http_server("HTTP/1.1 200 OK", b"signed raw bytes"); + assert_eq!(http.fetch_bytes(&uri).unwrap(), b"signed raw bytes"); + let uri = spawn_one_shot_http_server("HTTP/1.1 200 OK", b"streamed raw XML"); + let mut output = Vec::new(); + http.fetch_to_writer(&uri, &mut output).unwrap(); + assert_eq!(output, b"streamed raw XML"); + let uri = spawn_one_shot_http_server("HTTP/1.1 503 Unavailable", b"failure"); + assert!(http.fetch_bytes(&uri).is_err()); + let events: Vec = std::fs::read_dir(root.path().join("events")) + .unwrap() + .map(|entry| { + serde_json::from_slice(&std::fs::read(entry.unwrap().path()).unwrap()).unwrap() + }) + .collect(); + assert_eq!(events.len(), 3); + assert_eq!(events.iter().filter(|e| e["complete"] == true).count(), 2); + assert!( + events + .iter() + .any(|e| e["status"] == 503 && e["complete"] == false) + ); + for event in events.iter().filter(|e| e["complete"] == true) { + let hash = event["body"]["sha256"].as_str().unwrap(); + let archive = crate::recording::TransportArchive::open(root.path()).unwrap(); + assert!(archive.blob_path(hash).is_file()); + assert!( + event["completed_ms"].as_u64().unwrap() >= event["started_ms"].as_u64().unwrap() + ); + } + } + #[test] fn fetch_bytes_rejects_non_success_status() { let url = spawn_one_shot_http_server("HTTP/1.1 404 Not Found", b""); diff --git a/src/fetch/rsync.rs b/src/fetch/rsync.rs index a18ec2d..49d30db 100644 --- a/src/fetch/rsync.rs +++ b/src/fetch/rsync.rs @@ -21,6 +21,12 @@ pub fn normalize_rsync_base_uri(s: &str) -> String { /// v1: this is intentionally abstract so unit tests can use a mock, and later we can /// back it by calling the system `rsync` binary (RFC 6481 §5; RFC 8182 §3.4.5). pub trait RsyncFetcher: Send + Sync { + /// Explicit frozen-input experiment only; ordinary fetchers return None. + /// A returned outcome means the input view is already materialized. + fn frozen_sync_outcome(&self, _rsync_base_uri: &str) -> Option> { + None + } + /// Return a list of objects as `(rsync_uri, bytes)` pairs. fn fetch_objects(&self, rsync_base_uri: &str) -> RsyncFetchResult)>>; diff --git a/src/fetch/rsync_system.rs b/src/fetch/rsync_system.rs index 98a3766..e738fd2 100644 --- a/src/fetch/rsync_system.rs +++ b/src/fetch/rsync_system.rs @@ -55,6 +55,7 @@ pub struct SystemRsyncConfig { /// Note: actual mirror behavior is implemented separately from config wiring. pub mirror_root: Option, pub scope_policy: RsyncScopePolicy, + pub recording_root: Option, } impl Default for SystemRsyncConfig { @@ -66,6 +67,7 @@ impl Default for SystemRsyncConfig { extra_args: Vec::new(), mirror_root: None, scope_policy: RsyncScopePolicy::default(), + recording_root: None, } } } @@ -117,6 +119,20 @@ impl SystemRsyncFetcher { Self { config } } + fn capture( + &self, + kind: &str, + uri: &str, + ) -> Result, String> { + self.config + .recording_root + .as_deref() + .map(|root| { + Ok(crate::recording::TransportArchive::open(root)?.begin("rsync", kind, uri)) + }) + .transpose() + } + fn mirror_dst_dir(&self, normalized_rsync_base_uri: &str) -> Result, String> { let Some(root) = self.config.mirror_root.as_ref() else { return Ok(None); @@ -328,16 +344,26 @@ impl RsyncFetcher for SystemRsyncFetcher { "rsync URI must reference a file object: {rsync_uri}" )) })?; + let mut capture = self + .capture("object", rsync_uri) + .map_err(RsyncFetchError::Fetch)?; let tmp = TempDir::new().map_err(RsyncFetchError::Fetch)?; self.run_rsync(rsync_uri, tmp.path()) .map_err(RsyncFetchError::Fetch)?; let object_path = tmp.path().join(file_name); - std::fs::read(&object_path).map_err(|e| { + let bytes = std::fs::read(&object_path).map_err(|e| { RsyncFetchError::Fetch(format!( "read fetched rsync object failed: {}: {e}", object_path.display() )) - }) + })?; + if let Some(record) = capture.as_mut() { + record + .object(rsync_uri, &bytes) + .map_err(RsyncFetchError::Fetch)?; + record.finish().map_err(RsyncFetchError::Fetch)?; + } + Ok(bytes) } fn visit_objects( @@ -346,11 +372,17 @@ impl RsyncFetcher for SystemRsyncFetcher { visitor: &mut dyn FnMut(String, Vec) -> Result<(), String>, ) -> RsyncFetchResult<(usize, u64)> { let base = self.scope_fetch_uri(rsync_base_uri); + let mut capture = self + .capture("view", &base) + .map_err(RsyncFetchError::Fetch)?; let mut count = 0usize; let mut bytes_total = 0u64; let mut wrapped = |uri: String, bytes: Vec| -> Result<(), String> { bytes_total += bytes.len() as u64; count += 1; + if let Some(record) = capture.as_mut() { + record.object(&uri, &bytes)?; + } visitor(uri, bytes) }; @@ -361,6 +393,9 @@ impl RsyncFetcher for SystemRsyncFetcher { self.run_rsync(&base, &dst) .map_err(RsyncFetchError::Fetch)?; walk_dir_visit(&dst, &dst, &base, &mut wrapped).map_err(RsyncFetchError::Fetch)?; + if let Some(record) = capture.as_mut() { + record.finish().map_err(RsyncFetchError::Fetch)?; + } return Ok((count, bytes_total)); } @@ -369,6 +404,9 @@ impl RsyncFetcher for SystemRsyncFetcher { .map_err(RsyncFetchError::Fetch)?; walk_dir_visit(tmp.path(), tmp.path(), &base, &mut wrapped) .map_err(RsyncFetchError::Fetch)?; + if let Some(record) = capture.as_mut() { + record.finish().map_err(RsyncFetchError::Fetch)?; + } Ok((count, bytes_total)) } @@ -627,6 +665,7 @@ mod tests { fn system_rsync_host_scope_does_not_widen_success_fetch_scope() { let fetcher = SystemRsyncFetcher::new(SystemRsyncConfig { scope_policy: RsyncScopePolicy::Host, + recording_root: None, ..SystemRsyncConfig::default() }); assert_eq!( @@ -647,6 +686,7 @@ mod tests { fn system_rsync_dedup_key_uses_publication_point_scope_when_configured() { let fetcher = SystemRsyncFetcher::new(SystemRsyncConfig { scope_policy: RsyncScopePolicy::PublicationPoint, + recording_root: None, ..SystemRsyncConfig::default() }); assert_eq!( @@ -659,6 +699,7 @@ mod tests { fn system_rsync_dedup_key_uses_module_root_when_configured() { let fetcher = SystemRsyncFetcher::new(SystemRsyncConfig { scope_policy: RsyncScopePolicy::ModuleRoot, + recording_root: None, ..SystemRsyncConfig::default() }); assert_eq!( @@ -679,6 +720,7 @@ mod tests { extra_args: Vec::new(), mirror_root: None, scope_policy: RsyncScopePolicy::default(), + recording_root: None, }); let e = f .run_rsync("rsync://example.net/repo/", dst.path()) @@ -693,6 +735,7 @@ mod tests { extra_args: Vec::new(), mirror_root: None, scope_policy: RsyncScopePolicy::default(), + recording_root: None, }); let e = f .run_rsync("rsync://example.net/repo/", dst.path()) @@ -714,6 +757,7 @@ mod tests { extra_args: Vec::new(), mirror_root: Some(root_file.clone()), scope_policy: RsyncScopePolicy::default(), + recording_root: None, }); let err = fetcher @@ -742,6 +786,7 @@ mod tests { extra_args: Vec::new(), mirror_root: Some(root.clone()), scope_policy: RsyncScopePolicy::default(), + recording_root: None, }); let err = fetcher @@ -803,6 +848,7 @@ mod tests { extra_args: Vec::new(), mirror_root: None, scope_policy: RsyncScopePolicy::default(), + recording_root: None, }); fetcher @@ -842,6 +888,7 @@ mod tests { extra_args: Vec::new(), mirror_root: None, scope_policy: RsyncScopePolicy::default(), + recording_root: None, }); let err = fetcher @@ -886,6 +933,7 @@ mod tests { extra_args: Vec::new(), mirror_root: None, scope_policy: RsyncScopePolicy::default(), + recording_root: None, }); let err = fetcher @@ -932,6 +980,7 @@ mod tests { extra_args: Vec::new(), mirror_root: None, scope_policy: RsyncScopePolicy::default(), + recording_root: None, }); fetcher diff --git a/src/lib.rs b/src/lib.rs index f5d56c3..e4f8043 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -32,6 +32,8 @@ pub mod query; #[cfg(feature = "full")] pub mod query_db; #[cfg(feature = "full")] +pub mod recording; +#[cfg(feature = "full")] pub mod replay; #[cfg(feature = "full")] pub mod report; diff --git a/src/recording/mod.rs b/src/recording/mod.rs new file mode 100644 index 0000000..3c3f8e4 --- /dev/null +++ b/src/recording/mod.rs @@ -0,0 +1,282 @@ +//! Opt-in transport evidence. Immutable blobs precede atomic event publication. +//! This records decoded HTTP entity bytes, not TLS packets or rewritten XML. + +use std::collections::BTreeMap; +use std::io::{Read, Write}; +use std::path::{Path, PathBuf}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +pub const SCHEMA: &str = "rpki-transport-capture-v1"; + +pub fn now_ms() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_millis() as u64 +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub struct BlobRef { + pub sha256: String, + pub size: u64, +} + +#[derive(Clone, Debug)] +pub struct TransportArchive { + root: PathBuf, +} + +impl TransportArchive { + pub fn open(root: &Path) -> Result { + for dir in ["blobs/sha256", "events", "partial"] { + std::fs::create_dir_all(root.join(dir)).map_err(|e| e.to_string())?; + } + Ok(Self { root: root.into() }) + } + + pub fn blob_path(&self, hash: &str) -> PathBuf { + self.root.join("blobs/sha256").join(&hash[..2]).join(hash) + } + + fn commit_blob( + &self, + mut file: tempfile::NamedTempFile, + hash: String, + size: u64, + ) -> Result { + file.flush().map_err(|e| e.to_string())?; + let path = self.blob_path(&hash); + std::fs::create_dir_all(path.parent().unwrap()).map_err(|e| e.to_string())?; + // No partial body is ever visible at a content-addressed path. Concurrent + // identical writes may replace identical bytes on the same filesystem. + file.persist(path).map_err(|e| e.to_string())?; + Ok(BlobRef { sha256: hash, size }) + } + + pub fn put_bytes(&self, bytes: &[u8]) -> Result { + let hash = hex::encode(Sha256::digest(bytes)); + let path = self.blob_path(&hash); + if path.is_file() { + return Ok(BlobRef { + sha256: hash, + size: bytes.len() as u64, + }); + } + let mut file = tempfile::NamedTempFile::new_in(self.root.join("partial")) + .map_err(|e| e.to_string())?; + file.write_all(bytes).map_err(|e| e.to_string())?; + self.commit_blob(file, hash, bytes.len() as u64) + } + + pub fn begin(&self, transport: &str, kind: &str, uri: &str) -> CaptureEvent { + CaptureEvent { + archive: self.clone(), + data: serde_json::json!({ + "schema": SCHEMA, "id": uuid::Uuid::new_v4().to_string(), + "source": "rpki", "transport": transport, "kind": kind, + "uri": uri, "started_ms": now_ms(), "complete": false, + }), + objects: BTreeMap::new(), + finished: false, + } + } +} + +#[derive(Debug)] +pub struct CaptureEvent { + archive: TransportArchive, + data: serde_json::Value, + objects: BTreeMap, + finished: bool, +} + +impl CaptureEvent { + pub fn response(&mut self, response: &reqwest::blocking::Response) { + self.data["status"] = response.status().as_u16().into(); + self.data["final_uri"] = response.url().as_str().into(); + let mut headers = BTreeMap::new(); + for name in [ + "etag", + "last-modified", + "content-type", + "content-length", + "content-encoding", + "date", + "location", + ] { + if let Some(value) = response.headers().get(name).and_then(|h| h.to_str().ok()) { + headers.insert(name, value); + } + } + self.data["headers"] = serde_json::to_value(headers).unwrap(); + } + + pub fn body(&mut self, bytes: &[u8]) -> Result<(), String> { + self.data["body"] = serde_json::to_value(self.archive.put_bytes(bytes)?).unwrap(); + Ok(()) + } + + /// Tee in bounded memory; a destination/read failure cannot publish a success. + pub fn copy(&mut self, input: &mut dyn Read, out: &mut dyn Write) -> Result { + let mut file = tempfile::NamedTempFile::new_in(self.archive.root.join("partial")) + .map_err(|e| e.to_string())?; + let mut digest = Sha256::new(); + let mut size = 0; + let mut buffer = [0u8; 65536]; + loop { + let n = input.read(&mut buffer).map_err(|e| e.to_string())?; + if n == 0 { + break; + } + out.write_all(&buffer[..n]).map_err(|e| e.to_string())?; + file.write_all(&buffer[..n]).map_err(|e| e.to_string())?; + digest.update(&buffer[..n]); + size += n as u64; + } + let blob = self + .archive + .commit_blob(file, hex::encode(digest.finalize()), size)?; + self.data["body"] = serde_json::to_value(blob).unwrap(); + Ok(size) + } + + pub fn object(&mut self, uri: &str, bytes: &[u8]) -> Result<(), String> { + self.objects + .insert(uri.into(), self.archive.put_bytes(bytes)?); + Ok(()) + } + + fn publish(&mut self, complete: bool) -> Result<(), String> { + self.data["completed_ms"] = now_ms().into(); + self.data["complete"] = complete.into(); + if self.data["transport"] == "rsync" { + self.data["objects"] = serde_json::to_value(&self.objects).unwrap(); + } + if !complete { + self.data["error"] = + "request, destination, body or archive did not complete; see RP log".into(); + } + let path = self + .archive + .root + .join("events") + .join(format!("{}.json", self.data["id"].as_str().unwrap())); + let mut tmp = tempfile::NamedTempFile::new_in(self.archive.root.join("partial")) + .map_err(|e| e.to_string())?; + serde_json::to_writer(&mut tmp, &self.data).map_err(|e| e.to_string())?; + tmp.flush().map_err(|e| e.to_string())?; + tmp.persist(path).map_err(|e| e.to_string())?; + self.finished = true; + Ok(()) + } + + pub fn finish(&mut self) -> Result<(), String> { + self.publish(true) + } +} + +impl Drop for CaptureEvent { + fn drop(&mut self) { + if !self.finished + && let Err(error) = self.publish(false) + { + eprintln!("transport recording failure: {error}"); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn events(root: &Path) -> Vec { + std::fs::read_dir(root.join("events")) + .unwrap() + .map(|e| serde_json::from_slice(&std::fs::read(e.unwrap().path()).unwrap()).unwrap()) + .collect() + } + + #[test] + fn stream_and_bytes_are_identical_and_deduplicated() { + let tmp = tempfile::tempdir().unwrap(); + let archive = TransportArchive::open(tmp.path()).unwrap(); + let bytes = vec![73; 200000]; + let expected = archive.put_bytes(&bytes).unwrap(); + let mut event = archive.begin("http", "snapshot", "https://rp.test/snapshot.xml"); + let mut output = Vec::new(); + assert_eq!( + event.copy(&mut bytes.as_slice(), &mut output).unwrap(), + bytes.len() as u64 + ); + event.finish().unwrap(); + drop(event); + assert_eq!(output, bytes); + let record = events(tmp.path()).pop().unwrap(); + assert_eq!(record["body"]["sha256"], expected.sha256); + assert_eq!(record["complete"], true); + assert_eq!( + std::fs::read(archive.blob_path(&expected.sha256)).unwrap(), + bytes + ); + assert_eq!( + std::fs::read_dir(tmp.path().join("partial")) + .unwrap() + .count(), + 0 + ); + } + + #[test] + fn failed_destination_never_commits_body_or_success() { + struct Broken; + impl Write for Broken { + fn write(&mut self, _: &[u8]) -> std::io::Result { + Err(std::io::Error::other("broken")) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + let tmp = tempfile::tempdir().unwrap(); + let archive = TransportArchive::open(tmp.path()).unwrap(); + let mut event = archive.begin("http", "delta", "https://rp.test/d.xml"); + assert!(event.copy(&mut &b"raw bytes"[..], &mut Broken).is_err()); + drop(event); + let record = events(tmp.path()).pop().unwrap(); + assert_eq!(record["complete"], false); + assert!(record.get("body").is_none()); + assert_eq!( + std::fs::read_dir(tmp.path().join("partial")) + .unwrap() + .count(), + 0 + ); + } + + #[test] + fn rsync_generations_preserve_deleted_files_and_failures() { + let tmp = tempfile::tempdir().unwrap(); + let archive = TransportArchive::open(tmp.path()).unwrap(); + for names in [vec!["a", "b"], vec!["a"]] { + let mut event = archive.begin("rsync", "view", "rsync://rp.test/mod/"); + for name in names { + event + .object(&format!("rsync://rp.test/mod/{name}"), name.as_bytes()) + .unwrap(); + } + event.finish().unwrap(); + } + drop(archive.begin("rsync", "view", "rsync://rp.test/mod/")); + let all = events(tmp.path()); + assert_eq!(all.iter().filter(|e| e["complete"] == true).count(), 2); + let mut counts: Vec<_> = all + .iter() + .map(|e| e["objects"].as_object().unwrap().len()) + .collect(); + counts.sort(); + assert_eq!(counts, vec![0, 1, 2]); + } +} diff --git a/src/replay/mod.rs b/src/replay/mod.rs index 56f5ac9..b590db3 100644 --- a/src/replay/mod.rs +++ b/src/replay/mod.rs @@ -4,3 +4,4 @@ pub mod delta_fetch_http; pub mod delta_fetch_rsync; pub mod fetch_http; pub mod fetch_rsync; +pub mod validation_benchmark; diff --git a/src/replay/validation_benchmark.rs b/src/replay/validation_benchmark.rs new file mode 100644 index 0000000..f8a6f9e --- /dev/null +++ b/src/replay/validation_benchmark.rs @@ -0,0 +1,909 @@ +//! Frozen-input measurement support. Never performs public network I/O. +use std::collections::BTreeMap; +use std::fs::File; +use std::io::BufReader; +use std::path::Path; +use std::sync::Arc; + +use serde::{Deserialize, Serialize}; + +use crate::fetch::rsync::{RsyncFetchError, RsyncFetchResult, RsyncFetcher}; +use crate::fetch::rsync_system::{RsyncScopePolicy, scoped_rsync_fetch_uri}; +use crate::sync::rrdp::Fetcher; + +use crate::storage::RocksStore; +use crate::verification_only::{self, ValidationContract}; +use std::fs; +use std::path::PathBuf; + +pub(crate) struct PreparedBenchmark { + pub root: PathBuf, + pub source_contract: ValidationContract, + pub table: Arc, + pub store: Option>, + ticks_per_second: f64, +} + +impl PreparedBenchmark { + pub fn validate_effective( + &self, + args: &crate::cli::CliArgs, + policy: &crate::policy::Policy, + validation_time: time::OffsetDateTime, + ) -> Result<(), String> { + if args.verification_only + || args.raw_store_db.is_some() + || args.repo_bytes_db.is_some() + || args.rsync_local_dir.is_some() + || args.payload_replay_archive.is_some() + || args.payload_base_archive.is_some() + || args.record_transport_dir.is_some() + || args.crypto_signature_cache_observe_only + || args.publication_point_cache_observe_only + || !policy + .verification_forced_vcir_reuse_manifest_uris + .is_empty() + { + return Err( + "validation benchmark conflicts with another input/output mode".to_string(), + ); + } + let source = &self.source_contract; + let actual_cache = verification_only::ValidationCacheContract { + publication_point: args.enable_publication_point_validation_cache, + roa: args.enable_roa_validation_cache, + child_certificate: args.enable_child_certificate_validation_cache, + transport_prefetch: args.enable_transport_request_prefetch, + crypto_signature: args.enable_crypto_signature_cache, + }; + // Runtime-only constraints are bound separately by their semantic fingerprint. + if serde_json::to_value(policy).map_err(|e| e.to_string())? + != serde_json::to_value(&source.policy).map_err(|e| e.to_string())? + || source.validation_time()? != validation_time + || source.cache != actual_cache + || source.max_ca_depth != args.max_ca_depth + || source.max_instances != args.max_instances + || source.rsync_scope_policy != args.rsync_scope_policy + || source.ta_constraints_fingerprint + != (!policy.ta_constraints.is_empty()) + .then(|| policy.ta_constraints.fingerprint_sha256_hex()) + { + return Err( + "benchmark effective policy/time/cache/constraints differ from T1".to_string(), + ); + } + Ok(()) + } + + pub fn clock(&self) -> Result { + EngineClock::start(self.ticks_per_second) + } + + pub fn write_measurement(&self, clock: EngineClock) -> Result<(), String> { + let result = clock.finish()?; + write_json(&self.root.join("engine-timing.json"), &result) + } +} + +fn write_json(path: &Path, value: &impl Serialize) -> Result<(), String> { + let bytes = serde_json::to_vec_pretty(value).map_err(|error| error.to_string())?; + fs::write(path, bytes).map_err(|error| format!("write {}: {error}", path.display())) +} + +fn copy_sidecar(source: &Path, destination: &Path) -> Result<(), String> { + if !source.exists() && !source.is_symlink() { + return Ok(()); + } + let metadata = fs::symlink_metadata(source).map_err(|e| e.to_string())?; + if metadata.is_file() { + fs::copy(source, destination).map_err(|e| e.to_string())?; + } else if metadata.is_dir() { + fs::create_dir(destination).map_err(|e| e.to_string())?; + for entry in fs::read_dir(source).map_err(|e| e.to_string())? { + let entry = entry.map_err(|e| e.to_string())?; + copy_sidecar(&entry.path(), &destination.join(entry.file_name()))?; + } + } else { + return Err(format!( + "non-regular benchmark sidecar: {}", + source.display() + )); + } + Ok(()) +} + +fn isolated_output(output: &Path, protected: &[&Path]) -> Result { + if output.exists() || output.is_symlink() { + return Err("benchmark output already exists".to_string()); + } + let parent = output + .parent() + .ok_or("benchmark output needs a parent")? + .canonicalize() + .map_err(|e| e.to_string())?; + let output = parent.join( + output + .file_name() + .ok_or("benchmark output needs a basename")?, + ); + for source in protected { + let source = source.canonicalize().map_err(|e| e.to_string())?; + if output.starts_with(&source) || source.starts_with(&output) { + return Err("benchmark output overlaps a protected source".to_string()); + } + } + Ok(output) +} + +#[derive(Deserialize)] +struct PreStateManifest { + created_unix_ns: u128, + checkpoint_root: PathBuf, + files_sha256: BTreeMap, +} + +fn checkpoint_files( + root: &Path, + directory: &Path, + files: &mut BTreeMap, +) -> Result<(), String> { + for entry in fs::read_dir(directory).map_err(|e| e.to_string())? { + let path = entry.map_err(|e| e.to_string())?.path(); + let meta = fs::symlink_metadata(&path).map_err(|e| e.to_string())?; + if meta.is_dir() { + checkpoint_files(root, &path, files)?; + } else if meta.is_file() { + files.insert( + path.strip_prefix(root) + .map_err(|e| e.to_string())? + .to_string_lossy() + .into_owned(), + verification_only::sha256_file(&path)?, + ); + } else { + return Err(format!("non-regular checkpoint entry: {}", path.display())); + } + } + Ok(()) +} + +fn validate_pre_state(source_run: &Path, pre_state: &Path) -> Result { + let manifest: PreStateManifest = serde_json::from_slice( + &fs::read(source_run.join("pre-state.json")).map_err(|e| e.to_string())?, + ) + .map_err(|e| e.to_string())?; + #[derive(Deserialize)] + struct Start { + started_unix_ns: u128, + } + let start: Start = serde_json::from_slice( + &fs::read(source_run.join("t1-start.json")).map_err(|e| e.to_string())?, + ) + .map_err(|e| e.to_string())?; + if manifest.created_unix_ns > start.started_unix_ns { + return Err("checkpoint was created after T1 started".to_string()); + } + let root = manifest + .checkpoint_root + .canonicalize() + .map_err(|e| e.to_string())?; + if pre_state == Path::new("empty") { + if !manifest.files_sha256.is_empty() { + return Err("empty pre-state has a nonempty checkpoint manifest".to_string()); + } + } else if pre_state.canonicalize().map_err(|e| e.to_string())? + != root.join("db").canonicalize().map_err(|e| e.to_string())? + { + return Err("pre-state is not bound to the T1 checkpoint root".to_string()); + } + let mut actual = BTreeMap::new(); + checkpoint_files(&root, &root, &mut actual)?; + if actual != manifest.files_sha256 { + return Err("pre-step checkpoint files differ from T1 provenance".to_string()); + } + Ok(root) +} + +fn rewrite_command(command: &[String], output: &Path) -> Result, String> { + let forbidden = [ + "--verification-only", + "--rsync-local-dir", + "--raw-store-db", + "--repo-bytes-db", + "--tal-url", + "--cir-static-root", + "--dead-repo-blacklist", + "--payload-replay-archive", + "--payload-base-archive", + ]; + let mut rewritten = vec![command.first().ok_or("empty source command")?.clone()]; + let targets = BTreeMap::from([ + ("--db", "state/db"), + ("--report-json", "report.json"), + ("--validation-contract-out", "contract.json"), + ("--ccr-out", "result.ccr"), + ("--cir-out", "input.cir"), + ("--analysis-out", "analysis"), + ("--vrps-csv-out", "vrps.csv"), + ("--vaps-csv-out", "vaps.csv"), + ]); + let mut seen = std::collections::BTreeSet::new(); + let mut index = 1; + while index < command.len() { + let arg = &command[index]; + if forbidden.contains(&arg.as_str()) { + return Err(format!("unsupported source command option: {arg}")); + } + if matches!( + arg.as_str(), + "--record-transport-dir" | "--rsync-mirror-root" | "--evaluation-metrics-out" + ) { + if index + 1 >= command.len() { + return Err(format!("source command missing value: {arg}")); + } + index += 2; + continue; + } + if let Some(target) = targets.get(arg.as_str()) { + if index + 1 >= command.len() || !seen.insert(arg.clone()) { + return Err(format!("missing/duplicate source output option: {arg}")); + } + rewritten.push(arg.clone()); + rewritten.push(output.join(target).to_string_lossy().into_owned()); + index += 2; + } else { + rewritten.push(arg.clone()); + index += 1; + } + } + for (arg, target) in targets { + if !seen.contains(arg) + && matches!( + arg, + "--db" + | "--report-json" + | "--validation-contract-out" + | "--ccr-out" + | "--cir-out" + | "--analysis-out" + ) + { + rewritten.extend([ + arg.to_string(), + output.join(target).to_string_lossy().into_owned(), + ]); + } + } + if !rewritten.iter().any(|arg| arg == "--cir-enable") { + rewritten.push("--cir-enable".to_string()); + } + if !rewritten.iter().any(|arg| arg == "--analyze") { + rewritten.push("--analyze".to_string()); + } + Ok(rewritten) +} + +pub fn run(argv: &[String]) -> Result<(), String> { + let mut options = BTreeMap::new(); + let mut index = 2; + while index < argv.len() { + let key = &argv[index]; + if !["--source-run", "--source-state", "--pre-state", "--out"].contains(&key.as_str()) + || index + 1 >= argv.len() + || options + .insert(key.clone(), argv[index + 1].clone()) + .is_some() + { + return Err("Usage: rpki --validation-benchmark --source-run DIR --source-state DB --pre-state DB|empty --out NEW_DIR".to_string()); + } + index += 2; + } + let get = |name: &str| { + options + .get(name) + .map(PathBuf::from) + .ok_or_else(|| format!("validation benchmark requires {name}")) + }; + let source_run = get("--source-run")?; + let source_state = get("--source-state")?; + let pre_state = get("--pre-state")?; + let checkpoint_root = validate_pre_state(&source_run, &pre_state)?; + let mut protected = vec![ + source_run.as_path(), + source_state.as_path(), + checkpoint_root.as_path(), + ]; + if pre_state != Path::new("empty") { + protected.push(&pre_state); + } + let root = isolated_output(&get("--out")?, &protected)?; + let contract = verification_only::read_validation_contract(&source_run.join("contract.json"))?; + contract.require_current_binary()?; + if contract.cache.transport_prefetch { + return Err("benchmark transport-prefetch profile is not supported".to_string()); + } + let source_binding = { + let cir = verification_only::read_cir(&source_run.join("input.cir"))?; + if cir.validation_time != contract.validation_time()? { + return Err("source CIR/contract time mismatch".to_string()); + } + ( + cir.validation_time, + cir.object_list_sha256, + cir.reject_list_sha256, + cir.trust_anchors, + ) + }; + let table = Arc::new(FrozenTransportTable::from_report( + &source_run.join("report.json"), + contract.rsync_scope_policy, + )?); + let command: Vec = serde_json::from_slice( + &fs::read(source_run.join("command.json")).map_err(|e| e.to_string())?, + ) + .map_err(|e| e.to_string())?; + let source_args = crate::cli::parse_args(&command)?; + if source_args + .db_path + .canonicalize() + .map_err(|e| e.to_string())? + != source_state.canonicalize().map_err(|e| e.to_string())? + { + return Err("source command is bound to a different T1 database".to_string()); + } + let normal_command = rewrite_command(&command, &root)?; + fs::create_dir(&root).map_err(|e| e.to_string())?; + fs::create_dir(root.join("state")).map_err(|e| e.to_string())?; + let scratch = root.join("state/db"); + if pre_state != Path::new("empty") { + if pre_state.canonicalize().map_err(|e| e.to_string())? + == source_state.canonicalize().map_err(|e| e.to_string())? + { + return Err("pre-step cache must not be the T1 post-step database".to_string()); + } + RocksStore::create_read_only_checkpoint(&pre_state, &scratch).map_err(|e| e.to_string())?; + for suffix in [ + ".crypto-sig-cache", + ".pp-cache-index", + ".child-cert-cache-index", + ] { + let source_name = format!( + "{}{suffix}", + pre_state + .file_name() + .ok_or("pre-state basename missing")? + .to_string_lossy() + ); + copy_sidecar( + &pre_state.with_file_name(source_name), + &scratch.with_file_name(format!("db{suffix}")), + )?; + } + } + let store = Arc::new(RocksStore::open(&scratch).map_err(|e| e.to_string())?); + let overlay = store + .import_frozen_repository_for_benchmark(&source_state) + .map_err(|e| e.to_string())?; + let blobs = store + .verify_current_repository_blobs(1024) + .map_err(|e| e.to_string())?; + for selection in &contract.fallback_replay_selections { + let actual = verification_only::fallback_replay_selection_for_manifest( + store.as_ref(), + &selection.manifest_rsync_uri, + )?; + if actual != *selection { + return Err("T1 fallback conclusion is absent/different in pre-step cache".to_string()); + } + } + write_json( + &root.join("input-overlay.json"), + &serde_json::json!({ + "overlay": overlay, "blobs": blobs, "pre_state": pre_state, "source_state": source_state, + "source_contract_sha256": verification_only::sha256_file(&source_run.join("contract.json"))?, + "source_cir_sha256": verification_only::sha256_file(&source_run.join("input.cir"))?, + "source_ccr_sha256": verification_only::sha256_file(&source_run.join("result.ccr"))?, + "source_pre_state_sha256": verification_only::sha256_file(&source_run.join("pre-state.json"))?, + "pre_state_files_verified": true, + "transport_table": table.as_ref(), "normal_command": normal_command, + }), + )?; + let ticks = std::process::Command::new("getconf") + .arg("CLK_TCK") + .output() + .map_err(|e| e.to_string())?; + let ticks_per_second: f64 = std::str::from_utf8(&ticks.stdout) + .map_err(|e| e.to_string())? + .trim() + .parse() + .map_err(|e: std::num::ParseFloatError| e.to_string())?; + if !ticks.status.success() || !ticks_per_second.is_finite() || ticks_per_second <= 0.0 { + return Err("invalid CPU clock tick resolution".to_string()); + } + let mut prepared = PreparedBenchmark { + root: root.clone(), + source_contract: contract, + table, + store: Some(store), + ticks_per_second, + }; + crate::cli::run_validation_benchmark(&normal_command, &mut prepared)?; + let target = verification_only::read_cir(&root.join("input.cir"))?; + let inputs_match = target.validation_time == source_binding.0 + && target.object_list_sha256 == source_binding.1 + && target.reject_list_sha256 == source_binding.2 + && target.trust_anchors == source_binding.3; + let comparison = verification_only::compare_ccr_files( + &source_run.join("result.ccr"), + &root.join("result.ccr"), + )?; + let actual_contract = verification_only::read_validation_contract(&root.join("contract.json"))?; + let fallback = verification_only::compare_fallback_replay_selections( + &prepared.source_contract.fallback_replay_selections, + &actual_contract.fallback_replay_selections, + ); + write_json( + &root.join("equivalence.json"), + &serde_json::json!({"pass": inputs_match && comparison.state_digest_match && fallback.matches, + "inputs_match": inputs_match, "ccr": comparison, "fallback": fallback}), + )?; + if !inputs_match || !comparison.state_digest_match || !fallback.matches { + return Err("T2 input/payload/fallback differs from T1; sample rejected".to_string()); + } + Ok(()) +} + +pub(crate) struct EngineClock { + start: std::time::Instant, + cpu: (u64, u64), + ticks_per_second: f64, +} + +fn cpu_ticks() -> Result<(u64, u64), String> { + let data = fs::read_to_string("/proc/self/stat").map_err(|e| e.to_string())?; + let fields: Vec<&str> = data + .rsplit_once(") ") + .ok_or("invalid process stat")? + .1 + .split_whitespace() + .collect(); + Ok(( + fields + .get(11) + .ok_or("missing user CPU ticks")? + .parse() + .map_err(|e: std::num::ParseIntError| e.to_string())?, + fields + .get(12) + .ok_or("missing system CPU ticks")? + .parse() + .map_err(|e: std::num::ParseIntError| e.to_string())?, + )) +} + +impl EngineClock { + fn start(ticks_per_second: f64) -> Result { + Ok(Self { + cpu: cpu_ticks()?, + start: std::time::Instant::now(), + ticks_per_second, + }) + } + fn finish(self) -> Result { + let wall_ns = self.start.elapsed().as_nanos(); + let cpu = cpu_ticks()?; + Ok( + serde_json::json!({"schema":"rpki-frozen-validation-timing-v1", "wall_ns":wall_ns, + "user_cpu_secs": (cpu.0 - self.cpu.0) as f64 / self.ticks_per_second, + "system_cpu_secs": (cpu.1 - self.cpu.1) as f64 / self.ticks_per_second, + "cpu_tick_resolution_secs": 1.0 / self.ticks_per_second, + "boundary":"cache load, frozen-input validation and payload derivation, required cache/index persist and background write drain; excludes input overlay/drain, report/CIR/CCR encoding and output writes"}), + ) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum FrozenOutcome { + Success, + Failure(String), +} + +impl FrozenOutcome { + fn as_result(&self) -> Result { + match self { + Self::Success => Ok(0), + Self::Failure(error) => Err(error.clone()), + } + } +} + +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +pub struct FrozenTransportTable { + pub rrdp: BTreeMap, + pub rsync: BTreeMap, + pub source_publication_points: usize, +} + +#[derive(Deserialize)] +struct Report { + publication_points: Vec, +} + +#[derive(Deserialize)] +struct PublicationPoint { + rsync_base_uri: String, + rrdp_notification_uri: Option, + repo_sync_phase: Option, + repo_sync_error: Option, +} + +fn insert_outcome( + table: &mut BTreeMap, + uri: String, + outcome: FrozenOutcome, +) -> Result<(), String> { + if let Some(previous) = table.get(&uri) { + if previous != &outcome { + return Err(format!("contradictory frozen transport outcomes: {uri}")); + } + } else { + table.insert(uri, outcome); + } + Ok(()) +} + +impl FrozenTransportTable { + pub fn from_report(path: &Path, scope: RsyncScopePolicy) -> Result { + // Deserialize only transport fields, skipping large object/payload arrays. + let input = File::open(path).map_err(|error| format!("open source report: {error}"))?; + let report: Report = serde_json::from_reader(BufReader::new(input)) + .map_err(|error| format!("decode source report: {error}"))?; + let mut table = Self { + source_publication_points: report.publication_points.len(), + ..Self::default() + }; + for pp in report.publication_points { + let scope_uri = scoped_rsync_fetch_uri(scope, &pp.rsync_base_uri); + match pp.repo_sync_phase.as_deref() { + Some("rrdp_ok") => { + let uri = pp + .rrdp_notification_uri + .ok_or("RRDP success without notification URI")?; + insert_outcome(&mut table.rrdp, uri, FrozenOutcome::Success)?; + } + Some("rrdp_failed_rsync_ok") => { + let uri = pp + .rrdp_notification_uri + .ok_or("RRDP fallback without notification URI")?; + insert_outcome( + &mut table.rrdp, + uri, + FrozenOutcome::Failure("frozen source RRDP failure".to_string()), + )?; + insert_outcome(&mut table.rsync, scope_uri, FrozenOutcome::Success)?; + } + Some("rsync_only_ok") => { + insert_outcome(&mut table.rsync, scope_uri, FrozenOutcome::Success)?; + } + Some("rrdp_failed_rsync_failed") | Some("rsync_failed") => { + if let Some(uri) = pp.rrdp_notification_uri { + insert_outcome( + &mut table.rrdp, + uri, + FrozenOutcome::Failure("frozen source RRDP failure".to_string()), + )?; + } + let error = pp + .repo_sync_error + .ok_or("failed source transport without error evidence")?; + let error = error + .strip_prefix("rsync fallback failed: rsync fetch error: ") + .unwrap_or(&error) + .to_string(); + // Deduplicated publication points may retain different timeout text. + // Preserve the failure class, requiring consistent success/failure. + if let Some(FrozenOutcome::Failure(_)) = table.rsync.get(&scope_uri) { + continue; + } + insert_outcome(&mut table.rsync, scope_uri, FrozenOutcome::Failure(error))?; + } + other => { + return Err(format!( + "unsupported/missing source sync phase {other:?}: {}", + pp.rsync_base_uri + )); + } + } + } + Ok(table) + } +} + +#[derive(Clone)] +pub struct FrozenHttpFetcher(pub Arc); + +impl Fetcher for FrozenHttpFetcher { + fn frozen_sync_outcome(&self, uri: &str) -> Option> { + Some( + self.0 + .rrdp + .get(uri) + .map(FrozenOutcome::as_result) + .unwrap_or_else(|| Err(format!("unbound frozen RRDP transport: {uri}"))), + ) + } + fn fetch(&self, uri: &str) -> Result, String> { + Err(format!("network disabled for validation benchmark: {uri}")) + } +} + +#[derive(Clone)] +pub struct FrozenRsyncFetcher { + pub table: Arc, + pub scope: RsyncScopePolicy, +} + +impl RsyncFetcher for FrozenRsyncFetcher { + fn frozen_sync_outcome(&self, uri: &str) -> Option> { + let scope = scoped_rsync_fetch_uri(self.scope, uri); + Some( + self.table + .rsync + .get(&scope) + .map(FrozenOutcome::as_result) + .unwrap_or_else(|| Err(format!("unbound frozen rsync transport: {scope}"))), + ) + } + fn fetch_objects(&self, uri: &str) -> RsyncFetchResult)>> { + Err(RsyncFetchError::Fetch(format!( + "network disabled for validation benchmark: {uri}" + ))) + } + fn fetch_object(&self, uri: &str) -> RsyncFetchResult> { + Err(RsyncFetchError::Fetch(format!( + "network disabled for validation benchmark: {uri}" + ))) + } + fn dedup_key(&self, uri: &str) -> String { + scoped_rsync_fetch_uri(self.scope, uri) + } + fn failure_dedup_key(&self, uri: &str) -> Option { + Some(self.dedup_key(uri)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn benchmark_requires_natural_fallback_even_when_contract_selects_vcir() { + let argv = [ + "rpki", + "--db", + "unused-db", + "--tal-url", + "https://example.test/root.tal", + ] + .map(str::to_string); + let args = crate::cli::parse_args(&argv).unwrap(); + let policy = crate::policy::Policy::default(); + let validation_time = time::OffsetDateTime::from_unix_timestamp(1_794_221_384).unwrap(); + let mut contract = ValidationContract::for_current_binary( + validation_time, + policy.clone(), + args.max_ca_depth, + args.max_instances, + verification_only::ValidationCacheContract { + publication_point: args.enable_publication_point_validation_cache, + roa: args.enable_roa_validation_cache, + child_certificate: args.enable_child_certificate_validation_cache, + transport_prefetch: args.enable_transport_request_prefetch, + crypto_signature: args.enable_crypto_signature_cache, + }, + args.rsync_scope_policy, + ) + .unwrap(); + let manifest_uri = "rsync://example.test/repo/current.mft".to_string(); + contract + .fallback_replay_selections + .push(verification_only::FallbackReplaySelection { + manifest_rsync_uri: manifest_uri.clone(), + vcir_sha256: "22".repeat(32), + reuse_identity_sha256: "33".repeat(32), + }); + let prepared = PreparedBenchmark { + root: PathBuf::from("unused"), + source_contract: contract, + table: Arc::new(FrozenTransportTable::default()), + store: None, + ticks_per_second: 100.0, + }; + prepared + .validate_effective(&args, &policy, validation_time) + .unwrap(); + let mut forced = policy.clone(); + forced + .verification_forced_vcir_reuse_manifest_uris + .insert(manifest_uri); + // This runtime-only flag is intentionally absent from serialized policy; + // equality of the ordinary policy fingerprint cannot catch the bypass. + assert_eq!( + serde_json::to_value(&policy).unwrap(), + serde_json::to_value(&forced).unwrap() + ); + assert!( + prepared + .validate_effective(&args, &forced, validation_time) + .is_err() + ); + } + + #[test] + fn benchmark_rejects_changed_or_late_checkpoint_provenance() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().join("pre"); + let run = temp.path().join("run"); + fs::create_dir_all(root.join("db")).unwrap(); + fs::create_dir(&run).unwrap(); + let cache = root.join("db.crypto-sig-cache"); + fs::write(&cache, b"pre-step-successes").unwrap(); + let mut files = BTreeMap::new(); + checkpoint_files(&root, &root, &mut files).unwrap(); + let manifest = + json!({"created_unix_ns": 9, "checkpoint_root": root, "files_sha256": files}); + write_json(&run.join("pre-state.json"), &manifest).unwrap(); + write_json(&run.join("t1-start.json"), &json!({"started_unix_ns": 10})).unwrap(); + assert_eq!(validate_pre_state(&run, &root.join("db")).unwrap(), root); + assert!(validate_pre_state(&run, Path::new("empty")).is_err()); + fs::write(&cache, b"post-step-successes").unwrap(); + assert!( + validate_pre_state(&run, &root.join("db")) + .unwrap_err() + .contains("files differ") + ); + let mut late = manifest; + late["created_unix_ns"] = json!(11); + write_json(&run.join("pre-state.json"), &late).unwrap(); + assert!( + validate_pre_state(&run, &root.join("db")) + .unwrap_err() + .contains("after T1") + ); + } + + #[test] + fn benchmark_rewrites_outputs_and_rejects_shared_failure_state() { + let args: Vec = [ + "rpki", + "--db", + "/source/db", + "--report-json", + "/source/report.json", + "--record-transport-dir", + "/source/archive", + "--rsync-mirror-root", + "/source/mirror", + "--evaluation-metrics-out", + "/source/evaluation.json", + "--tal-path", + "/input/afrinic.tal", + "--ta-path", + "/input/afrinic.cer", + "--enable-crypto-signature-cache", + ] + .into_iter() + .map(str::to_string) + .collect(); + let rewritten = rewrite_command(&args, Path::new("/scratch")).unwrap(); + assert!(!rewritten.iter().any(|s| s.starts_with("/source/"))); + assert!( + rewritten + .windows(2) + .any(|a| a == ["--db", "/scratch/state/db"]) + ); + assert!(rewritten.iter().any(|s| s == "/input/afrinic.tal")); + assert!( + rewritten + .iter() + .any(|s| s == "--enable-crypto-signature-cache") + ); + let mut unsafe_args = args; + unsafe_args.extend(["--dead-repo-blacklist".into(), "/source/blacklist".into()]); + assert!( + rewrite_command(&unsafe_args, Path::new("/scratch")) + .unwrap_err() + .contains("unsupported") + ); + } + + #[test] + fn benchmark_output_cannot_overlap_sources_or_follow_sidecar_links() { + let root = tempfile::tempdir().unwrap(); + let source = root.path().join("source"); + fs::create_dir(&source).unwrap(); + assert!(isolated_output(&source.join("scratch"), &[&source]).is_err()); + assert!(isolated_output(&source, &[&source]).is_err()); + assert!(isolated_output(&root.path().join("scratch"), &[&source]).is_ok()); + let original = source.join("index"); + fs::write(&original, b"pre-step-cache").unwrap(); + let copied = root.path().join("copy"); + copy_sidecar(&original, &copied).unwrap(); + fs::write(&copied, b"new-cache").unwrap(); + assert_eq!(fs::read(&original).unwrap(), b"pre-step-cache"); + #[cfg(unix)] + { + let link = source.join("index-link"); + std::os::unix::fs::symlink(&original, &link).unwrap(); + assert!(copy_sidecar(&link, &root.path().join("linked-copy")).is_err()); + } + } + + #[test] + fn frozen_transport_preserves_failure_even_with_available_old_view() { + let root = tempfile::tempdir().unwrap(); + let path = root.path().join("report.json"); + std::fs::write(&path, serde_json::to_vec(&json!({"publication_points":[{ + "rsync_base_uri":"rsync://repo.example/module/ca/", "rrdp_notification_uri":"https://repo.example/notify.xml", + "repo_sync_phase":"rrdp_failed_rsync_failed", "repo_sync_error":"rsync fallback failed: rsync fetch error: original failure" + }]})).unwrap()).unwrap(); + let table = Arc::new( + FrozenTransportTable::from_report(&path, RsyncScopePolicy::ModuleRoot).unwrap(), + ); + let http = FrozenHttpFetcher(Arc::clone(&table)); + assert!( + http.frozen_sync_outcome("https://repo.example/notify.xml") + .unwrap() + .is_err() + ); + let rsync = FrozenRsyncFetcher { + table, + scope: RsyncScopePolicy::ModuleRoot, + }; + assert_eq!( + rsync + .frozen_sync_outcome("rsync://repo.example/module/ca/") + .unwrap() + .unwrap_err(), + "original failure" + ); + assert!(rsync.fetch_objects("rsync://repo.example/module/").is_err()); + assert!(http.fetch("https://unrecorded.example/").is_err()); + assert!( + http.frozen_sync_outcome("https://unrecorded.example/") + .unwrap() + .is_err() + ); + } + + #[test] + fn frozen_transport_rejects_conflicting_or_unknown_source_outcomes() { + let root = tempfile::tempdir().unwrap(); + let path = root.path().join("report.json"); + let success = json!({"rsync_base_uri":"rsync://a.example/module/", "rrdp_notification_uri":"https://a.example/n.xml", "repo_sync_phase":"rrdp_ok"}); + let mut failed = success.clone(); + failed["repo_sync_phase"] = json!("rrdp_failed_rsync_failed"); + failed["repo_sync_error"] = json!("failure"); + std::fs::write( + &path, + serde_json::to_vec(&json!({"publication_points":[success,failed]})).unwrap(), + ) + .unwrap(); + assert!( + FrozenTransportTable::from_report(&path, RsyncScopePolicy::ModuleRoot) + .unwrap_err() + .contains("contradictory") + ); + std::fs::write( + &path, + b"{\"publication_points\":[{\"rsync_base_uri\":\"rsync://a.example/module/\"}]}", + ) + .unwrap(); + assert!( + FrozenTransportTable::from_report(&path, RsyncScopePolicy::ModuleRoot) + .unwrap_err() + .contains("unsupported/missing") + ); + } +} diff --git a/src/storage.rs b/src/storage.rs index 19ddc35..2cd11dc 100644 --- a/src/storage.rs +++ b/src/storage.rs @@ -1,3 +1,4 @@ +mod benchmark; mod config; mod keys; mod pack; @@ -15,6 +16,7 @@ use serde::{Deserialize, Serialize}; use crate::blob_store::{ExternalRawStoreDb, ExternalRepoBytesDb, RawObjectStore}; use crate::data_model::rc::{AsResourceSet, IpResourceSet}; +pub use benchmark::{FrozenRepositoryImportProof, StateColumnFingerprint}; use config::*; pub use config::{ ALL_COLUMN_FAMILY_NAMES, CF_CHILD_CERTIFICATE_CACHE_PROJECTION, CF_MANIFEST_REPLAY_META, @@ -4326,7 +4328,7 @@ impl RocksStore { self.try_load_publication_point_cache_mmap_index_for_update("refresh")?; enum RefreshAction { Entries { - entries: Vec<(String, Vec)>, + entries: Vec<(String, Arc<[u8]>)>, write_segment: bool, old_entries: usize, dirty_entries: usize, @@ -4347,7 +4349,7 @@ impl RocksStore { RefreshAction::Entries { entries: dirty .iter() - .map(|(key, value)| (key.clone(), value.as_ref().to_vec())) + .map(|(key, value)| (key.clone(), Arc::clone(value))) .collect::>(), write_segment: true, old_entries: mmap.entries(), @@ -4359,7 +4361,7 @@ impl RocksStore { RefreshAction::Entries { entries: index .iter() - .map(|(key, value)| (key.clone(), value.as_ref().to_vec())) + .map(|(key, value)| (key.clone(), Arc::clone(value))) .collect::>(), write_segment: false, old_entries: 0, @@ -4378,7 +4380,10 @@ impl RocksStore { dirty_entries, } => (entries, write_segment, old_entries, dirty_entries), RefreshAction::ScanDb => ( - self.load_publication_point_cache_projection_entries()?, + self.load_publication_point_cache_projection_entries()? + .into_iter() + .map(|(key, value)| (key, Arc::<[u8]>::from(value))) + .collect(), false, 0, 0, diff --git a/src/storage/benchmark.rs b/src/storage/benchmark.rs new file mode 100644 index 0000000..a67bfc5 --- /dev/null +++ b/src/storage/benchmark.rs @@ -0,0 +1,288 @@ +//! Explicit experiment-only input overlay. Never imports a validation result. +use std::collections::BTreeMap; +use std::path::Path; + +use rocksdb::{DB, IteratorMode, Options, WriteBatch}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +use super::*; + +const INPUT_COLUMNS: &[&str] = &[ + CF_REPOSITORY_VIEW, + CF_RAW_BY_HASH, + CF_RAW_BLOB, + CF_RRDP_SOURCE, + CF_RRDP_SOURCE_MEMBER, + CF_RRDP_URI_OWNER, +]; +const CACHE_COLUMNS: &[&str] = &[ + CF_VCIR, + CF_VCIR_FAILED_FETCH_REUSE_IDENTITY, + CF_MANIFEST_REPLAY_META, + CF_ROA_CACHE_PROJECTION, + CF_CHILD_CERTIFICATE_CACHE_PROJECTION, + CF_PUBLICATION_POINT_CACHE_PROJECTION, + CF_TRANSPORT_PREFETCH, +]; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct StateColumnFingerprint { + pub keys: u64, + pub key_value_bytes: u64, + pub sha256: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct FrozenRepositoryImportProof { + pub imported_columns: BTreeMap, + pub cache_before: BTreeMap, + pub cache_after: BTreeMap, + pub background_io_drained: bool, +} + +fn fingerprint(db: &DB, name: &str) -> StorageResult { + let cf = db + .cf_handle(name) + .ok_or_else(|| StorageError::InvalidData { + entity: "benchmark_column", + detail: format!("missing column family: {name}"), + })?; + let mut digest = Sha256::new(); + let (mut keys, mut size) = (0u64, 0u64); + for item in db.iterator_cf(cf, IteratorMode::Start) { + let (key, value) = item.map_err(|error| StorageError::RocksDb(error.to_string()))?; + digest.update((key.len() as u64).to_be_bytes()); + digest.update(&key); + digest.update((value.len() as u64).to_be_bytes()); + digest.update(&value); + keys += 1; + size += (key.len() + value.len()) as u64; + } + Ok(StateColumnFingerprint { + keys, + key_value_bytes: size, + sha256: hex::encode(digest.finalize()), + }) +} + +impl RocksStore { + /// Finish background writes inside the measured engine. Staging drains + /// before the clock; validation drains before stopping it. + pub fn drain_validation_benchmark_io(&self) -> StorageResult<()> { + let mut wait = rocksdb::WaitForCompactOptions::default(); + wait.set_flush(true); + wait.set_abort_on_pause(true); + wait.set_timeout(60_000_000); + self.db.wait_for_compact(&wait).map_err(|error| { + StorageError::RocksDb(format!( + "benchmark background writes did not drain: {error}" + )) + }) + } + + pub fn validation_cache_fingerprints( + &self, + ) -> StorageResult> { + CACHE_COLUMNS + .iter() + .map(|name| Ok((name.to_string(), fingerprint(&self.db, name)?))) + .collect() + } + + /// Replace only the frozen raw input, retaining the scratch's pre-step caches. + /// Callers must own an isolated scratch; partial imports are never resumable. + pub fn import_frozen_repository_for_benchmark( + &self, + source: &Path, + ) -> StorageResult { + if self.external_raw_store.is_some() || self.external_repo_bytes.is_some() { + return Err(StorageError::InvalidData { + entity: "benchmark_input", + detail: "external raw stores are not supported by the benchmark overlay" + .to_string(), + }); + } + let source_path = source + .canonicalize() + .map_err(|error| StorageError::RocksDb(error.to_string()))?; + let destination_path = self + .db + .path() + .canonicalize() + .map_err(|error| StorageError::RocksDb(error.to_string()))?; + if source_path.starts_with(&destination_path) || destination_path.starts_with(&source_path) + { + return Err(StorageError::InvalidData { + entity: "benchmark_input", + detail: "source and scratch paths must not overlap".to_string(), + }); + } + let mut options = Options::default(); + let blob_mode = work_db_blob_mode_from_env(); + configure_work_db_options(&mut options, blob_mode, work_db_memory_profile_from_env()); + let source_db = DB::open_cf_descriptors_read_only( + &options, + &source_path, + column_family_descriptors_for_blob_mode(blob_mode), + false, + ) + .map_err(|error| StorageError::RocksDb(error.to_string()))?; + let cache_before = self.validation_cache_fingerprints()?; + let mut imported_columns = BTreeMap::new(); + for &name in INPUT_COLUMNS { + let destination_cf = self.cf(name)?; + let source_cf = source_db + .cf_handle(name) + .ok_or(StorageError::MissingColumnFamily(name))?; + let mut batch = WriteBatch::default(); + let mut pending = 0usize; + // Remove stale/withdrawn scratch entries before copying the exact source view. + for item in self.db.iterator_cf(destination_cf, IteratorMode::Start) { + let (key, _) = item.map_err(|error| StorageError::RocksDb(error.to_string()))?; + batch.delete_cf(destination_cf, key); + pending += 1; + if pending >= 1024 { + self.write_batch(std::mem::take(&mut batch))?; + pending = 0; + } + } + if pending > 0 { + self.write_batch(batch)?; + } + let mut batch = WriteBatch::default(); + let (mut pending, mut pending_bytes) = (0usize, 0usize); + for item in source_db.iterator_cf(source_cf, IteratorMode::Start) { + let (key, value) = + item.map_err(|error| StorageError::RocksDb(error.to_string()))?; + pending_bytes += key.len() + value.len(); + batch.put_cf(destination_cf, key, value); + pending += 1; + if pending >= 1024 || pending_bytes >= 8 * 1024 * 1024 { + self.write_batch(std::mem::take(&mut batch))?; + pending = 0; + pending_bytes = 0; + } + } + if pending > 0 { + self.write_batch(batch)?; + } + let expected = fingerprint(&source_db, name)?; + if fingerprint(&self.db, name)? != expected { + return Err(StorageError::InvalidData { + entity: "benchmark_input", + detail: format!("frozen column differs after import: {name}"), + }); + } + imported_columns.insert(name.to_string(), expected); + } + let cache_after = self.validation_cache_fingerprints()?; + if cache_before != cache_after { + return Err(StorageError::InvalidData { + entity: "benchmark_input", + detail: "validation cache changed during raw input overlay".to_string(), + }); + } + // Do not charge asynchronous input staging to the later validation clock. + // No validation or external writer runs against this private scratch yet. + self.drain_validation_benchmark_io()?; + Ok(FrozenRepositoryImportProof { + imported_columns, + cache_before, + cache_after, + background_io_drained: true, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn benchmark_overlay_replaces_inputs_without_importing_post_step_successes() { + let root = tempfile::tempdir().unwrap(); + let source_path = root.path().join("post"); + let scratch_path = root.path().join("scratch"); + { + let source = RocksStore::open(&source_path).unwrap(); + for &name in INPUT_COLUMNS { + source + .db + .put_cf(source.cf(name).unwrap(), b"new-input", b"post raw bytes") + .unwrap(); + } + for &name in CACHE_COLUMNS { + source + .db + .put_cf( + source.cf(name).unwrap(), + b"new-positive-conclusion", + b"must never import", + ) + .unwrap(); + } + } + let scratch = RocksStore::open(&scratch_path).unwrap(); + for &name in INPUT_COLUMNS { + scratch + .db + .put_cf(scratch.cf(name).unwrap(), b"stale-input", b"must disappear") + .unwrap(); + } + for &name in CACHE_COLUMNS { + scratch + .db + .put_cf( + scratch.cf(name).unwrap(), + b"pre-step-conclusion", + b"retain unchanged", + ) + .unwrap(); + } + let proof = scratch + .import_frozen_repository_for_benchmark(&source_path) + .unwrap(); + assert_eq!(proof.cache_before, proof.cache_after); + for &name in CACHE_COLUMNS { + let cf = scratch.cf(name).unwrap(); + assert_eq!( + scratch + .db + .get_cf(cf, b"pre-step-conclusion") + .unwrap() + .as_deref(), + Some(b"retain unchanged".as_slice()) + ); + assert!( + scratch + .db + .get_cf(cf, b"new-positive-conclusion") + .unwrap() + .is_none() + ); + } + for &name in INPUT_COLUMNS { + let cf = scratch.cf(name).unwrap(); + assert!(scratch.db.get_cf(cf, b"stale-input").unwrap().is_none()); + assert_eq!( + scratch.db.get_cf(cf, b"new-input").unwrap().as_deref(), + Some(b"post raw bytes".as_slice()) + ); + } + } + + #[test] + fn benchmark_overlay_rejects_the_authoritative_database_as_scratch() { + let root = tempfile::tempdir().unwrap(); + let path = root.path().join("db"); + let store = RocksStore::open(&path).unwrap(); + assert!( + store + .import_frozen_repository_for_benchmark(&path) + .unwrap_err() + .to_string() + .contains("must not overlap") + ); + } +} diff --git a/src/storage/pp_cache_index.rs b/src/storage/pp_cache_index.rs index 68065be..34294b8 100644 --- a/src/storage/pp_cache_index.rs +++ b/src/storage/pp_cache_index.rs @@ -1,6 +1,6 @@ use std::collections::{BTreeMap, HashMap}; use std::fs::{self, File}; -use std::io::Write; +use std::io::{BufWriter, Write}; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::time::{Instant, SystemTime, UNIX_EPOCH}; @@ -346,7 +346,7 @@ pub fn compact_pp_cache_index(dir: &Path) -> StorageResult StorageResult( +pub fn write_pp_cache_index_segment( dir: &Path, entries: I, ) -> StorageResult where - I: IntoIterator)>, + I: IntoIterator, + V: AsRef<[u8]>, { fs::create_dir_all(dir).map_err(|e| StorageError::RocksDb(e.to_string()))?; let current = dir.join("current.idx"); @@ -400,12 +401,13 @@ where Ok(stats) } -pub fn write_pp_cache_index_atomic( +pub fn write_pp_cache_index_atomic( path: &Path, entries: I, ) -> StorageResult where - I: IntoIterator)>, + I: IntoIterator, + V: AsRef<[u8]>, { let started = Instant::now(); let parent = path.parent().ok_or_else(|| StorageError::InvalidData { @@ -414,7 +416,8 @@ where })?; fs::create_dir_all(parent).map_err(|e| StorageError::RocksDb(e.to_string()))?; - let mut ordered = BTreeMap::>::new(); + // Retain shared/borrowed values without copying the entire cache payload. + let mut ordered = BTreeMap::::new(); for (key, value) in entries { ordered.insert(key, value); } @@ -422,7 +425,7 @@ where let tmp_path = parent.join("next.tmp"); write_pp_cache_index_file( &tmp_path, - ordered.iter().map(|(k, v)| (k.as_str(), v.as_slice())), + ordered.iter().map(|(k, v)| (k.as_str(), v.as_ref())), )?; let file_bytes = fs::metadata(&tmp_path) .map_err(|e| StorageError::RocksDb(e.to_string()))? @@ -448,12 +451,11 @@ where let entry_table_len = entries.len() * ENTRY_LEN; let blob_offset = entry_table_offset + entry_table_len; let mut table = Vec::with_capacity(entry_table_len); - let mut blob = Vec::new(); + let mut blob_len = 0usize; for (key, value) in entries.iter() { - let key_offset = blob.len(); - blob.extend_from_slice(key.as_bytes()); - let value_offset = blob.len(); - blob.extend_from_slice(value); + let key_offset = blob_len; + let value_offset = key_offset + key.len(); + blob_len = value_offset + value.len(); write_u64(&mut table, key_offset as u64); write_u32(&mut table, key.len() as u32); write_u64(&mut table, value_offset as u64); @@ -467,17 +469,24 @@ where write_u64(&mut header, entry_table_offset as u64); write_u64(&mut header, entry_table_len as u64); write_u64(&mut header, blob_offset as u64); - write_u64(&mut header, blob.len() as u64); + write_u64(&mut header, blob_len as u64); header.resize(HEADER_LEN, 0); - let mut file = File::create(path).map_err(|e| StorageError::RocksDb(e.to_string()))?; + let mut file = + BufWriter::new(File::create(path).map_err(|e| StorageError::RocksDb(e.to_string()))?); file.write_all(&header) .map_err(|e| StorageError::RocksDb(e.to_string()))?; file.write_all(&table) .map_err(|e| StorageError::RocksDb(e.to_string()))?; - file.write_all(&blob) + for (key, value) in entries { + file.write_all(key.as_bytes()) + .and_then(|_| file.write_all(value)) + .map_err(|e| StorageError::RocksDb(e.to_string()))?; + } + file.flush() .map_err(|e| StorageError::RocksDb(e.to_string()))?; - file.sync_all() + file.get_ref() + .sync_all() .map_err(|e| StorageError::RocksDb(e.to_string()))?; Ok(()) } @@ -518,6 +527,69 @@ fn write_u64(out: &mut Vec, value: u64) { mod tests { use super::*; + #[test] + fn pp_cache_index_shared_values_keep_v1_bytes_and_tombstones() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("current.idx"); + let value: Arc<[u8]> = Arc::from(&b"new"[..]); + write_pp_cache_index_atomic( + &path, + vec![ + ("z".to_string(), Arc::from(&b"old"[..])), + ("a".to_string(), Arc::from(&b""[..])), + ("z".to_string(), Arc::clone(&value)), + ], + ) + .unwrap(); + // Fixed format-v1 fixture: 64-byte header, two 24-byte entries, + // sorted blob "a" + empty tombstone + "z" + last duplicate "new". + let expected = concat!( + "52504b49505049445800000001000000", + "02000000000000004000000000000000", + "30000000000000007000000000000000", + "05000000000000000000000000000000", + "000000000000000001000000010000000000000000000000", + "010000000000000001000000020000000000000003000000", + "617a6e6577", + ); + assert_eq!(fs::read(&path).unwrap(), hex::decode(expected).unwrap()); + assert_eq!(Arc::strong_count(&value), 1); + let (index, _) = load_pp_cache_mmap_index(&path).unwrap(); + assert_eq!(index.lookup("a"), Some(PpCacheIndexLookup::Deleted)); + assert_eq!(index.get("z"), Some(&b"new"[..])); + } + + #[test] + #[ignore = "768MiB disk fixture; run alone under a 256MiB address-space limit"] + fn pp_cache_index_large_shared_payload_is_streamed() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("current.idx"); + let value: Arc<[u8]> = Arc::from(vec![0x5a; 8 * 1024 * 1024]); + let stats = write_pp_cache_index_atomic( + &path, + (0..96).map(|i| { + ( + format!("rsync://fixture.test/{i:04}.mft"), + Arc::clone(&value), + ) + }), + ) + .unwrap(); + assert_eq!(stats.new_entries, 96); + assert!(stats.file_bytes > 768 * 1024 * 1024); + assert_eq!(Arc::strong_count(&value), 1); + // Inspect the on-disk endpoints without mapping the 768MiB file into + // the deliberately limited process address space. + use std::io::{Read, Seek, SeekFrom}; + let mut file = File::open(&path).unwrap(); + let mut marker = [0; 8]; + file.read_exact(&mut marker).unwrap(); + assert_eq!(&marker, &MAGIC[..8]); + file.seek(SeekFrom::End(-8)).unwrap(); + file.read_exact(&mut marker).unwrap(); + assert_eq!(marker, [0x5a; 8]); + } + #[test] fn pp_cache_index_roundtrips_multiple_entries() { let dir = tempfile::tempdir().expect("tempdir"); diff --git a/src/sync/repo.rs b/src/sync/repo.rs index 57ad934..2141f73 100644 --- a/src/sync/repo.rs +++ b/src/sync/repo.rs @@ -134,11 +134,11 @@ pub fn sync_publication_point( if matches!(&err, RrdpSyncError::Rrdp(e) if e.is_cross_origin_violation()) { rfc_refs.push(RfcRef("RFC 9674 §3.2")); } - let warnings = vec![Warning::new(format!( - "RRDP failed; falling back to rsync: {err}" - )) - .with_rfc_refs(&rfc_refs) - .with_context(notification_uri)]; + let warnings = vec![ + Warning::new(format!("RRDP failed; falling back to rsync: {err}")) + .with_rfc_refs(&rfc_refs) + .with_context(notification_uri), + ]; let written = rsync_sync_into_current_store( store, rsync_base_uri, @@ -426,6 +426,15 @@ fn try_rrdp_sync( timing: Option<&TimingHandle>, download_log: Option<&DownloadLogHandle>, ) -> Result { + if let Some(outcome) = http_fetcher.frozen_sync_outcome(notification_uri) { + let written = outcome.map_err(RrdpSyncError::Fetch)?; + crate::sync::rrdp::hydrate_current_repo_index_from_rrdp_members( + store, + notification_uri, + current_repo_index, + )?; + return Ok(written); + } let notification_origin = RrdpOrigin::parse(notification_uri, RrdpResourceKind::Notification)?; let notification_xml = { let _step = timing @@ -528,6 +537,7 @@ fn try_rrdp_sync_with_retry( t.record_count("rrdp_retry_attempt_total", 1); } + let mut evaluation_span = crate::analysis::evaluation::sync_span("rrdp", notification_uri); match try_rrdp_sync( store, notification_uri, @@ -537,6 +547,9 @@ fn try_rrdp_sync_with_retry( download_log, ) { Ok(written) => { + if let Some(span) = evaluation_span.as_mut() { + span.set_success(); + } crate::progress_log::emit( "rrdp_sync_success", serde_json::json!({ @@ -599,6 +612,24 @@ fn rsync_sync_into_current_store( timing: Option<&TimingHandle>, download_log: Option<&DownloadLogHandle>, ) -> Result { + if let Some(outcome) = rsync_fetcher.frozen_sync_outcome(rsync_base_uri) { + let written = + outcome.map_err(|error| RepoSyncError::Rsync(RsyncFetchError::Fetch(error)))?; + if let Some(index) = current_repo_index { + let entries = store + .list_repository_view_entries_with_prefix(&rsync_fetcher.dedup_key(rsync_base_uri)) + .map_err(|error| RepoSyncError::Storage(error.to_string()))?; + index + .write() + .map_err(|_| { + RepoSyncError::Storage("current repo index lock poisoned".to_string()) + })? + .apply_repository_view_entries(&entries) + .map_err(RepoSyncError::Storage)?; + } + return Ok(written); + } + let mut evaluation_span = crate::analysis::evaluation::sync_span("rsync", rsync_base_uri); let started = std::time::Instant::now(); let sync_scope_uri = rsync_fetcher.dedup_key(rsync_base_uri); crate::progress_log::emit( @@ -726,6 +757,9 @@ fn rsync_sync_into_current_store( ); } + if let Some(span) = evaluation_span.as_mut() { + span.set_success(); + } Ok(object_count) } diff --git a/src/sync/rrdp.rs b/src/sync/rrdp.rs index 9859ef0..98d9c81 100644 --- a/src/sync/rrdp.rs +++ b/src/sync/rrdp.rs @@ -234,12 +234,18 @@ pub enum RrdpError { }, #[error("RRDP {resource} redirect limit exceeded ({max}) (RFC 9674 §3.2)")] - RedirectLimitExceeded { resource: RrdpResourceKind, max: usize }, + RedirectLimitExceeded { + resource: RrdpResourceKind, + max: usize, + }, } impl RrdpError { pub fn is_cross_origin_violation(&self) -> bool { - matches!(self, Self::CrossOriginReference { .. } | Self::CrossOriginRedirect { .. }) + matches!( + self, + Self::CrossOriginReference { .. } | Self::CrossOriginRedirect { .. } + ) } } @@ -285,10 +291,12 @@ impl RrdpOrigin { resource, detail: "host is missing".to_string(), })?; - let port = url.port_or_known_default().ok_or_else(|| RrdpError::InvalidRrdpUri { - resource, - detail: "port is missing or unknown".to_string(), - })?; + let port = url + .port_or_known_default() + .ok_or_else(|| RrdpError::InvalidRrdpUri { + resource, + detail: "port is missing or unknown".to_string(), + })?; Ok(Self { scheme: url.scheme().to_ascii_lowercase(), host: host.to_ascii_lowercase(), @@ -321,6 +329,11 @@ pub enum RrdpFetchError { pub type RrdpSyncResult = Result; pub trait Fetcher: Send + Sync { + /// Explicit frozen-input experiment only; no protocol fetch/apply is needed. + fn frozen_sync_outcome(&self, _notification_uri: &str) -> Option> { + None + } + fn fetch(&self, uri: &str) -> Result, String>; fn fetch_to_writer(&self, uri: &str, out: &mut dyn Write) -> Result { @@ -349,7 +362,8 @@ pub trait Fetcher: Send + Sync { _notification_origin: &RrdpOrigin, out: &mut dyn Write, ) -> Result { - self.fetch_to_writer(uri, out).map_err(RrdpFetchError::Fetch) + self.fetch_to_writer(uri, out) + .map_err(RrdpFetchError::Fetch) } } @@ -747,7 +761,10 @@ fn sync_from_notification_snapshot_inner( Ok(origin) => origin, Err(e) => { if let Some(t) = timing.as_ref() { - t.record_count("rrdp_rejected_cross_origin_total", e.is_cross_origin_violation() as u64); + t.record_count( + "rrdp_rejected_cross_origin_total", + e.is_cross_origin_violation() as u64, + ); } return Err(e.into()); } @@ -918,7 +935,10 @@ fn sync_from_notification_inner( Ok(origin) => origin, Err(e) => { if let Some(t) = timing.as_ref() { - t.record_count("rrdp_rejected_cross_origin_total", e.is_cross_origin_violation() as u64); + t.record_count( + "rrdp_rejected_cross_origin_total", + e.is_cross_origin_violation() as u64, + ); } return Err(e.into()); } @@ -948,6 +968,7 @@ fn sync_from_notification_inner( if let Some(s) = same_session_state { if s.serial == notif.serial { + crate::analysis::evaluation::record_rrdp_mode(notification_uri, "no_update"); let _hydrate_step = timing .as_ref() .map(|t| t.span_rrdp_repo_step(notification_uri, "hydrate_current_index")); @@ -1118,6 +1139,7 @@ fn sync_from_notification_inner( hydrated as u64, ); } + crate::analysis::evaluation::record_rrdp_mode(notification_uri, "delta"); return Ok(applied_total); } } @@ -1126,6 +1148,7 @@ fn sync_from_notification_inner( } // Snapshot fallback (RFC 8182 §3.4.3). + crate::analysis::evaluation::record_rrdp_mode(notification_uri, "snapshot"); let _fetch_step = timing .as_ref() .map(|t| t.span_rrdp_repo_step(notification_uri, "fetch_snapshot")); @@ -1214,7 +1237,7 @@ fn sync_from_notification_inner( Ok(published) } -fn hydrate_current_repo_index_from_rrdp_members( +pub(crate) fn hydrate_current_repo_index_from_rrdp_members( store: &RocksStore, notification_uri: &str, current_repo_index: Option<&CurrentRepoIndexHandle>, diff --git a/src/validation/tree_runner.rs b/src/validation/tree_runner.rs index 8a92701..c26240b 100644 --- a/src/validation/tree_runner.rs +++ b/src/validation/tree_runner.rs @@ -3904,6 +3904,30 @@ fn audit_detail_from_vcir_status( } } +// A manifest hash lock alone is not stage2 validation. Keep the same default +// status in fresh audit and persisted artifacts used by PP/fallback reuse. +fn snapshot_file_initial_audit_result(file: &PackFile) -> (AuditObjectResult, Option) { + if !file.rsync_uri.ends_with(".crl") { + return ( + AuditObjectResult::Skipped, + Some("skipped: not processed in stage2".to_string()), + ); + } + let ok = file + .bytes() + .ok() + .and_then(|bytes| crate::data_model::crl::RpkixCrl::decode_der(bytes).ok()) + .is_some(); + if ok { + (AuditObjectResult::Ok, None) + } else { + ( + AuditObjectResult::Error, + Some("CRL decode failed".to_string()), + ) + } +} + fn build_publication_point_audit_from_snapshot( ca: &CaInstanceHandle, source: PublicationPointSource, @@ -3916,49 +3940,20 @@ fn build_publication_point_audit_from_snapshot( objects: &crate::validation::objects::ObjectsOutput, child_audits: &[ObjectAuditEntry], ) -> PublicationPointAudit { - use crate::data_model::crl::RpkixCrl; use std::collections::HashMap; let locked_files = &pack.files; let mut audit_by_uri: HashMap = HashMap::new(); for f in locked_files { + let (result, detail) = snapshot_file_initial_audit_result(f); audit_by_uri.insert( f.rsync_uri.clone(), ObjectAuditEntry { rsync_uri: f.rsync_uri.clone(), sha256_hex: sha256_hex_from_32(&f.sha256), kind: kind_from_rsync_uri(&f.rsync_uri), - result: AuditObjectResult::Skipped, - detail: Some("skipped: not processed in stage2".to_string()), - }, - ); - } - - for f in locked_files { - if !f.rsync_uri.ends_with(".crl") { - continue; - } - let ok = f - .bytes() - .ok() - .and_then(|bytes| RpkixCrl::decode_der(bytes).ok()) - .is_some(); - audit_by_uri.insert( - f.rsync_uri.clone(), - ObjectAuditEntry { - rsync_uri: f.rsync_uri.clone(), - sha256_hex: sha256_hex_from_32(&f.sha256), - kind: AuditObjectKind::Crl, - result: if ok { - AuditObjectResult::Ok - } else { - AuditObjectResult::Error - }, - detail: if ok { - None - } else { - Some("CRL decode failed".to_string()) - }, + result, + detail, }, ); } @@ -6111,12 +6106,12 @@ fn build_vcir_related_artifacts( for file in &pack.files { let audit_entry = audit_by_uri.get(file.rsync_uri.as_str()).copied(); - let result = audit_entry - .map(|entry| entry.result.clone()) - .unwrap_or(AuditObjectResult::Ok); + let (result, detail) = audit_entry + .map(|entry| (entry.result.clone(), entry.detail.clone())) + .unwrap_or_else(|| snapshot_file_initial_audit_result(file)); let validation_status = audit_result_to_vcir_status(&result); let reject_reason = if validation_status == VcirArtifactValidationStatus::Rejected { - audit_entry.and_then(|entry| entry.detail.clone()) + detail } else { None }; diff --git a/src/validation/tree_runner/tests.rs b/src/validation/tree_runner/tests.rs index af343cd..91f487c 100644 --- a/src/validation/tree_runner/tests.rs +++ b/src/validation/tree_runner/tests.rs @@ -1391,6 +1391,10 @@ fn build_vcir_related_artifacts_classifies_snapshot_files_and_audit_statuses() { "rsync://example.test/repo/issuer/extra.bin", vec![9u8], ), + PackFile::from_bytes_compute_sha256( + "rsync://example.test/repo/issuer/broken.crl", + vec![0u8], + ), ], }; let ca = CaInstanceHandle { @@ -1472,6 +1476,83 @@ fn build_vcir_related_artifacts_classifies_snapshot_files_and_audit_statuses() { assert!(artifacts.iter().any(|artifact| artifact.uri.as_deref() == Some("rsync://example.test/repo/issuer/extra.bin") && artifact.artifact_kind == VcirArtifactKind::Other)); + let fresh = build_publication_point_audit_from_snapshot( + &ca, + PublicationPointSource::Fresh, + None, + None, + None, + None, + &pack, + &[], + &objects, + &[], + ); + for file in &pack.files { + let entry = fresh + .objects + .iter() + .find(|entry| entry.rsync_uri == file.rsync_uri) + .unwrap(); + let artifact = artifacts + .iter() + .find(|artifact| artifact.uri.as_deref() == Some(file.rsync_uri.as_str())) + .unwrap(); + assert_eq!( + audit_result_from_vcir_status(artifact.validation_status), + entry.result, + "cache must preserve fresh audit status for {}", + file.rsync_uri + ); + if entry.result == AuditObjectResult::Error { + assert_eq!(artifact.reject_reason, entry.detail); + } + } + let now = time::OffsetDateTime::now_utc(); + let mut vcir = sample_vcir_for_projection(now, &sha256_hex(b"child-cert")); + vcir.related_artifacts = artifacts.clone(); + let projection = PublicationPointCacheProjection::from_vcir_with_context( + &vcir, + ca.publication_point_rsync_uri.clone(), + ca.ca_certificate_rsync_uri.clone(), + [0x11; 32], + [0x22; 32], + [0x33; 32], + [0x44; 32], + [0x55; 32], + ) + .expect("build projection with skipped artifacts"); + let encoded = serde_json::to_vec(&projection).unwrap(); + let projection: PublicationPointCacheProjection = serde_json::from_slice(&encoded).unwrap(); + let restored = build_publication_point_audit_from_publication_point_cache_projection( + &ca, + PublicationPointSource::PublicationPointCache, + None, + None, + None, + None, + &projection, + now, + &[], + &empty_objects_output(), + &[], + ); + for entry in &fresh.objects { + let cached = restored + .objects + .iter() + .find(|cached| cached.rsync_uri == entry.rsync_uri) + .unwrap(); + assert_eq!( + cached.result, entry.result, + "restored status for {}", + entry.rsync_uri + ); + assert_eq!(cached.sha256_hex, entry.sha256_hex); + if entry.result == AuditObjectResult::Error { + assert_eq!(cached.detail, entry.detail); + } + } assert!( !artifacts .iter()