Repository navigation
test(dpr): netns runtime-proof — provider-only DPR при all-unhealthy A и живом B (#355) - #360
Draft
saymer-alt wants to merge 18 commits into
Draft
saymer-alt wants to merge 18 commits into
saymer-alt wants to merge 18 commits into
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.
…outing (#351) Opt-in DPR card target '🛰 Только <provider>' (PROVIDER:<name>): RULE-SET goes strictly to a provider-only url-test group (use: [chosen provider]); other subscriptions never enter the policy route. Engine receives a SELECT placeholder; applyDprProviderTargets post-patch rewrites the rule, sets empty-fallback REJECT (no-DIRECT #284), removes the unreachable NAME select only when unreferenced. Fail-closed: missing provider/group/rule, Sub Mode OFF, AWL — explicit build errors, no silent fallback. Provider options live in the dialer target registry; project persists PROVIDER:<name>. Tests: tests/dpr-provider-target.cjs (12 node), browser UI regression, mihomo -t parse-only contracts on pinned 1.19.31/1.19.33. SELECT semantics, GLOBAL, MATCH,GLOBAL and no-DIRECT contracts unchanged.
…owns rebuild (#351) CI run 42482521853 deterministic/browser: policyCardDom emitted provider options without the refresh marker, so registry updates left duplicate/ stale unmanaged options. All provider options now carry data-dpr-provider; refreshPolicyProviderOptions rebuilds them consistently. Test predicate for Sub Mode OFF corrected (expects exactly one honest missing-subscription slot).
…icies (#351) Mutate the current proxy-groups array in place; add regression proving both policies keep independent providers and remove both unreferenced SELECT groups.
…llback (#351) Block bare/whitespace-only PROVIDER: targets before they can be normalized into pooled SELECT. Add Node and browser regressions, and clarify that Mihomo empty-fallback covers empty groups, not proven all-unhealthy no-leak behavior.
…#351) Fail-closed malformed provider targets must reset the previous YAML validation result; UI and copy controls must show the failed build. Add browser regression for ERROR and disabled copy.
Preserve strict provider routing and current RU/EN Builder; integrate both UI and CI test suites without changing generated runtime.
… lab (#355) Adds a test-only scenario (no production code changes): - gen-dpr.mjs: builds the actual #352 config (engine + exact applyDprProviderTargets post-patch extracted from index.html) for two synthetic providers + one DPR policy; asserts the provider-only contract statically; one marked LAB-ONLY rewrite of the gstatic health-check URL to an offline lab 204 endpoint (count asserted, routing untouched). - dpr-sub.mjs: stateful provider payload server (live/dead/empty modes) + 204 health endpoint. - dpr-provider-runtime.sh: contained scenario proving at network endpoints that provider-only DPR egresses strictly via the chosen provider and fails closed (no B leak, no direct VPS-IP egress) when it is all-unhealthy or empty; MATCH,GLOBAL control path intact; recovery via provider refresh; leak-detector selftest; fail-closed verdict. - .gitattributes: LF for lab scripts (CRLF checkouts break bash).
- liveness: explicitly wait for dest :8099 / dpr-sub :8097 to listen (fresh node needs ~2s cold start; native mihomo bootstraps faster, so the old flow raced the node services and FATALed at the hop check); keep the process-state dump in the FATAL branch as honest diagnostics. - README-DPR-355.md: dependencies (exact #338 lab + in-tree #352 DPT source), scenario files, matrix, run instructions, observed runtime semantics (empty group vs unhealthy node; url-test re-test after provider refresh) and lab boundaries.
This was referenced Nov 8, 2026
…338 Preserve provider-only DPR implementation, i18n UI and rootless lab guard CI. Review and retest at resulting exact SHA before any merge.
Owner
Author
Independent exact-SHA CI/dependency checkpoint — 2026-11-09Current Draft PR #360 HEAD
|
iproute2 >= 6.x exits nonzero on the idempotent 'ip addr add 127.0.0.1/8 dev lo' (kernel pre-assigns loopback in every fresh netns), so require_lab_isolation aborted with 'cannot address private loopback' on modern WSL2/Ubuntu before any scenario could start. Keep the guard fail-closed: accept the add, or verify the address is present.
Owner
Author
Integration checkpoint after owner GO merge #352 (2026-11-09)
|
Preserve existing 5 lab-only changes and merged #352; integrate main's CONTRIBUTING.md unchanged. No runtime or production change.
Owner
Author
Completed exact-HEAD CI checkpoint — 2026-11-09Draft PR #360 HEAD
|
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Актуальное состояние — 09.11.2026, синхронизировано с latest main
eec438031a93ebb53197c134783f9dd7adfac9a1, basemain=f8f79ce052c5ddff7c3b1f7874fb9604077ac089. Синхронизация произведена отдельным merge-коммитом без force-push. В нём сохранены все лабораторные файлы и добавлен только новыйCONTRIBUTING.mdизmain(docs-only commitf8f79ce).main...#360: ровно 5 lab/test-only файлов (README-DPR-355.md,dpr-provider-runtime.sh,dpr-sub.mjs,gen-dpr.mjs,lib/netns.sh). Никаких дублирующихся изменений реализации из merged PR #352, нет конфликтов.9d0e5356. Ранее независимый локальный synthetic netns runtime PASS подтверждён на4098c81c(Mihomo 1.19.31 и 1.19.33), а новый merge добавил только CONTRIBUTING; это исторические подтверждения в идентичной функциональной области, а не новый runtime-прогон наeec43803или Field PASS.main=f8f79ceGenerator CI #42673542005 и runtime workflow #42673542399 отмечены GitHub какfailure, хотя все зарегистрированные jobs SUCCESS; Generator CI создал только 4 из ожидаемых 6. Причина UNKNOWN; единственное изменениеmainпосле feat(dpr): provider-only policy target — strict single-subscription routing (#351) #352 —CONTRIBUTING.md. Не выдавать это ни за доказанный defect Builder, ни за CI PASS. Нужен отдельный triage, если повторится.Текущий интеграционный статус — 09.11.2026 (вечер; runtime netns proof ПОВТОРЁН на этом SHA)
4098c81c2dcf9758d661251f921c419d31f4d4a2;main=cf44e531…(содержит MERGED test(no-direct): synthetic netns field-test tool for #284 (test-only) #338); feat(dpr): provider-only policy target — strict single-subscription routing (#351) #352 head3da32d06…— не изменён.4098c81и PASS на обеих пиновых версиях Mihomo (синтетическая netns-лаборатория test(no-direct): synthetic netns field-test tool for #284 (test-only) #338, WSL2 Ubuntu, kernel 6.18, официальныйmihomo-linux-amd64-compatible, SHA256 сверены с пинами CI):VERDICT: PASS, accumulated FAILs 0, non-selftest direct-egress hits 0 (v4+v6), LAB-EXIT=0;VERDICT: PASS, accumulated FAILs 0, non-selftest direct-egress hits 0 (v4+v6), LAB-EXIT=0.Матрица P1/N1/R1/N2/N3 + обязательный selftest детектора утечки — все PASS. Endpoint evidence: позитивные GEMINI-запросы наблюдались на dest-endpoint только с ожидаемых synthetic-выходов (via A
10.210.0.1, контроль MATCH,GLOBAL via B10.211.0.2); все негативные пути (all-unhealthy A, пустой A, cold-start dead A) — ноль попаданий на endpoint от любого источника при явной клиентской ошибке (http 502); selftest direct-запрос наблюдался с10.210.0.3(критерий armed весь прогон). Полная матрица и условия применимости: комментарий в Issue #355.tools/no-direct-egress-lab/lib/netns.sh): на современных iproute2 (≥6.x, измерено на 6.19.0/kernel 6.18 WSL2) идемпотентныйip addr add 127.0.0.1/8 dev loв свежем netns возвращает rc=2 (адрес пре-назначен ядром), из-за чего gaterequire_lab_isolationблокировал запуск лаборатории («FATAL: cannot address private loopback») до любого сценария. Коммит4098c81сохраняет gate fail-closed: принимает успешный add или верифицирует фактическое наличие адреса. Продуктовый код feat(dpr): provider-only policy target — strict single-subscription routing (#351) #352 и остальные файлы test(no-direct): synthetic netns field-test tool for #284 (test-only) #338 не тронуты; diff относительно feat(dpr): provider-only policy target — strict single-subscription routing (#351) #352 — 4 test-only файла test(dpr): netns runtime-proof provider-only при all-unhealthy A и живом B (#351/#284) #355 + эта правка общего lib/.4098c81: Generator CI run 42665476970 — success (static+node, browser, owner-UX firefox/webkit, mihomo compat 1.19.31, compat 1.19.33, stacked provenance); update-web4core — success (no-diff); portable-hwid — skipped (как и прежде).warp://-провайдеры. Один PASS лаборатории не доказывает host-level защиту на настоящем VPS — отдельный packet-path/field этап (BLOCKED до owner GO).test(dpr): runtime-proof provider-only DPR при отказе выбранного провайдера (#355)
Draft. Merge только после отдельного owner GO. Test-only: продакшн-код не меняется.
Branch
test/dpr-provider-runtime-355, stacked: основан на head Draft PR #352 (af8a5f6bb9bda10497447cfd65e16a0bf24923b5, содержитmainпосле i18n #354) + merge head Draft PR #338 (b3ac7838b8b34517dabdc0dddef77e7813ead972, netns-лаборатория #284) + 2 коммита этого PR. История #338 и #352 не переписывалась и не редактировалась — только merge + новые файлы. Оба PR остаются независимыми; после их merge diff этого PR сведётся к тестовым файлам.Что доказано (runtime, endpoint-наблюдения — не YAML и не
mihomo -t)Strict provider-only DPR из #352: политика с целью
PROVIDER:<A>выходит только через узлы провайдера A; при отказе A — fail-closed, никогда через живого провайдера B и никогда напрямую с VPS-IP. Тестируется фактический конфиг #352: движок (web4core.runtime.js) → карточка как SELECT-плейсхолдер → точный пост-патчapplyDprProviderTargets, извлечённый изindex.htmlэтой ветки по DPT-маркерам (тот же код, что в браузере), со статическими ассертами контракта (GEMINI-AUTO use:[A],empty-fallback: REJECT, правило наGEMINI-AUTO,MATCH,GLOBALпоследним).Наблюдаемые user-plane выходы GEMINI-запроса:
10.210.0.1(узел A, root-ns stand-in) /10.211.0.2(узел B, egress ns) /10.210.0.3(напрямую с VPS-IP — терминальный провал вердикта).Матрица результатов — VERDICT: PASS на обеих пиновых версиях
MATCH,GLOBALне сломан10.210.0.1; контрольный запрос — только10.211.0.210.210.0.1empty-fallback: REJECT, не путать с unhealthyselftest-directвиден с10.210.0.3; критерий armed весь прогонПрогоны (полная матрица каждый раз,
LAB-EXIT=0):VERDICT: PASS, FAILs 0, leaks 0;VERDICT: PASS, FAILs 0, leaks 0 (+ stability re-run — PASS);Файлы (только новые; ни один файл #338/#352 не изменён)
tools/no-direct-egress-lab/gen-dpr.mjs— конфиг через реальный pipeline feat(dpr): provider-only policy target — strict single-subscription routing (#351) #352 + статические ассерты; одна помеченная LAB-ONLY замена: gstatic health-check URL (4 вхождения, count asserted) → lab 204-эндпоинт (лаборатория оффлайн по дизайну); groups/use/rules/empty-fallback не тронуты.tools/no-direct-egress-lab/dpr-sub.mjs— stateful-сервер payload'ов провайдера A (live/dead/empty по mode-файлу) +/sub-b+/hc204.tools/no-direct-egress-lab/dpr-provider-runtime.sh— сценарий: изоляция test(no-direct): synthetic netns field-test tool for #284 (test-only) #338 (unshare -ngate первым side-effect'ом, безымянные child-ns по PID, ownership-очистка, никаких host-мутаций), матрица, endpoint-ассерты негативов (ноль попаданий probe-пути от любого источника), fail-closed вердиктlib/verdict.sh.tools/no-direct-egress-lab/README-DPR-355.md— документация: зависимости с SHA, источник YAML, матрица, запуск, наблюдения, границы..gitattributes—eol=lfдля lab-скриптов (CRLF-checkout ломает bash; лаборатория test(no-direct): synthetic netns field-test tool for #284 (test-only) #338 не запускалась бы с Windows-checkout).Проверки
test-guards.sh(test(no-direct): synthetic netns field-test tool for #284 (test-only) #338) на этой ветке — GUARDS: ALL PASS (38 проверок гигиены/вердикта).tests/dpr-provider-target.cjs(feat(dpr): provider-only policy target — strict single-subscription routing (#351) #352) на этой ветке — 14 passed, 0 failed.Наблюдения о рантайм-семантике (INFO, зафиксированы честно)
empty-fallback: REJECTдействует при пустой группе (N2: 0 узлов); при присутствующем, но unhealthy узле наблюдаемая неудача — dial-ошибка единственного узла провайдера (N1/N3). Оба fail-closed; ни один не выходит через B/direct.url-test-группа может продолжать звать предыдущий (удалённый, мёртвый) узел до следующего группового теста — интервал health-check (300s в этом конфиге) или API re-test (GET /group/<name>/delay). R1 форсирует re-test для ограниченности прогона; незфорсированный путь — интервальный (задержка восстановления до interval).NOT TESTED / границы (честно)
warp://-провайдеры вне скоупа (DPR-карточки — URL-подписки); реальные VPS/подписки/роутеры не затрагивались; fixtures синтетические (*.example.invalid-стиль, TEST-NET-1, fd00::/8, lab.local).web4core.runtime.js, Builder, provider overrides,x-hwid, правила no-DIRECT, проектный формат — не тронуты.CI
36cf79aЛокальная netns-лаборатория в CI не запускается (изолированная сеть по контракту #338); CI ветки подтверждает, что merge-дерево (#352+#338+это) не ломает существующие контракты.
Никаких merge, stable, Pages, релизов и закрытия #284/#351 без отдельного owner GO.