Skip to content

test(no-direct): synthetic netns field-test tool for #284 (test-only) - #338

Merged
saymer-alt merged 5 commits into
mainfrom
zai-no-direct-lab-tool
Nov 8, 2026
Merged

saymer-alt merged 5 commits into
mainfrom
zai-no-direct-lab-tool

Conversation

@saymer-alt

@saymer-alt saymer-alt commented Nov 5, 2026 •

Copy link
Copy Markdown
Owner

Draft / не мержить без owner GO. Test-only: доказательная лаборатория #284 в репозитории (п. 3.1 продолжения). Продакшн-код Builder не меняется.

Safety-review 2026-11-06 (переработка изоляции и вердикта)

По итогам адресного review устранены пять блокирующих дефектов прежней версии:

  1. Изоляция вместо мутаций host. Каждый скрипт лаборатории первым
    side-effect'ом пере-exec'ается внутрь приватного unshare -n namespace
    (lib/netns.sh:require_lab_isolation). Все sysctl/ссылки/forwarding —
    namespace-локальные и исчезают вместе с ним; общий host-стек не
    изменяется. unshare недоступен → запуск отказывается работать
    (fallback на host-namespace отсутствует). Подтверждено парным снимком
    host-состояния (iptables/ip6tables -S, sysctls, ip netns list, ссылки,
    процессы) до/после полного прогона: различий нет.
  2. Владение процессами и ресурсами. Дочерние namespace ("vps"/"egress")
    — безымянные, по PID; в /run/netns ничего не регистрируется, общих имён
    нет. Cleanup убивает только зарегистрированные PID, чей /proc/PID/cmdline
    содержит маркер этого запуска; удаляет только каталог этого запуска.
    pkill/pattern-kill исключены полностью; конкурентные прогоны запрещены
    mkdir-локом с PID держателя и перехватом протухшего лока.
  3. Fail-closed вердикт (lib/verdict.sh): любой упавший позитив,
    неожиданно прошедший негатив, HTTP-статус не по контракту
    (lab_curl/api_ok/api_select=204), недоступный хоп, отказ GLOBAL-выбора
    — копится в счётчик; финальный вердикт exit 1 при любом FAIL или
    любом не-selftest попадании с source «VPS» (v4+v6). Общий VERDICT: PASS
    при накопленных FAIL невозможен.
  4. Обязательный selftest детектора утечки в начале каждого прогона:
    прямой запрос из vps-namespace должен наблюдаться на endpoint, иначе
    прогон FATAL — критерий не считается «работающим по умолчанию».
  5. Корректность, найденная при перезапуске: готовность API проверяется
    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 0
lab.sh A: живой upstream (VLESS-ingress; loopback mixed) PASS — endpoint видел 10.211.0.2
lab.sh B: полный отказ (all-dead url-test; ручной выбор dead-upstream-1; GLOBAL=REJECT) PASS — клиент fail-closed (502) во всех трёх
lab.sh C: ручной re-select на разрешённый узел PASS — endpoint снова 10.211.0.2
lab.sh D: Sub Mode ON — provider-fetch (service plane) + user-plane PASS — fetch наблюдён с VPS-IP, user-plane через узел подписки
lab.sh D2: мёртвый узел в подписке PASS — fetch живёт, user-plane fail-closed
dns-observe.sh: hostname при мёртвых upstream (наблюдение DNS-пути) PASS (наблюдения информационные)
ipv6-observe.sh: v6 через строгий exit (ipv6: false) PASS — fail-closed, 0 v6-попаданий с VPS-v6
ipv6-live-exit.sh: v6-capable egress PASS — endpoint видел fd00:2011::2 (egress), никогда fd00:2010::3
Leak-критерий по всем прогонам 0 не-selftest попаданий с VPS-IP (v4+v6)

Что внутри tools/no-direct-egress-lab/

  • gen.mjs — сценарные конфиги ровно через vendored web4core.runtime.js; lab-only добавки промаркированы;
  • lib/netns.sh — gate изоляции, mkdir-лок, PID/marker-очистка, безымянные child-namespace, veth-проводка, ожидание listen и готовности API;
  • lib/verdict.sh — fail-closed счётчик, строгие HTTP-хелперы, критерий утечки с маркированными self-URL, терминальный вердикт;
  • lab.sh / dns-observe.sh / ipv6-observe.sh / ipv6-live-exit.sh — сценарии (см. матрицу);
  • test-guards.sh — 38 проверок гигиены и вердикта;
  • dest.mjs — контролируемый endpoint (dual-stack), сервер подписок, DNS-стаб.

Гигиена

  • lab CA — только в certs/ (gitignored), доверие исключительно через SSL_CERT_FILE одного процесса; системное доверие не изменяется;
  • секретов нет: синтетические UUID, RFC 5737-адреса, fd00::/8, lab.local; transient-состояние (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.

…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.

Copy link
Copy Markdown
Owner Author

Independent safety review + integration update — 08.11.2026

Draft #338 head: fd187c20ae87b4bf79eced29ea8146eb96c0aa1f; base main: 23b851a46b5808a290994dc0c9c22b032b95e266. The branch was synced by a two-parent merge commit, then a small follow-up documentation/LF commit. No squash/merge of the PR, production deployment or other PR mutation.

Two concrete safety issues fixed:

  1. The old require_lab_isolation() trusted AMG_LAB_INSIDE=1 from the environment. A spoiled/inherited marker could skip unshare -n and then invoke network setup in the host namespace. Now it checks that /proc/self/ns/net differs from /proc/1/ns/net before any loopback or sysctl writes, and exits immediately on absent/unreadable/equal namespace evidence. Pure predicate and synthetic spoof-negative mock added to rootless guards.
  2. The previous guard grep -qE ... | grep -v ... was effectively inert: -q emits nothing, so the downstream grep couldn't inspect violations. Replaced with anchored active-command matching; the guard now demonstrates both non-detection of comments and detection of a synthetic injected sysctl line (no execution).

Integration / reproducibility: Generator CI now calls bash tools/no-direct-egress-lab/test-guards.sh only in the static+node job, without privilege, netns, network mutations or real field traffic. The preceding CI on intermediate SHA c8418d2 already reported this new step SUCCESS. .gitattributes uses the exact tested LF settings from stacked #360 for Windows/WSL checkouts. README updated for real namespace check and 43 rootless assertions (original 38 + 5). #360 has not been modified.

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.

Copy link
Copy Markdown
Owner Author

Final exact-SHA CI checkpoint — 2026-11-08

HEAD fd187c20ae87b4bf79eced29ea8146eb96c0aa1f, base main=23b851a46b5808a290994dc0c9c22b032b95e266: OPEN DRAFT, mergeable CLEAN, 13 expected test/lab/git hygiene files, no outstanding CHANGES_REQUESTED reviews or unresolved review threads.

  • Generator CI #42508764310 — 6/6 SUCCESS on exact SHA: static+Node (including the new rootless test-guards.sh action), Chromium browser, Firefox, WebKit, pinned Mihomo 1.19.31/1.19.33.
  • Runtime provenance #42508764309 — SUCCESS on the same SHA.
  • New rootless guards exercise synthetic namespace-marker spoofing, private-namespace predicate and forbidden-mutator scanner. These are mock/static checks only, not a re-run of the privileged netns lab.
  • Independent review fixes: don't trust AMG_LAB_INSIDE=1 without comparing real netns inodes; fix inert grep -q | grep -v guard; enforce LF checkouts for WSL and document actual 43 rootless tests. Branch synced to post-feat(i18n): Builder Phase 2A — базовые RU/EN элементы Mihomo Builder (#353) #354 main; no VPS/routers, stable, releases, Pages, generated runtime files changed.

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.

@saymer-alt
saymer-alt marked this pull request as ready for review November 8, 2026 19:46
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-08T19:48:52.293254Z fd187c2 Draft marked ready
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@saymer-alt
saymer-alt merged commit cf44e53 into main Nov 8, 2026
9 checks passed
@saymer-alt
saymer-alt deleted the zai-no-direct-lab-tool branch November 8, 2026 19:47

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +41 to +42
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; }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment on lines +64 to +67
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]),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

saymer-alt added a commit that referenced this pull request Nov 9, 2026
…338

Preserve provider-only DPR implementation, i18n UI and rootless lab guard CI. Review and retest at resulting exact SHA before any merge.
saymer-alt added a commit that referenced this pull request Nov 9, 2026
…352 (#355)

Keep only four DPR-specific lab files on top of current #352 tree. Use merged hardened isolation gate and rootless CI checks from main. Preserve historical runtime evidence SHAs; new CI covers this combined head.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant