Skip to content

test(dpr): netns runtime-proof — provider-only DPR при all-unhealthy A и живом B (#355) - #360

Draft
saymer-alt wants to merge 18 commits into
mainfrom
test/dpr-provider-runtime-355
Draft

saymer-alt wants to merge 18 commits into
mainfrom
test/dpr-provider-runtime-355

Conversation

@saymer-alt

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

Copy link
Copy Markdown
Owner

Актуальное состояние — 09.11.2026, синхронизировано с latest main

  • Этот Draft PR test(dpr): netns runtime-proof — provider-only DPR при all-unhealthy A и живом B (#355) #360: HEAD eec438031a93ebb53197c134783f9dd7adfac9a1, base main=f8f79ce052c5ddff7c3b1f7874fb9604077ac089. Синхронизация произведена отдельным merge-коммитом без force-push. В нём сохранены все лабораторные файлы и добавлен только новый CONTRIBUTING.md из main (docs-only commit f8f79ce).
  • Точный GitHub compare 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, нет конфликтов.
  • Текущая проверка: Generator CI #42676962635 QUEUED при записи этого состояния. Не объявлять PASS до завершения, и не переносить сюда прежний CI как exact-SHA PASS.
  • Evidence reuse: предшествующий 6/6 PASS #42670009690 относится к 9d0e5356. Ранее независимый локальный synthetic netns runtime PASS подтверждён на 4098c81c (Mihomo 1.19.31 и 1.19.33), а новый merge добавил только CONTRIBUTING; это исторические подтверждения в идентичной функциональной области, а не новый runtime-прогон на eec43803 или Field PASS.
  • Наблюдение об инфраструктуре: у main=f8f79ce Generator 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, если повторится.
  • NO MERGE test(dpr): netns runtime-proof — provider-only DPR при all-unhealthy A и живом B (#355) #360 / NO stable / NO release / NO Pages / NO field без отдельного owner GO. Не подтверждены IPv6 DPR path, host firewall/PBR/NAT и реальный VPS.

Текущий интеграционный статус — 09.11.2026 (вечер; runtime netns proof ПОВТОРЁН на этом SHA)


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 на обеих пиновых версиях

Кейс Ожидание Результат
P1: A healthy, B healthy GEMINI строго через A; MATCH,GLOBAL не сломан PASS — endpoint видел только 10.210.0.1; контрольный запрос — только 10.211.0.2
N1: A существует, все его узлы unhealthy (dead payload + provider refresh), B healthy явная ошибка/timeout, не живой endpoint B, не direct PASS — клиент fail-closed (http 502), ноль попаданий probe-пути на endpoint от любого источника; контроль через B работает
R1: восстановление A (live payload + refresh + групповой re-test) GEMINI снова через A PASS — endpoint снова 10.210.0.1
N2: A пуст (cold start) семантика empty-fallback: REJECT, не путать с unhealthy PASS — provider A отдаёт 0 узлов, клиент fail-closed, ноль endpoint-попаданий; B работает
N3: cold start с A all-unhealthy fail-closed PASS — ноль endpoint-попаданий; B работает
Selftest детектора утечки прямой запрос из vps-ns обязан наблюдаться PASS — selftest-direct виден с 10.210.0.3; критерий armed весь прогон
Критерий утечки #338 (dest-хиты с VPS-IP вне selftest, v4+v6) 0 0 во всех прогонах; накопленных FAIL нет

Прогоны (полная матрица каждый раз, LAB-EXIT=0):

  • mihomo v1.19.31 linux amd64 (official compatible build) — VERDICT: PASS, FAILs 0, leaks 0;
  • mihomo v1.19.33 linux amd64 (official compatible build) — VERDICT: PASS, FAILs 0, leaks 0 (+ stability re-run — PASS);
  • дополнительно 1.19.31 (mipsle-сборка owner'а под binfmt) — 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 -n gate первым 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).

Проверки

Наблюдения о рантайм-семантике (INFO, зафиксированы честно)

  • empty-fallback: REJECT действует при пустой группе (N2: 0 узлов); при присутствующем, но unhealthy узле наблюдаемая неудача — dial-ошибка единственного узла провайдера (N1/N3). Оба fail-closed; ни один не выходит через B/direct.
  • После provider refresh provider-only url-test-группа может продолжать звать предыдущий (удалённый, мёртвый) узел до следующего группового теста — интервал health-check (300s в этом конфиге) или API re-test (GET /group/<name>/delay). R1 форсирует re-test для ограниченности прогона; незфорсированный путь — интервальный (задержка восстановления до interval).

NOT TESTED / границы (честно)

CI

Workflow Run Результат
Generator CI 42505836860 success 6/6 (static+node, browser, owner-UX firefox, owner-UX webkit, compat 1.19.31, compat 1.19.33) на head 36cf79a

Локальная netns-лаборатория в CI не запускается (изолированная сеть по контракту #338); CI ветки подтверждает, что merge-дерево (#352+#338+это) не ломает существующие контракты.

Никаких merge, stable, Pages, релизов и закрытия #284/#351 без отдельного owner GO.

saymer-alt and others added 13 commits November 5, 2026 21:47
…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).
Combine provider-only routing with provider name sync and RU/EN foundation; do not change project semantics or runtime generated artifacts.
…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.
…338

Preserve provider-only DPR implementation, i18n UI and rootless lab guard CI. Review and retest at resulting exact SHA before any merge.
…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.

Copy link
Copy Markdown
Owner Author

Independent exact-SHA CI/dependency checkpoint — 2026-11-09

Current Draft PR #360 HEAD c4bf524c9ae940de609c435ca55d4b9bf8ef3b14, base main=cf44e5318f01def5469cccc330240f715213d837, mergeable; parent Draft #352 HEAD 3da32d06fee5d570fba27dd133a5d122d588700b.

saymer-alt and others added 2 commits November 9, 2026 20:31
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.
…ct tree)

Merge parents: existing #360 HEAD and squash merge of #352 into main.
Keep five test-only lab files and preserve all main product blobs unchanged.
No production changes or field claim.

Copy link
Copy Markdown
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.

Copy link
Copy Markdown
Owner Author

Completed exact-HEAD CI checkpoint — 2026-11-09

Draft PR #360 HEAD eec438031a93ebb53197c134783f9dd7adfac9a1, base main=f8f79ce052c5ddff7c3b1f7874fb9604077ac089; GitHub mergeable CLEAN. Its diff vs main remains exactly 5 test-only netns lab files.

This branch has not been deployed

No deployments
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