20261117 固化13步自然回放、数据哈希与第二版性能基线

This commit is contained in:
2026-11-17 16:59:57 +08:00
parent 56db3cc6e7
commit 5c0ec3a04b
17 changed files with 7044 additions and 5 deletions

View File

@@ -0,0 +1,124 @@
# 标准性能测试:13步自然串行回放
#188收尾标准为同一109 RRDP仓库、8持续缺口、五个真实TAL/TA,1 snapshot+12个增量逻辑验证时点。
原始逻辑时间相隔300秒,回放紧凑执行,每步完成自身T1/T2及统计后进入下一步。
每策略使用自己的连续state/mirror,不恢复固定seed,不清OS缓存,不加实现层稳定化,不启用prefetch。
实现生产版本:`56db3cc6e7f220a7213985269bda9d712c7a0bcf`,源文件SHA见
[baseline-v2.json](configs/baseline-v2.json),与M7实测第二版全部生产源文件一致。
实测ELF SHA256:`67f7756f95e1aaad537be5a1f2a53e46563a0b958f15c1adc10cb8207267809c`。
后续M15诊断、M20减写候选不在该生产版本中;恢复patch见specs本迭代的`archived-candidates/`。
## 本机保存位置与数据契约
- 数据本体:`/home/yuyr/dev/rpki_dev/replay_data/capture03-13step-v1`,不在Git仓库内。
- 冻结工具:`/home/yuyr/dev/rpki_dev/replay_tools/v2-67f7756f/bin`,不随`target`清理。
- Git清单:[capture03-manifest.json](configs/capture03-manifest.json),与数据根的`bundle-manifest.json`完全一致。
- 清单SHA256:`238c17055443ba14dfdc2c0930413b16fc1963c75c0990e0823ff8589f697702`。
- 原始输入632份,1,704,765,956字节:109 snapshot、253 delta、235 notification内容版本、25 rsync文件、5 TA及5 TAL。
- 附加元数据保留原始contract/capture/registry/closure、13 epochs、被选中的observations/events和scope。
文件逐项相对路径、SHA、字节数、对应step和每步HTTP/rsync工作量均在清单中。
这是**实际消费的输入子集**:不含录制后续未使用的snapshot、无关历史delta、完整视图或RP运行DB/报告。
原XML/DER/TAL及metadata不改字节。原archive完整闭包报告仅作历史来源;不能拿它声称精简包具备全量录制闭包。
`verify_bundle_chain.py`独立重放这13点所需的snapshot/delta,比较原始view摘要,并核验最后一步rsync文件。
`verify_bundle_server.py`逐epoch通过实际HTTP/TLS读取全部选中实体,启用原域名SNI/CA核验,并实际运行只读rsync。
旧server预检所有可用引用,缺少未使用snapshot也会拒绝启动。新模式仅在scope、manifest和其SHA均显式给定时
供给选中实体;缺少必需文件或hash不符硬失败,额外请求返回404并使控制器工作量审计失败,没有上游补取。
完整archive模式保持原来的严格预检。旧#187预跑/正式和所有186历史原件保留,未做清理。
## 校验与运行
依赖Linux、Python3.11+、openssl、rsync;真正测量还需root、iproute2、systemd及cgroup v2。
下列命令从实现仓库根运行。`DATASET`和`TOOLS`可搬到其他路径,修改为实际位置。
```bash
DATASET=/home/yuyr/dev/rpki_dev/replay_data/capture03-13step-v1
TOOLS=/home/yuyr/dev/rpki_dev/replay_tools/v2-67f7756f/bin
python3 scripts/experiments/reuse_eval/replay_bundle.py verify \
--root "$DATASET" --manifest "$DATASET/bundle-manifest.json" \
--expected-sha256 238c17055443ba14dfdc2c0930413b16fc1963c75c0990e0823ff8589f697702
python3 scripts/experiments/reuse_eval/verify_bundle_chain.py \
--root "$DATASET" --manifest "$DATASET/bundle-manifest.json" \
--expected-sha256 238c17055443ba14dfdc2c0930413b16fc1963c75c0990e0823ff8589f697702
python3 scripts/experiments/reuse_eval/natural_replay.py --check-only \
--dataset "$DATASET" --binary-dir "$TOOLS" --out /data/NEW_UNIQUE_RUN
```
获得实验窗口后,在186将同一数据包和代码放到持久目录,再执行:
```bash
python3 scripts/experiments/reuse_eval/natural_replay.py \
--dataset "$DATASET" --binary-dir "$TOOLS" --out /data/NEW_UNIQUE_RUN
# 单独测PP完整13步:在上面命令后加 --profiles pp
```
默认配置[natural13.json](configs/natural13.json)覆盖baseline/signature/object/pp/hybrid,策略依次执行。
单策略可选;多策略必须baseline先执行、不得重复。输出根必须全新且位于数据包之外。
默认检查主机身份为186;换机器需明确修改配置并建立新硬件基线,不直接与186算代码收益。
RP绑CPU1–3、server绑CPU0,3+3workers,5GiB cgroup;不自动操作任何业务服务。
运行前需Panda已停止且无竞争RP、足够空闲inode和磁盘;默认最低150GiB,运行中每步再检查。
Panda186应保持inactive/disabled,脚本**永不重新启动**它。禁止触及231的relay。
中断保留失败现场;该入口不将半步结果拼成成功,也不自动删除/覆盖旧输出。
新候选构建时使用独立工具目录,并显式给`--expected-binary-sha256 <candidate SHA>`。
归档git commit、production source SHA、Cargo.lock、features/toolchain及四工具SHA。
复现旧依赖可将[baseline-v2.Cargo.lock](configs/baseline-v2.Cargo.lock)复制为根Cargo.lock后使用`cargo build --release --locked`;
重新构建的ELF不保证逐字节等于历史ELF,不应沿用其SHA。
控制器每步检查工具和脚本未变;完整输入SHA复核在测量前进行。
## 七指标与证明
1. Repository sync:原生RRDP/rsync执行区间并集,包含网络、解析、应用、索引及失败尝试;不是纯下载。
2. RP validation:独立T2冻结输入引擎wall,含cache加载、验证/派生、必要持久化及后台写drain。
3. Update→payload:controller trigger至CCR同目录原子rename,不声称fsync持久性。
4. Cache hits:各启用层实际hits/queries,关闭的层不记作0%命中。
5. CPU:整个T1 RP cgroup及子进程核秒,server排除在外。
6. Peak RSS:GNU time wait4最大RSS,和包含文件页缓存的cgroup MemoryPeak区分。
7. Cache size:该策略必须保留的已验证投影序列化字节和sidecar;排除公共仓库原始内容与未启用投影。
逐步保存summary、配置/工具/脚本hash、契约、传输/请求日志、CIR/CCR比较、T2等价、计数及cache-size。
多策略以同一步baseline做完整CIR/CCR比较。单策略首项的自比较只提供结构/摘要,不能冒作跨版本完整等价;
另以[expected-outputs.json](configs/expected-outputs.json)核验历史CCR规范状态摘要、CIR census和payload数量,
T2核验本步完整输入/输出、fallback绑定、hit/miss、前态hash与后台drain。
历史CIR census不是完整object map相等的替代证明。
与旧测量对齐,T1之后仍做独立T2、exact cache accounting,下一步T1前复制完整前态。
这些计时外操作会触碰文件/预热OS缓存;不得删掉它们后仍称同协议,也不能把T2加到/扣出T1推导阶段时间。
没有额外5分钟墙钟等待;也没有固定seed恢复、drop_caches或新诊断机制。
## 当前性能基线的边界
[baseline-v2.json](configs/baseline-v2.json)保存35行真实逐步七指标、源码/ELF、机器和来源:
M11 PP完整13步、M9五策略各4步、M24 PP自然1+1,三者分组。
PP M11 snapshot为107.255s/187.333核秒,12增量平均15.885s/23.597核秒,
正常10步平均16.559s/23.916核秒(精确值以JSON为准)。
M24 snapshot121.256s、首delta40.367s;同一代码仍有wall波动,不能把单次差异当稳定代码收益。
snapshot单列;正常steps1–10与steps11/12的单PP fallback分开,最后一步也有RRDP→rsync。
13个不同逻辑工作负载不是13次独立重复,不据此报告置信度/P5/P95稳定性。
固定seed/冷OS缓存/M15诊断ELF/M20减写数据不得混算进自然v2基线。
本次精简包/新入口做了数据链及服务校验,**没有重新计时跑RP端到端**;历史数据绑定的是相同生产源码和
旧全archive服务控制器。后续首轮新入口实测应独立命名,先核对工作量与测量协议,再建立新入口基线。
## 采集与重新获取
完整采集代码`capture.py/campaign.py/rrdp.py/common.py`、RP录制开关及原server/namespace工具已在仓库。
[capture1h.example.json](configs/capture1h.example.json)保留1小时、60秒notification、300秒逻辑步配置;
路径相对调用CWD,五个TAL放`inputs/`。新录制必须新根,bootstrap闭包/缺口单独声明;不自动启动。
包里的原始`archive/capture.json`保留实际采集命令/配置/事件来源,hash由清单绑定。
若本机数据包丢失,在获准读取186原件后,可使用`fetch_bundle.py`按Git清单并行压缩rsync取回:
```bash
mkdir -p "$DATASET"
cp scripts/experiments/reuse_eval/configs/capture03-manifest.json "$DATASET/bundle-manifest.json"
python3 scripts/experiments/reuse_eval/fetch_bundle.py \
--manifest "$DATASET/bundle-manifest.json" --root "$DATASET" \
--expected-sha256 238c17055443ba14dfdc2c0930413b16fc1963c75c0990e0823ff8589f697702 \
--host root@47.251.66.186 --identity /path/to/key --jobs 8
```
fetch只读清单所指源文件,不取整个19GB录制/实验目录,已有不同内容拒绝覆盖;完成后逐文件SHA复核。
`replay_bundle.py export/stream/extract`也提供从原scope和实际消费inventory创建/流式保存新精简包的入口。

View File

@@ -1,5 +1,9 @@
# #187 原始传输录制与五策略回放评估
2026-11-17标准性能框架已固化为[13步自然串行回放](NATURAL_REPLAY.md):
新入口`natural_replay.py`,代码/配置/数据hash/当前v2七指标基线在仓库,实际消费的约1.7GB数据单独保存在本机。
下文`sequence_matrix.py`等为历史#187入口,包含旧Panda恢复语义;后续标准实验使用新入口,Panda186保持停止/禁用。
实现采集、归档、闭包核验、固定 epoch HTTPS/rsync 服务、缓存归因、完整序列控制器和单轮正式七指标导出。
186 上 v18 预跑与 v20 第一轮正式测试均已完成65/65,后者七指标已逐项重算并与预跑校验。
2026-11-12用户决定收尾本次交付:后续两轮正式测试暂不执行,不启动新录制或回放;186的原始录制、预跑、正式结果、state及历史失败现场全部保留,不清理或改写。

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,44 @@
{
"run_root": "recordings/new-capture",
"archive_root": "recordings/new-capture/archive/capture_01",
"binary": "target/release/rpki",
"tals": [
"inputs/afrinic.tal",
"inputs/apnic.tal",
"inputs/arin.tal",
"inputs/lacnic.tal",
"inputs/ripe.tal"
],
"duration_secs": 3600,
"poll_secs": 60,
"step_secs": 300,
"workers": 4,
"max_repositories": 1000,
"bootstrap_attempts": 3,
"rp_timeout_secs": 1800,
"bootstrap_gap_policy": "record-with-gaps",
"rp_args": [
"--parallel-max-repo-sync-workers-global",
"4",
"--parallel-phase2-object-workers",
"4",
"--rsync-scope",
"module-root",
"--max-ca-depth",
"32",
"--http-timeout-secs",
"30",
"--rsync-timeout-secs",
"30"
],
"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
}
}

View File

@@ -0,0 +1,500 @@
{
"schema": "rpki-natural13-expected-outputs-v1",
"source": "#188 M11 production v2 PP13; CCR canonical state + CIR census, not historical full CIR map",
"steps": [
{
"step": 0,
"counts": {
"aspas": 4046,
"publication_points": 56141,
"vrps": 1046587
},
"cir_census": {
"objectCount": 572295,
"rejectCount": 110,
"rejectListSha256": "9a39780db69ec3ff5db3f62d2d6a1c0fe21a6090d41eba786a418cfd053312bb",
"talCount": 5,
"trustAnchorCount": 5,
"validationTime": "2026-11-09 9:54:44.0 +00:00:00"
},
"ccr_states": {
"mfts": [
true,
"fa0072c4eae6cb8592c253480dc0ca4a63734a2595838330dd29d3055cfc1c86"
],
"vrps": [
true,
"30b279c2cc2530ceecd927782cc2687e2a923e6eb0e89473fb8e1c25bbb45162"
],
"vaps": [
true,
"5c62a179024b9ce139bb8b9b3d3f5cf3417949e108124756313605c3642d29bf"
],
"tas": [
true,
"b9ba66b2bcd54e4812249f60ed2de9357670cc48ff848f1bc35f5986703de71f"
],
"rks": [
true,
"197880e4611642b27be2becbd56f047b531a7cd53a4f97dcae3af4ff8553c7f4"
]
}
},
{
"step": 1,
"counts": {
"aspas": 4046,
"publication_points": 56141,
"vrps": 1046591
},
"cir_census": {
"objectCount": 575917,
"rejectCount": 111,
"rejectListSha256": "8494715f65cf1045188b92674991c942f6379bdfdacb7d8bc5cc860c8dc1550e",
"talCount": 5,
"trustAnchorCount": 5,
"validationTime": "2026-11-09 9:59:44.0 +00:00:00"
},
"ccr_states": {
"mfts": [
true,
"ea5dd90e1c0f183f917f4f31664e4761831012e4c08cb27ea2e00097736ac416"
],
"vrps": [
true,
"b74148e909c1735f117839bf3823e4cba22a080052d4895f6df5c24e6a75ca3c"
],
"vaps": [
true,
"9532ad356b9ba4b08375ca74916479fc7721d4de521e490d354f79102e77c91b"
],
"tas": [
true,
"b9ba66b2bcd54e4812249f60ed2de9357670cc48ff848f1bc35f5986703de71f"
],
"rks": [
true,
"197880e4611642b27be2becbd56f047b531a7cd53a4f97dcae3af4ff8553c7f4"
]
}
},
{
"step": 2,
"counts": {
"aspas": 4045,
"publication_points": 56141,
"vrps": 1046482
},
"cir_census": {
"objectCount": 595617,
"rejectCount": 110,
"rejectListSha256": "df02a86ba3896ed69816624a2d60061b1cea2cc72cae415d9028c19d18cba262",
"talCount": 5,
"trustAnchorCount": 5,
"validationTime": "2026-11-09 10:04:44.0 +00:00:00"
},
"ccr_states": {
"mfts": [
true,
"d4b11f96c964cee3f5595c01012fbb42312d62454fc513c6bea6f6b220df06f3"
],
"vrps": [
true,
"c7795cc490d6c9ce13f552f65de24d0b42e13e09e5b6fdd19912e79ff0f2da20"
],
"vaps": [
true,
"efcb0d636db6af2f75e33465b71b1f574abdf8b858196af02821a755753e9529"
],
"tas": [
true,
"b9ba66b2bcd54e4812249f60ed2de9357670cc48ff848f1bc35f5986703de71f"
],
"rks": [
true,
"197880e4611642b27be2becbd56f047b531a7cd53a4f97dcae3af4ff8553c7f4"
]
}
},
{
"step": 3,
"counts": {
"aspas": 4045,
"publication_points": 56141,
"vrps": 1046483
},
"cir_census": {
"objectCount": 575924,
"rejectCount": 110,
"rejectListSha256": "df02a86ba3896ed69816624a2d60061b1cea2cc72cae415d9028c19d18cba262",
"talCount": 5,
"trustAnchorCount": 5,
"validationTime": "2026-11-09 10:09:44.0 +00:00:00"
},
"ccr_states": {
"mfts": [
true,
"49a691bf33f6233091db39b215404db113e3633b92120754403cdd7aeeb929d7"
],
"vrps": [
true,
"a3bfc10128bca6d17ccaedeb9f821605a5f1a0c502efd5d7d7bcdef3f1815b39"
],
"vaps": [
true,
"efcb0d636db6af2f75e33465b71b1f574abdf8b858196af02821a755753e9529"
],
"tas": [
true,
"b9ba66b2bcd54e4812249f60ed2de9357670cc48ff848f1bc35f5986703de71f"
],
"rks": [
true,
"197880e4611642b27be2becbd56f047b531a7cd53a4f97dcae3af4ff8553c7f4"
]
}
},
{
"step": 4,
"counts": {
"aspas": 4045,
"publication_points": 56141,
"vrps": 1046480
},
"cir_census": {
"objectCount": 575911,
"rejectCount": 110,
"rejectListSha256": "df02a86ba3896ed69816624a2d60061b1cea2cc72cae415d9028c19d18cba262",
"talCount": 5,
"trustAnchorCount": 5,
"validationTime": "2026-11-09 10:14:44.0 +00:00:00"
},
"ccr_states": {
"mfts": [
true,
"89dc575f44dd415126f46b05ef73d1bfc8be7b290f9bd308b35a642bc253bb00"
],
"vrps": [
true,
"4c8aa3451ddc2d051c454d479953d9a57686b8097ba43472df8494c04ef0c36f"
],
"vaps": [
true,
"efcb0d636db6af2f75e33465b71b1f574abdf8b858196af02821a755753e9529"
],
"tas": [
true,
"b9ba66b2bcd54e4812249f60ed2de9357670cc48ff848f1bc35f5986703de71f"
],
"rks": [
true,
"197880e4611642b27be2becbd56f047b531a7cd53a4f97dcae3af4ff8553c7f4"
]
}
},
{
"step": 5,
"counts": {
"aspas": 4045,
"publication_points": 56141,
"vrps": 1046481
},
"cir_census": {
"objectCount": 572283,
"rejectCount": 110,
"rejectListSha256": "df02a86ba3896ed69816624a2d60061b1cea2cc72cae415d9028c19d18cba262",
"talCount": 5,
"trustAnchorCount": 5,
"validationTime": "2026-11-09 10:19:44.0 +00:00:00"
},
"ccr_states": {
"mfts": [
true,
"f3755e61c17ee91c650347a962d28d7ce0fb33adf53b2f4fc6ce9510e5c1916e"
],
"vrps": [
true,
"68f382b2370a0e8d3edd182472fbe2b00e348baf27b0eb7693ac9a2506a14197"
],
"vaps": [
true,
"efcb0d636db6af2f75e33465b71b1f574abdf8b858196af02821a755753e9529"
],
"tas": [
true,
"b9ba66b2bcd54e4812249f60ed2de9357670cc48ff848f1bc35f5986703de71f"
],
"rks": [
true,
"197880e4611642b27be2becbd56f047b531a7cd53a4f97dcae3af4ff8553c7f4"
]
}
},
{
"step": 6,
"counts": {
"aspas": 4045,
"publication_points": 56141,
"vrps": 1046483
},
"cir_census": {
"objectCount": 599262,
"rejectCount": 111,
"rejectListSha256": "39ada219712bc395af59fc4fda3e6db14da6fa95dff74331c0f3f13c47bd3aa5",
"talCount": 5,
"trustAnchorCount": 5,
"validationTime": "2026-11-09 10:24:44.0 +00:00:00"
},
"ccr_states": {
"mfts": [
true,
"22d26ba27344b5d5d5fffb3fc3442faa499035ed444684b8d112239642ad1d7b"
],
"vrps": [
true,
"212ad14b6a6a51f475da12f69f698ceedf4049e0d78ac9adbba7ff632a07ae24"
],
"vaps": [
true,
"efcb0d636db6af2f75e33465b71b1f574abdf8b858196af02821a755753e9529"
],
"tas": [
true,
"b9ba66b2bcd54e4812249f60ed2de9357670cc48ff848f1bc35f5986703de71f"
],
"rks": [
true,
"197880e4611642b27be2becbd56f047b531a7cd53a4f97dcae3af4ff8553c7f4"
]
}
},
{
"step": 7,
"counts": {
"aspas": 4045,
"publication_points": 56141,
"vrps": 1046483
},
"cir_census": {
"objectCount": 572431,
"rejectCount": 111,
"rejectListSha256": "39ada219712bc395af59fc4fda3e6db14da6fa95dff74331c0f3f13c47bd3aa5",
"talCount": 5,
"trustAnchorCount": 5,
"validationTime": "2026-11-09 10:29:44.0 +00:00:00"
},
"ccr_states": {
"mfts": [
true,
"bf5ea68cc3da6af3a4a5e3cef1a3460fdb20531348614dafe47ee48a4d1f14af"
],
"vrps": [
true,
"212ad14b6a6a51f475da12f69f698ceedf4049e0d78ac9adbba7ff632a07ae24"
],
"vaps": [
true,
"efcb0d636db6af2f75e33465b71b1f574abdf8b858196af02821a755753e9529"
],
"tas": [
true,
"b9ba66b2bcd54e4812249f60ed2de9357670cc48ff848f1bc35f5986703de71f"
],
"rks": [
true,
"197880e4611642b27be2becbd56f047b531a7cd53a4f97dcae3af4ff8553c7f4"
]
}
},
{
"step": 8,
"counts": {
"aspas": 4045,
"publication_points": 56141,
"vrps": 1046483
},
"cir_census": {
"objectCount": 575906,
"rejectCount": 111,
"rejectListSha256": "39ada219712bc395af59fc4fda3e6db14da6fa95dff74331c0f3f13c47bd3aa5",
"talCount": 5,
"trustAnchorCount": 5,
"validationTime": "2026-11-09 10:34:44.0 +00:00:00"
},
"ccr_states": {
"mfts": [
true,
"c85ee48d7d60ae80ac25f3b4109c2bec2c82df68d0744f018f171ae25b8d578a"
],
"vrps": [
true,
"b0a536ec7a53a90d2dec960de578e1d721bbd50b672a85c96e63517dc76c4576"
],
"vaps": [
true,
"efcb0d636db6af2f75e33465b71b1f574abdf8b858196af02821a755753e9529"
],
"tas": [
true,
"b9ba66b2bcd54e4812249f60ed2de9357670cc48ff848f1bc35f5986703de71f"
],
"rks": [
true,
"197880e4611642b27be2becbd56f047b531a7cd53a4f97dcae3af4ff8553c7f4"
]
}
},
{
"step": 9,
"counts": {
"aspas": 4045,
"publication_points": 56141,
"vrps": 1046482
},
"cir_census": {
"objectCount": 575928,
"rejectCount": 111,
"rejectListSha256": "39ada219712bc395af59fc4fda3e6db14da6fa95dff74331c0f3f13c47bd3aa5",
"talCount": 5,
"trustAnchorCount": 5,
"validationTime": "2026-11-09 10:39:44.0 +00:00:00"
},
"ccr_states": {
"mfts": [
true,
"ecf4375e53da4e536b4277f43ce0577984210eaed627f1589aa33fb57846cfa3"
],
"vrps": [
true,
"440d2bd6b6f4290089efe565f26270f457630eb829d1f43a48f43b0b1f775b7f"
],
"vaps": [
true,
"efcb0d636db6af2f75e33465b71b1f574abdf8b858196af02821a755753e9529"
],
"tas": [
true,
"b9ba66b2bcd54e4812249f60ed2de9357670cc48ff848f1bc35f5986703de71f"
],
"rks": [
true,
"197880e4611642b27be2becbd56f047b531a7cd53a4f97dcae3af4ff8553c7f4"
]
}
},
{
"step": 10,
"counts": {
"aspas": 4045,
"publication_points": 56142,
"vrps": 1046481
},
"cir_census": {
"objectCount": 595624,
"rejectCount": 111,
"rejectListSha256": "39ada219712bc395af59fc4fda3e6db14da6fa95dff74331c0f3f13c47bd3aa5",
"talCount": 5,
"trustAnchorCount": 5,
"validationTime": "2026-11-09 10:44:44.0 +00:00:00"
},
"ccr_states": {
"mfts": [
true,
"d823978f1f4c5fcef50f02b8acf4030e5755b7a36a75ddf3d51548c4336306eb"
],
"vrps": [
true,
"fbb296a9e6577e4bc968ee58a20a53eeb84d06c8b36b51e47b672bd43153f105"
],
"vaps": [
true,
"efcb0d636db6af2f75e33465b71b1f574abdf8b858196af02821a755753e9529"
],
"tas": [
true,
"b9ba66b2bcd54e4812249f60ed2de9357670cc48ff848f1bc35f5986703de71f"
],
"rks": [
true,
"197880e4611642b27be2becbd56f047b531a7cd53a4f97dcae3af4ff8553c7f4"
]
}
},
{
"step": 11,
"counts": {
"aspas": 4045,
"publication_points": 56142,
"vrps": 1046481
},
"cir_census": {
"objectCount": 575914,
"rejectCount": 112,
"rejectListSha256": "0e7c2315f15c1a3274c3bc2b228db6daa89b464f9a2fd93648839745862bef0f",
"talCount": 5,
"trustAnchorCount": 5,
"validationTime": "2026-11-09 10:49:44.0 +00:00:00"
},
"ccr_states": {
"mfts": [
true,
"1b86b76f11962a110f85ab1418e39c5640e525e0550054b4d76025e714d23580"
],
"vrps": [
true,
"d22823a8eeb5eb1de7bbd3a96358914e57205d12fe7f0599a97fdf06adece100"
],
"vaps": [
true,
"efcb0d636db6af2f75e33465b71b1f574abdf8b858196af02821a755753e9529"
],
"tas": [
true,
"b9ba66b2bcd54e4812249f60ed2de9357670cc48ff848f1bc35f5986703de71f"
],
"rks": [
true,
"197880e4611642b27be2becbd56f047b531a7cd53a4f97dcae3af4ff8553c7f4"
]
}
},
{
"step": 12,
"counts": {
"aspas": 4045,
"publication_points": 56142,
"vrps": 1046481
},
"cir_census": {
"objectCount": 575928,
"rejectCount": 112,
"rejectListSha256": "0e7c2315f15c1a3274c3bc2b228db6daa89b464f9a2fd93648839745862bef0f",
"talCount": 5,
"trustAnchorCount": 5,
"validationTime": "2026-11-09 10:54:44.0 +00:00:00"
},
"ccr_states": {
"mfts": [
true,
"acfc894476ccdaf82a315c278fd83018ee2db5327520ea6dd193e161892f9c26"
],
"vrps": [
true,
"37c33a79bf689b15cf2de552098156f6662bc9071c66a8d48aed0d9a40d37295"
],
"vaps": [
true,
"efcb0d636db6af2f75e33465b71b1f574abdf8b858196af02821a755753e9529"
],
"tas": [
true,
"b9ba66b2bcd54e4812249f60ed2de9357670cc48ff848f1bc35f5986703de71f"
],
"rks": [
true,
"197880e4611642b27be2becbd56f047b531a7cd53a4f97dcae3af4ff8553c7f4"
]
}
}
]
}

View File

@@ -0,0 +1,32 @@
{
"schema": "rpki-natural13-config-v1",
"protocol": "natural-serial-13-v1",
"expected_host": "iZrj9bs1xzk2i95si3ghnlZ",
"expected_scope_sha256": "2ecc5dfc2200c30762ea1854b65a0863f3ffbd1a90c5cc713ad9dbc43e3ee79a",
"expected_bundle_sha256": "238c17055443ba14dfdc2c0930413b16fc1963c75c0990e0823ff8589f697702",
"expected_binary_sha256": "67f7756f95e1aaad537be5a1f2a53e46563a0b958f15c1adc10cb8207267809c",
"expected_outputs": "expected-outputs.json",
"profile_order": [
"baseline",
"signature",
"object",
"pp",
"hybrid"
],
"formal_metrics": true,
"minimum_free_gib": 150,
"run_timeout_secs": 1800,
"policy_notes": {
"rp_cpus": "1-3",
"server_cpus": "0",
"rp_memory_max": "5G",
"workers": [
3,
3
],
"prefetch": false,
"sequence": "own state+mirror; T2 and prestate/cache accounting between T1; no drop_caches/seed; no 300s wall wait",
"cache_protocol": "natural OS cache, not controlled warm/cold",
"rsync": "native recorded views only; last step RRDP failure preserved"
}
}

View File

@@ -0,0 +1,78 @@
#!/usr/bin/env python3
"""Fetch a reviewed bundle manifest via parallel compressed rsync, then hash all files.
Fetch the small exported manifest first. No remote mutation, cleanup, RP or server
execution is performed here. Source absolute paths are provenance, destinations
are always relative to the local bundle root.
"""
from __future__ import annotations
import argparse
from concurrent.futures import ThreadPoolExecutor
import json
from pathlib import Path
import shlex
import subprocess
import tempfile
from common import file_sha256
from replay_bundle import load_manifest, safe_path, verify
def fetch(root: Path, manifest: dict, host: str, key: Path, jobs: int) -> dict:
if not 1 <= jobs <= 16 or host.startswith("-") or any(c.isspace() for c in host):
raise ValueError("invalid transfer endpoint/job count")
ssh = shlex.join(["ssh", "-F", "/dev/null", "-i", str(key.resolve()), "-o", "IdentitiesOnly=yes",
"-o", "BatchMode=yes", "-o", "ConnectTimeout=10", "-o", "StrictHostKeyChecking=yes"])
archive_root = Path(next(r["source"] for r in manifest["files"] if r["path"] == "archive/contract.json")).parent
pending, other = [], []
for row in manifest["files"]:
target = safe_path(root, row["path"])
if target.exists():
if target.stat().st_size == row["bytes"] and file_sha256(target) == row["sha256"]:
continue
raise ValueError("existing local content differs: " + row["path"])
target.parent.mkdir(parents=True, exist_ok=True)
if row["path"].startswith("archive/"):
relative = row["path"][len("archive/"):]
if Path(row["source"]) != archive_root / relative:
raise ValueError("archive source layout mismatch")
pending.append((row["bytes"], relative))
else:
other.append(row)
groups = [[] for _ in range(jobs)]
sizes = [0] * jobs
for size, relative in sorted(pending, reverse=True):
index = sizes.index(min(sizes))
groups[index].append(relative)
sizes[index] += size
base = ["rsync", "-rtz", "--compress-level=3", "--timeout=120", "--protect-args", "-e", ssh]
def transfer(index: int):
with tempfile.TemporaryDirectory(prefix="rpki-bundle-list-") as tmp:
listing = Path(tmp) / "files"
listing.write_text("\n".join(groups[index]) + "\n")
if groups[index]:
subprocess.run(base + ["--files-from=" + str(listing), host + ":" + str(archive_root) + "/",
str(root / "archive") + "/"], check=True)
with ThreadPoolExecutor(max_workers=jobs) as pool:
list(pool.map(transfer, range(jobs)))
for row in other:
subprocess.run(base + [host + ":" + row["source"], str(safe_path(root, row["path"]))], check=True)
return verify(root, manifest)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--manifest", type=Path, required=True)
parser.add_argument("--expected-sha256", required=True)
parser.add_argument("--root", type=Path, required=True)
parser.add_argument("--host", required=True)
parser.add_argument("--identity", type=Path, required=True)
parser.add_argument("--jobs", type=int, default=8)
args = parser.parse_args()
manifest = load_manifest(args.manifest, args.expected_sha256)
print(json.dumps(fetch(args.root, manifest, args.host, args.identity, args.jobs)))
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,313 @@
#!/usr/bin/env python3
"""Portable natural 13-step replay; serial state/mirror, historical T2 between steps.
No cache drop, fixed seed, prefetch, source diagnostics or online data collection.
The new consumed bundle path is service-verified separately from historical runs.
"""
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
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
from sequence_matrix import (PROFILE_FLAGS, call, resource_guard, systemd_measure, tal_arguments,
rp_command, require_ready, require_transport, payload_counts,
compare_profile_contracts, require_t2_fallback_bindings)
from replay_bundle import load_manifest, verify as verify_bundle
from serve import uri_key
PROTOCOL = "natural-serial-13-v1"
def validate_profiles(order: list[str]) -> None:
if (not order or len(order) != len(set(order)) or set(order) - set(PROFILE_FLAGS)
or (len(order) > 1 and order[0] != "baseline")):
raise ValueError("select one profile or a unique matrix with baseline first")
def require_expected_outputs(run: Path, expected: dict) -> None:
"""CCR canonical state digests plus CIR census; T2 supplies full row equivalence."""
ccr = read_json(run / "ccr-comparison.json")
cir = read_json(run / "cir-comparison.json")
states = {r["name"]: (r["verificationPresent"], r["verificationHashHex"]) for r in ccr["states"]}
if states != {k: tuple(v) for k, v in expected["ccr_states"].items()}:
raise ValueError("CCR differs from pinned canonical outputs")
if cir["rpkiClient"] != expected["cir_census"]:
raise ValueError("CIR census differs from pinned historical outputs")
if payload_counts(run) != expected["counts"]:
raise ValueError("payload counts differ from pinned outputs")
def check_requests(path: Path, epoch: dict) -> None:
expected = {uri_key(r["uri"]): r for r in epoch["http_entities"] if r["kind"] != "ta"}
actual = set()
statuses = {}
for line in path.read_text().splitlines():
event = json.loads(line)
statuses[str(event["status"])] = statuses.get(str(event["status"]), 0) + 1
if event["status"] in (200, 304):
key = uri_key(event["uri"])
if key not in expected or event["sha256"] != expected[key]["sha256"]:
raise ValueError("unexpected served entity")
actual.add(key)
elif not event.get("controlled_failure"):
raise ValueError("unexpected unserved request; consumed subset is insufficient")
if actual != set(expected) or statuses != epoch["expected_transport"]["http_response_status_counts"]:
raise ValueError("request workload differs from the pinned natural chain")
def run_natural(config: dict) -> dict:
if socket.gethostname() != config["expected_host"] or os.geteuid() != 0:
raise ValueError("natural replay requires root on the configured host")
root, scope_path, output = (Path(config[k]).resolve() for k in ("archive", "scope", "out"))
outside_archive(root, output)
bundle_path = Path(config["bundle_manifest"]).resolve()
bundle = load_manifest(bundle_path, config["expected_bundle_sha256"])
bundle_proof = verify_bundle(bundle_path.parent, bundle)
if output.is_relative_to(bundle_path.parent):
raise ValueError("outputs must be outside the immutable bundle")
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 = True
expected_outputs = read_json(Path(config["expected_outputs"]))
expected_outputs_sha256 = file_sha256(Path(config["expected_outputs"]))
order = config.get("profile_order", list(PROFILE_FLAGS))
validate_profiles(order)
first_profile = order[0]
summary = {"status": "running", "pass": False, "purpose": "natural-serial-13-step", "protocol": PROTOCOL, "bundle_verification": bundle_proof,
"performance_ready": False, "missing_formal_metrics": [] if formal else ["sync-wall-union", "payload-ready-publication"],
"expected_outputs_sha256": expected_outputs_sha256,
"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, config.get("minimum_free_gib", 150))}
atomic_json(output / "summary.json", summary)
namespaces_owned = False
try:
if subprocess.run(["systemctl", "is-active", "--quiet", "panda-rpki.service"], capture_output=True).returncode == 0:
raise ValueError("Panda must already be stopped; this runner never restarts it")
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, bundle["origin_hosts"])))
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, config.get("minimum_free_gib", 150))
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),
"--bundle-manifest", str(bundle_path), "--bundle-sha256", config["expected_bundle_sha256"]])
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 == first_profile:
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 / first_profile / 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)
if config.get("expected_outputs"):
expected = expected_outputs["steps"][step]
require_expected_outputs(run, expected)
check_requests(run / "server-requests.jsonl", bundle["epochs"][step])
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)
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):
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 interrupted(*_) -> None:
raise KeyboardInterrupt("natural replay controller interrupted")
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--config", type=Path, default=Path(__file__).parent / "configs/natural13.json")
parser.add_argument("--dataset", type=Path, required=True)
parser.add_argument("--binary-dir", type=Path, required=True)
parser.add_argument("--out", type=Path, required=True)
parser.add_argument("--profiles", nargs="+", choices=tuple(PROFILE_FLAGS))
parser.add_argument("--expected-binary-sha256", help="Explicit pin for a future candidate build")
parser.add_argument("--check-only", action="store_true", help="Hash bundle/config/tools without starting RP")
args = parser.parse_args()
config = read_json(args.config)
if config.get("protocol") != PROTOCOL or config.get("formal_metrics") is not True:
raise ValueError("config must select the standard natural protocol and all seven metrics")
config.update(archive=str(args.dataset.resolve() / "archive"), scope=str(args.dataset.resolve() / "config/scope.json"),
bundle_manifest=str(args.dataset.resolve() / "bundle-manifest.json"), out=str(args.out.resolve()))
names = {"binary": "rpki", "ccr_compare": "verification_ccr_compare", "cir_compare": "cir_state_compare", "db_stats": "db_stats"}
for name, filename in names.items():
config[name] = str(args.binary_dir.resolve() / filename)
config["expected_outputs"] = str((args.config.parent / config["expected_outputs"]).resolve())
if args.profiles:
config["profile_order"] = args.profiles
if args.expected_binary_sha256:
config["expected_binary_sha256"] = args.expected_binary_sha256
validate_profiles(config["profile_order"])
if args.check_only:
manifest = load_manifest(Path(config["bundle_manifest"]), config["expected_bundle_sha256"])
proof = verify_bundle(args.dataset, manifest)
if file_sha256(Path(config["binary"])) != config["expected_binary_sha256"]:
raise ValueError("RP binary pin mismatch")
for name in names:
proof[name + "_sha256"] = file_sha256(Path(config[name]))
require_closure(Path(config["archive"]), Path(config["scope"]))
print(json.dumps(proof))
return
signal.signal(signal.SIGTERM, interrupted)
result = run_natural(config)
print(json.dumps({"pass": result["pass"], "runs": len(result["runs"]), "protocol": PROTOCOL}))
if __name__ == "__main__":
main()

View File

@@ -20,7 +20,7 @@ def command(*args: str) -> None:
subprocess.run(args, check=True, timeout=30, capture_output=True, text=True)
def all_hosts(root: Path) -> list[str]:
def all_hosts(root: Path, extra_hosts: list[str] | None = None) -> list[str]:
hosts = set()
def add(uri):
url = urllib.parse.urlsplit(uri)
@@ -33,6 +33,11 @@ def all_hosts(root: Path) -> list[str]:
if not re.fullmatch(r"[a-z0-9.-]+", host):
raise ValueError(f"unsafe hostname: {host}")
hosts.add(host)
for host in extra_hosts or []:
add("https://" + host + "/")
if (root / "registry.json").exists():
for uri in read_json(root / "registry.json"):
add(uri)
for path in (root / "events").glob("*.json"):
add(read_json(path)["uri"])
for path in (root / "observations").glob("*.json"):
@@ -182,14 +187,21 @@ def main():
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("--bundle-manifest", type=Path)
parser.add_argument("--bundle-sha256")
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)
state = ReplayState(args.archive, args.epoch, args.scope, args.bundle_manifest, args.bundle_sha256)
if args.bundle_manifest:
from replay_bundle import load_manifest
bundle = load_manifest(args.bundle_manifest, args.bundle_sha256)
hosts = all_hosts(args.archive, bundle["origin_hosts"])
else:
hosts = all_hosts(args.archive)
mapping = host_mapping(hosts)
args.out.mkdir(parents=True, exist_ok=True)
tls = tls_assets(args.out, hosts)
@@ -209,6 +221,8 @@ def main():
"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))
if args.bundle_manifest:
manifest.update(bundle_manifest=str(args.bundle_manifest.resolve()), bundle_sha256=args.bundle_sha256)
atomic_json(epoch_root / "replay.json", manifest)
if args.create_network:
create_network(mapping)

View File

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

View File

@@ -26,6 +26,10 @@ def main():
if file_sha256(Path(manifest["scope_path"])) != manifest["scope_sha256"]:
raise ValueError("replay scope changed since asset preparation")
command += ["--scope", manifest["scope_path"]]
if manifest.get("bundle_manifest"):
if file_sha256(Path(manifest["bundle_manifest"])) != manifest["bundle_sha256"]:
raise ValueError("consumed bundle manifest changed since preparation")
command += ["--bundle-manifest", manifest["bundle_manifest"], "--bundle-sha256", manifest["bundle_sha256"]]
for scheme in ("http", "https"):
for port in manifest[scheme + "_ports"]:
command += ["--" + scheme + "-port", str(port)]

View File

@@ -21,7 +21,8 @@ def uri_key(uri: str) -> tuple:
class ReplayState:
def __init__(self, root: Path, epoch_path: Path, scope_path: Path | None = None):
def __init__(self, root: Path, epoch_path: Path, scope_path: Path | None = None,
bundle_manifest: Path | None = None, bundle_sha256: str | None = None):
self.archive = Archive(root, read_only=True)
self.epoch_path = epoch_path
self.epoch_hash = digest_bytes(epoch_path.read_bytes())
@@ -31,6 +32,14 @@ class ReplayState:
raise ValueError("capture contract hash mismatch")
self.scope = None
self.scope_hash = None
self.subset = None
if bundle_manifest is not None or bundle_sha256 is not None:
from replay_bundle import epoch_subset
if bundle_manifest is None or scope_path is None or bundle_sha256 is None:
raise ValueError("subset requires scope, manifest and pinned SHA256")
self.subset = epoch_subset(root, epoch_path, scope_path, bundle_manifest, bundle_sha256)
self.allowed = ({uri_key(r["uri"]): r for r in self.subset["http_entities"]}
if self.subset is not None else None)
self.failures = {}
if scope_path is not None:
from scope import select_epoch
@@ -64,6 +73,8 @@ class ReplayState:
event = read_json(root / "events" / f"{event_id}.json")
self.check_event(event, uri)
self.rsync_events.append(event)
if self.allowed is not None and set(self.entries) != set(self.allowed):
raise ValueError("consumed HTTP entities are not closed by original metadata")
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"]:
@@ -71,6 +82,12 @@ class ReplayState:
def add(self, uri: str, ref: dict, content_type: str) -> None:
key = uri_key(uri)
if self.allowed is not None:
selected = self.allowed.get(key)
if selected is None:
return
if selected["sha256"] != ref["sha256"] or selected["bytes"] != ref["size"]:
raise ValueError("consumed entity differs from original metadata")
existing = self.entries.get(key)
if existing and existing["sha256"] != ref["sha256"]:
raise ValueError(f"conflicting contents for one epoch URI: {uri}")
@@ -140,6 +157,8 @@ def main():
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("--bundle-manifest", type=Path)
parser.add_argument("--bundle-sha256")
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=[])
@@ -151,7 +170,7 @@ def main():
if args.scope:
from scope import require_closure
require_closure(args.archive, args.scope)
state = ReplayState(args.archive, args.epoch, args.scope)
state = ReplayState(args.archive, args.epoch, args.scope, args.bundle_manifest, args.bundle_sha256)
if not args.http_port and not args.https_port:
parser.error("at least one server port is required")
servers, listeners = [], []

View File

@@ -0,0 +1,112 @@
import hashlib
import io
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
from common import Archive, atomic_json, file_sha256
from natural_replay import check_requests, validate_profiles
from prepare_replay import all_hosts
from replay_bundle import SCHEMA, load_manifest, safe_path, verify
from serve import ReplayState, uri_key
class BundleTests(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"unchanged signed input"))
self.uri = "https://rp.example/notification.xml"
binding = dict(id="one", session="session", serial=1, notification=self.ref, view="view", completed_ms=1)
observation = dict(binding, complete=True, references=[dict(uri="https://rp.example/unused.xml",
available=True, sha256="f" * 64, size=500)])
atomic_json(self.archive.root / "observations/one.json", observation)
self.epoch = self.archive.root / "epochs/epoch_0000.json"
atomic_json(self.epoch, dict(complete=True, validation_time_ms=2, repositories={self.uri: binding},
ta_object_events={}, rsync_view_events={}))
self.scope = self.root / "config/scope.json"
atomic_json(self.scope, {})
selected = dict(kind="notification", uri=self.uri, sha256=self.ref["sha256"], bytes=self.ref["size"], steps=[0])
files = []
for path in [self.scope, self.epoch, self.archive.root / "observations/one.json", self.archive.blob_path(self.ref["sha256"])]:
files.append(dict(path=str(path.relative_to(self.root)), sha256=file_sha256(path), bytes=path.stat().st_size))
self.manifest = self.root / "bundle-manifest.json"
atomic_json(self.manifest, dict(schema=SCHEMA, full_archive_closure=False, files=files,
scope_sha256=file_sha256(self.scope), payload_totals={}, epochs=[dict(path="epochs/epoch_0000.json",
sha256=file_sha256(self.epoch), http_entities=[selected], expected_transport={"http_response_status_counts": {"200": 1}})]))
self.sha = file_sha256(self.manifest)
def state(self):
with patch("scope.select_epoch", return_value={"excluded_repositories": [], "routes": {}}):
return ReplayState(self.archive.root, self.epoch, self.scope, self.manifest, self.sha)
def test_missing_unused_reference_requires_explicit_subset(self):
with self.assertRaisesRegex(ValueError, "missing/truncated"):
ReplayState(self.archive.root, self.epoch)
self.assertEqual(set(self.state().entries), {uri_key(self.uri)})
def test_manifest_pin_is_required_and_enforced(self):
with self.assertRaisesRegex(ValueError, "pinned"):
ReplayState(self.archive.root, self.epoch, self.scope, self.manifest)
with self.assertRaisesRegex(ValueError, "SHA256 mismatch"):
load_manifest(self.manifest, "0" * 64)
def test_original_metadata_tamper_fails(self):
self.epoch.write_text(self.epoch.read_text() + " ")
with self.assertRaisesRegex(ValueError, "metadata changed"):
self.state()
def test_required_payload_is_never_skipped(self):
self.archive.blob_path(self.ref["sha256"]).unlink()
with self.assertRaisesRegex(ValueError, "missing/truncated"):
self.state()
def test_full_file_hash_verification_detects_same_size_corruption(self):
manifest = load_manifest(self.manifest, self.sha)
self.assertTrue(verify(self.root, manifest)["pass"])
blob = self.archive.blob_path(self.ref["sha256"])
blob.write_bytes(b"x" * blob.stat().st_size)
with self.assertRaisesRegex(ValueError, "missing or changed"):
verify(self.root, manifest)
def test_relative_paths_cannot_escape_bundle(self):
for relative in ("../escape", "/etc/passwd", "archive/../../escape"):
with self.assertRaises(ValueError):
safe_path(self.root, relative)
(self.root / "escape").symlink_to(self.root.parent)
with self.assertRaises(ValueError):
safe_path(self.root, "escape/file")
def test_request_audit_detects_unexpected_fetch_or_missing_input(self):
epoch = load_manifest(self.manifest)["epochs"][0]
log = self.root / "requests.jsonl"
event = dict(uri=self.uri, status=200, sha256=self.ref["sha256"], controlled_failure=False)
log.write_text(json.dumps(event) + "\n")
check_requests(log, epoch)
event.update(uri="https://rp.example/unused.xml", status=404, sha256=None)
log.write_text(json.dumps(event) + "\n")
with self.assertRaisesRegex(ValueError, "unserved"):
check_requests(log, epoch)
log.write_text("")
with self.assertRaisesRegex(ValueError, "workload"):
check_requests(log, epoch)
def test_profiles_are_independent_with_baseline_first_for_matrix(self):
validate_profiles(["pp"])
validate_profiles(["baseline", "signature", "object", "pp", "hybrid"])
for order in ([], ["pp", "baseline"], ["pp", "pp"], ["unknown"]):
with self.assertRaises(ValueError):
validate_profiles(order)
def test_host_mapping_keeps_failed_registry_and_original_rsync_origins(self):
atomic_json(self.archive.root / "registry.json", {self.uri: {}, "https://missing.example/n.xml": {}})
hosts = all_hosts(self.archive.root, ["failed-rsync.example"])
self.assertEqual(set(hosts), {"rp.example", "missing.example", "failed-rsync.example"})
if __name__ == "__main__":
unittest.main()

View File

@@ -0,0 +1,88 @@
#!/usr/bin/env python3
"""Verify consumed snapshot/delta transitions against original recorded view digests.
No RP or live Internet access. This verifies the frozen 13-step workload, not
unused minute observations or all advertised RRDP history in the full capture.
"""
from __future__ import annotations
import argparse
import json
from pathlib import Path
from common import Archive, file_sha256, read_json
from replay_bundle import load_manifest, verify
from rrdp import notification, payload_view, view_digest
from scope import require_closure
from serve import ReplayState
def verify_chain(root: Path, manifest_path: Path, expected_sha256: str) -> dict:
manifest = load_manifest(manifest_path, expected_sha256)
proof = verify(root, manifest)
archive = Archive(root / "archive", read_only=True)
scope_path = root / "config/scope.json"
scope = require_closure(archive.root, scope_path)
views, versions = {}, {}
steps = []
for selection in manifest["epochs"]:
epoch_path = archive.root / selection["path"]
state = ReplayState(archive.root, epoch_path, scope_path, manifest_path, expected_sha256)
allowed = {(r["uri"], r["sha256"]) for r in selection["http_entities"]}
snapshots, deltas, unchanged, failures = 0, 0, 0, 0
for uri, binding in state.epoch["repositories"].items():
if uri in scope["routes"].get(epoch_path.name, {}):
failures += 1
continue # This step consumes the bound rsync view, not RRDP.
observation = read_json(archive.root / "observations" / f"{binding['id']}.json")
parsed = notification(archive.blob_path(binding["notification"]["sha256"]), uri)
if (parsed["session"], parsed["serial"]) != (binding["session"], binding["serial"]):
raise ValueError("notification binding changed")
if uri not in views:
ref = next(r for r in parsed["references"] if r["kind"] == "snapshot")
if (ref["uri"], ref["sha256"]) not in allowed:
raise ValueError("required initial snapshot missing")
views[uri] = payload_view(archive.blob_path(ref["sha256"]), "snapshot", parsed["session"], parsed["serial"])
snapshots += 1
else:
session, serial, digest = versions[uri]
if session != parsed["session"] or serial > parsed["serial"]:
raise ValueError("unserved session reset or serial rollback")
refs = {r["serial"]: r for r in parsed["references"] if r["kind"] == "delta"}
if parsed["serial"] - serial > 10000:
raise ValueError("delta chain bound")
for number in range(serial + 1, parsed["serial"] + 1):
ref = refs[number]
if (ref["uri"], ref["sha256"]) not in allowed:
raise ValueError("consumed delta chain is incomplete")
views[uri] = payload_view(archive.blob_path(ref["sha256"]), "delta", session, number, views[uri])
deltas += 1
if serial == parsed["serial"]:
unchanged += 1
digest = view_digest(views[uri])
if digest != binding["view"]:
raise ValueError("consumed chain differs from original snapshot view: " + uri)
versions[uri] = (parsed["session"], parsed["serial"], digest)
rsync = {uri: ref for event in state.rsync_events for uri, ref in event["objects"].items()}
expected_rsync = {r["uri"]: {"sha256": r["sha256"], "size": r["bytes"]}
for r in manifest["payload_inventory"] if r["kind"] == "rsync" and selection["step"] in r["steps"]}
if rsync != expected_rsync:
raise ValueError("rsync workload differs from selected content")
steps.append({"step": selection["step"], "snapshots": snapshots, "deltas": deltas,
"unchanged": unchanged, "rrdp_controlled_failures": failures,
"http_entities": len(state.entries), "rsync_files": len(rsync), "view_digests_match": True})
return {**proof, "manifest_sha256": file_sha256(manifest_path), "steps": steps,
"new_rp_executions": 0, "verification": "consumed natural chain vs original view digests; no full minute-history closure claim"}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--root", type=Path, required=True)
parser.add_argument("--manifest", type=Path, required=True)
parser.add_argument("--expected-sha256", required=True)
args = parser.parse_args()
print(json.dumps(verify_chain(args.root, args.manifest, args.expected_sha256)))
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,153 @@
#!/usr/bin/env python3
"""Exercise every selected HTTP entity over local verified TLS, plus native rsync.
Uses loopback and temporary assets only: no RP, network namespace, live origin,
system service change or performance measurement. URI Host/SNI remains original.
"""
from __future__ import annotations
import argparse
import hashlib
from http.client import HTTPResponse
from http.server import ThreadingHTTPServer
import json
import os
from pathlib import Path
import socket
import ssl
import subprocess
import tempfile
import threading
import time
from urllib.parse import urlsplit
from common import file_sha256, read_json
from prepare_replay import all_hosts, rsync_tree, tls_assets
from replay_bundle import load_manifest
from serve import ReplayState, handler_for
def verify_server(root: Path, manifest_path: Path, expected_sha256: str) -> dict:
manifest = load_manifest(manifest_path, expected_sha256)
steps = []
with tempfile.TemporaryDirectory(prefix="rpki188-bundle-service-") as tmp:
assets = Path(tmp)
assets.chmod(0o755)
tls = tls_assets(assets, all_hosts(root / "archive", manifest["origin_hosts"]))
context = ssl.create_default_context(cafile=tls["ca"])
for selection in manifest["epochs"]:
state = ReplayState(root / "archive", root / "archive" / selection["path"], root / "config/scope.json",
manifest_path, expected_sha256)
entities, bytes_checked, failures_checked = 0, 0, 0
for scheme in ("http", "https"):
rows = [r for r in selection["http_entities"] if urlsplit(r["uri"]).scheme == scheme]
for key, status in state.failures.items():
protocol, host, port, path, query = key
if protocol == scheme:
rows.append({"uri": f"{protocol}://{host}:{port}{path}" + ("?" + query if query else ""),
"expected_status": status, "bytes": 0})
if not rows:
continue
server = ThreadingHTTPServer(("127.0.0.1", 0), handler_for(state, scheme))
if scheme == "https":
server_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
server_context.load_cert_chain(tls["cert"], tls["key"])
server.socket = server_context.wrap_socket(server.socket, server_side=True)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
for row in rows:
uri = urlsplit(row["uri"])
sock = socket.create_connection(server.server_address, timeout=30)
if scheme == "https":
sock = context.wrap_socket(sock, server_hostname=uri.hostname)
with sock:
target = (uri.path or "/") + (("?" + uri.query) if uri.query else "")
sock.sendall(f"GET {target} HTTP/1.1\r\nHost: {uri.netloc}\r\nConnection: close\r\n\r\n".encode("ascii"))
response = HTTPResponse(sock)
response.begin()
if response.status != row.get("expected_status", 200):
raise ValueError(f"entity fetch failed: {response.status} {row['uri']}")
digest, size = hashlib.sha256(), 0
while chunk := response.read(1024 * 1024):
digest.update(chunk)
size += len(chunk)
if size != row["bytes"] or (response.status == 200 and digest.hexdigest() != row["sha256"]):
raise ValueError("served bytes differ from pinned entity")
if response.status == 200:
entities += 1
else:
failures_checked += 1
bytes_checked += size
finally:
server.shutdown()
server.server_close()
thread.join(timeout=10)
rsync_count = 0
if state.rsync_events:
configs = rsync_tree(state, assets / f"rsync-{selection['step']}",
{urlsplit(e["uri"]).hostname: "127.0.0.1" for e in state.rsync_events})
for index, original in enumerate(configs):
original = Path(original)
with socket.socket() as probe:
probe.bind(("127.0.0.1", 0))
port = probe.getsockname()[1]
config = original.with_name("loopback.conf")
lines = original.read_text().splitlines()
lines = [f"port = {port}" if line.startswith("port = ") else line for line in lines]
# A non-root loopback verifier must inherit its uid/groups;
# explicit gid makes rsync call privileged setgroups().
# Production prepared configs still use uid/gid 65534.
if os.geteuid() != 0:
lines = [line for line in lines if not line.startswith(("uid = ", "gid = "))]
config.write_text("\n".join(lines) + "\n")
process = subprocess.Popen(["rsync", "--daemon", "--no-detach", "--config", str(config)],
stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
try:
deadline = time.monotonic() + 10
while True:
if process.poll() is not None:
raise RuntimeError(process.stderr.read().decode())
try:
with socket.create_connection(("127.0.0.1", port), timeout=1):
break
except OSError:
if time.monotonic() >= deadline:
raise
time.sleep(.05)
modules = original.parent / "modules"
for module in modules.iterdir():
target = assets / f"fetched-{selection['step']}-{index}" / module.name
target.mkdir(parents=True)
transfer = subprocess.run(["rsync", "-r", f"rsync://127.0.0.1:{port}/{module.name}/", str(target)],
capture_output=True, timeout=60)
if transfer.returncode:
raise RuntimeError("loopback rsync failed: " + transfer.stderr.decode(errors="replace"))
expected = {str(p.relative_to(module)): file_sha256(p) for p in module.rglob("*") if p.is_file()}
actual = {str(p.relative_to(target)): file_sha256(p) for p in target.rglob("*") if p.is_file()}
if expected != actual:
raise ValueError("native rsync file contents differ")
rsync_count += len(actual)
finally:
process.terminate()
process.wait(timeout=10)
process.stderr.close()
steps.append({"step": selection["step"], "http_entities": entities,
"controlled_failures_checked": failures_checked,
"served_body_bytes": bytes_checked, "native_rsync_files": rsync_count, "pass": True})
return {"pass": True, "manifest_sha256": expected_sha256, "steps": steps,
"https": "local CA chain and original-hostname SNI verification enabled",
"new_rp_executions": 0, "performance_measurement": False}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--root", type=Path, required=True)
parser.add_argument("--manifest", type=Path, required=True)
parser.add_argument("--expected-sha256", required=True)
args = parser.parse_args()
print(json.dumps(verify_server(args.root, args.manifest, args.expected_sha256)))
if __name__ == "__main__":
main()