Repository navigation
test(no-direct): synthetic netns field-test tool for #284 (test-only) - #338
Conversation
…ce, test-only) Reproducible local lab proving the no-DIRECT user-egress invariant of #284 at runtime (acceptance scenarios A/B/C/D plus IPv6): three network namespaces — vps (simulated VPS public IP v4+v6, mihomo A with Builder- generated YAML from the vendored web4core runtime), egress (the allowed upstream node, mihomo B), and the root namespace hosting the controlled logging endpoint, subscription server and a DNS stub. Leak criterion: any endpoint hit whose source is the VPS IP outside the deliberate leak-detector selftest => hard FAIL exit 1. - gen.mjs regenerates scenario configs via buildFromRequest; lab-only additions (external-controller, VLESS ingress listener) are marked and separated from the Builder output; - lab.sh runs the full matrix with per-hop liveness checks and a cleanup trap owning only its own processes/namespaces; transient state (run/, certs/) is gitignored; - the lab CA lives only in certs/ and is trusted exclusively via SSL_CERT_FILE of the one process that needs it — the system trust store is never modified; - ipv6-observe.sh / ipv6-live-exit.sh: with ipv6: false on the exit node, IPv6 destinations are refused outright (fail-closed, 'ip version error'); with an ipv6-capable exit, the endpoint sees the egress v6 and never the VPS v6 — zero fd00:2010::3 hits in any scenario; - dns-observe.sh: hostname requests are passed to the upstream for remote resolution; the VPS-side DNS stub logs zero queries. Synthetic data only (RFC 5737 / RFC 4122 / fd00::/8 / lab.local). Requires MIHOMO_BIN (>= 1.19.31) and root network namespaces; no real VPS, no production claims — OS-level packet path stays a separate acceptance (BLOCKED until owner GO).
…, fail-closed verdict Safety review fixes for the no-direct-egress lab (owner review of PR #338): Containment: every lab script re-executes itself inside a private 'unshare -n' namespace (require_lab_isolation) — all sysctl/iptables/ topology changes are namespace-local and vanish with it; the shared host stack is never modified and there is no fallback to the host namespace. Paired host-state snapshots (iptables/ip6tables -S, sysctls, netns list, links, processes) are byte-identical before/after a full suite run. Ownership: child 'vps'/'egress' namespaces are UNNAMED, created by PID — nothing under /run/netns, no shared names to collide with foreign namespaces. Every started process is registered with a run-unique marker; cleanup kills only PIDs whose /proc cmdline still carries it (no pkill, no pattern kills) and removes only this run's directory. Concurrent runs are refused via a PID-recorded mkdir lock with stale takeover. Fail-closed verdict (lib/verdict.sh): every unmet mandatory condition — failed positive, unexpectedly passing negative, non-expected HTTP status (lab_curl/api_ok/api_select=204), unreachable hop, refused GLOBAL select — accumulates; final verdict exits 1 on any FAIL or any non-selftest endpoint hit from the simulated VPS IP (v4+v6). Lab infrastructure probes are marked URLs (/self-vps, /self-egress, /selftest-direct) and whitelisted from the leak criterion; the detector itself is proven by a mandatory selftest before results are trusted. Correctness fixes found while re-running: API readiness is probed via GET /proxies/GLOBAL==200 (/version answers while the default empty config is still applied — selections 404 in that window); every scenario restart gets a fresh -d directory (profile.store-selected would otherwise restore the previous scenario's GLOBAL selection); outage members are dead-upstream-1/2 (the old select of a non-existent name was silently moot); observe scripts wait for dest to listen and forward child-to-child transit (without it the strict-exit 502 was transport death, not the tested semantics); IPv6 lab addresses use nodad (DAD made early v6 dials fail). test-guards.sh: 38 static/mock checks — no pkill, no 'ip netns add/del', no system trust mutation, isolation gate precedes mutations, strict status helpers in use, marker-checked cleanup, verdict FAILs on leak/FAIL. All guards pass; lab.sh and all three observe scripts end with VERDICT: PASS / exit 0 on the pinned mihomo 1.19.31.
…spoofed isolation (#284) Fail closed if AMG_LAB_INSIDE is inherited in PID 1's network namespace; require real distinct netns before loopback/sysctl mutation. Fix inert grep -q pipeline in static containment guard and add mock-negative assertions. Run rootless guard suite in Generator CI (never live netns).
…vidence (#338) Keep Linux lab scripts LF even when checked out from Windows. Document verified namespace gate and 43 rootless guard checks.
Independent safety review + integration update — 08.11.2026Draft #338 head: Two concrete safety issues fixed:
Integration / reproducibility: Generator CI now calls Final exact-SHA CI: Generator CI #42508764310 was PENDING when this note was composed; provenance #42508764309 started. Do NOT claim final GREEN until complete. Existing real netns lab evidence is from prior #338/#355 runs, not from these CI rootless guards. Remaining gate: review final exact SHA checks, then separate owner GO for integrating test-only #338. After any squash merge, rebase/reconstruct stacked #360 so its resulting diff is only its own DPR scenario. Full host-level VPS/IPv6 packet-path verification remains NOT TESTED; no claim of production-wide no-leak proof. |
Final exact-SHA CI checkpoint — 2026-11-08HEAD
Review verdict: code/CI READY FOR OWNER REVIEW; no merge authorized yet. The preexisting synthetic lab's network-level evidence and stacked #360 remain separate; real host firewall/PBR/NAT, IPv6 DPR and actual VPS field proof remain NOT TESTED here. To integrate stacked #360 cleanly after #338/#352, reconstruct its diff to its own test-only files and rerun exact-head CI. |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: fd187c20ae
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| ip link set lo up || { echo "FATAL: cannot initialize private loopback" >&2; exit 1; } | ||
| ip addr add 127.0.0.1/8 dev lo 2>/dev/null || { echo "FATAL: cannot address private loopback" >&2; exit 1; } |
There was a problem hiding this comment.
Make loopback address initialization idempotent
On Linux, bringing a fresh namespace's loopback interface up automatically installs 127.0.0.1/8. The subsequent address-add therefore fails with an existing-address error, which this gate treats as fatal. All four live lab scripts call this gate and consequently exit before running their scenarios. Remove the redundant address addition or accept an already-correct loopback address.
Useful? React with 👍 / 👎.
| say "== Scenario D2: provider fetch with dead node ==" | ||
| restart_vps configA-sub-dead | ||
| sleep 3 | ||
| grep -q '"remote":"'$VPS_V4'"' "$DEST_LOG" || lab_fail "D2: provider fetch did not run despite a dead node in the subscription" |
There was a problem hiding this comment.
Check scenario-specific subscription logs for provider fetches
In scenarios D and D2, this assertion reads dest.jsonl, but subscription requests are written to sub.jsonl by dest.mjs. Moreover, the destination log already contains VPS-source entries from the mandatory liveness checks and leak-detector selftest, so both assertions pass even if no subscription fetch occurs. In particular, D2 can report PASS when fetching the dead-node subscription itself fails. Check a fresh subscription-log entry for the corresponding /sub or /sub-dead request and the expected source instead.
Useful? React with 👍 / 👎.
| const name = msg.subarray(12, msg.length - 5); | ||
| const ans = Buffer.concat([ | ||
| hdr, name, Buffer.from([0, 0, 0, 1]), | ||
| Buffer.from([0xc0, 0x0c, 0, 1, 0, 0, 0, 60, 0, 0, 0, 4, 10, 210, 0, 1]), |
There was a problem hiding this comment.
Encode a valid DNS question and answer in the stub response
For a normal A/IN query, removing the final five bytes strips the name terminator and question fields, but the replacement supplies only four bytes. The resulting question decodes as QTYPE 0 and QCLASS 448, and the answer is misaligned; the answer's class is also encoded as zero rather than IN. A resolver therefore cannot consume the advertised 10.210.0.1 answer. This can make the hostname negative test pass because the lab DNS stub is broken rather than because upstream routing fails closed. Preserve the original question and encode an A/IN resource record with the correct field boundaries.
Useful? React with 👍 / 👎.
…338 Preserve provider-only DPR implementation, i18n UI and rootless lab guard CI. Review and retest at resulting exact SHA before any merge.
Draft / не мержить без owner GO. Test-only: доказательная лаборатория #284 в репозитории (п. 3.1 продолжения). Продакшн-код Builder не меняется.
Safety-review 2026-11-06 (переработка изоляции и вердикта)
По итогам адресного review устранены пять блокирующих дефектов прежней версии:
side-effect'ом пере-exec'ается внутрь приватного
unshare -nnamespace(
lib/netns.sh:require_lab_isolation). Все sysctl/ссылки/forwarding —namespace-локальные и исчезают вместе с ним; общий host-стек не
изменяется.
unshareнедоступен → запуск отказывается работать(fallback на host-namespace отсутствует). Подтверждено парным снимком
host-состояния (iptables/ip6tables -S, sysctls,
ip netns list, ссылки,процессы) до/после полного прогона: различий нет.
— безымянные, по PID; в
/run/netnsничего не регистрируется, общих имённет. Cleanup убивает только зарегистрированные PID, чей
/proc/PID/cmdlineсодержит маркер этого запуска; удаляет только каталог этого запуска.
pkill/pattern-kill исключены полностью; конкурентные прогоны запрещеныmkdir-локом с PID держателя и перехватом протухшего лока.
lib/verdict.sh): любой упавший позитив,неожиданно прошедший негатив, HTTP-статус не по контракту
(
lab_curl/api_ok/api_select=204), недоступный хоп, отказ GLOBAL-выбора— копится в счётчик; финальный вердикт
exit 1при любом FAIL илилюбом не-selftest попадании с source «VPS» (v4+v6). Общий
VERDICT: PASSпри накопленных FAIL невозможен.
прямой запрос из vps-namespace должен наблюдаться на endpoint, иначе
прогон FATAL — критерий не считается «работающим по умолчанию».
GET /proxies/GLOBAL==200(/versionотвечает уже в окне стартовойконфигурации, где selections дают 404); каждый рестарт сценария получает
свежий
-dкаталог (profile.store-selectedиначе молча восстанавливал быGLOBAL предыдущего сценария); члены outage-конфига —
dead-upstream-1/2(прежний select несуществующего имени был фиктивным); observe-скрипты ждут
listen у dest и включают namespace-локальный child-to-child forwarding
(иначе строгий exit-502 был смертью транспорта, а не тестируемой
семантикой); v6-адреса лаборатории с
nodad(DAD ломал ранние v6-диалы).Матрица последнего прогона (2026-11-06, mihomo 1.19.31, WSL2)
test-guards.sh(38 статических/mock-проверок: нет pkill, нетip netns add/del, нет мутаций системного trust, gate до мутаций, строгие статусы, marker-очистка, вердикт FAIL при утечке/FAIL)GUARDS: ALL PASS, exit 0lab.shA: живой upstream (VLESS-ingress; loopback mixed)10.211.0.2lab.shB: полный отказ (all-dead url-test; ручной выборdead-upstream-1;GLOBAL=REJECT)lab.shC: ручной re-select на разрешённый узел10.211.0.2lab.shD: Sub Mode ON — provider-fetch (service plane) + user-planelab.shD2: мёртвый узел в подпискеdns-observe.sh: hostname при мёртвых upstream (наблюдение DNS-пути)ipv6-observe.sh: v6 через строгий exit (ipv6: false)ipv6-live-exit.sh: v6-capable egressfd00:2011::2(egress), никогдаfd00:2010::3Что внутри
tools/no-direct-egress-lab/web4core.runtime.js; lab-only добавки промаркированы;Гигиена
certs/(gitignored), доверие исключительно черезSSL_CERT_FILEодного процесса; системное доверие не изменяется;run/,certs/,wd*/) gitignored;MIHOMO_BIN(>= 1.19.31), root и Linux netns (WSL2 ок); в CI не запускается (изолированная сеть по контракту).Границы (без изменений)
Это не proof свойств ОС: host firewall/PBR/NAT, resolv.conf, реальный TUN, реальные клиенты и реальные VPS — отдельный packet-path/полевой этап (BLOCKED до owner GO). Полные результаты — в комментарии к Issue #284.