diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fbff9d5..65e10f5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,101 +1,165 @@ -name: NetPreference MVP +name: NetPreference verify and SDK on: push: - branches: [feat/mvp] - paths: ['.bootstrap/READY', 'cmd/**', 'internal/**', 'tests/**', 'scripts/**', 'files/**', 'packaging/**', 'openwrt/**', 'go.mod', '.github/workflows/**'] + branches: ['**'] + paths: ['cmd/**', 'internal/**', 'tests/**', 'scripts/**', 'files/**', 'packaging/**', 'openwrt/**', 'go.mod', '.github/workflows/**', 'LICENSE', 'docs/LICENSE-Go'] pull_request: workflow_dispatch: permissions: - contents: write + contents: read concurrency: - group: netpreference-${{ github.ref }} + group: netpreference-${{ github.workflow }}-${{ github.ref }} cancel-in-progress: false jobs: verify: runs-on: ubuntu-24.04 - timeout-minutes: 20 + timeout-minutes: 25 steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 with: fetch-depth: 0 - - name: Materialize checked source transport - if: github.event_name == 'push' && hashFiles('.bootstrap/READY') != '' - shell: bash - run: | - set -euo pipefail - python3 - <<'PY' - import base64, hashlib, io, lzma, pathlib, tarfile - root=pathlib.Path('.') - encoded=''.join(p.read_text().strip() for p in sorted(root.glob('.bootstrap/part-*.b64'))) - data=base64.b64decode(encoded,validate=True) - expected=(root/'.bootstrap/READY').read_text().strip() - assert hashlib.sha256(data).hexdigest()==expected, 'source transport checksum mismatch' - with tarfile.open(fileobj=io.BytesIO(lzma.decompress(data)),mode='r:') as archive: - for member in archive.getmembers(): - path=pathlib.PurePosixPath(member.name) - assert member.isfile() and not path.is_absolute() and '..' not in path.parts - assert path.parts[0] not in ('.git','.github','.bootstrap','dist') - assert not member.name.startswith('docs/failures/') - archive.extractall('.',filter='data') - PY - git config user.name 'github-actions[bot]' - git config user.email '41898282+github-actions[bot]@users.noreply.github.com' - git rm -r .bootstrap - git add README.md LICENSE .gitignore go.mod cmd internal files packaging scripts tests openwrt docs - git commit -m 'feat: materialize tested NetPreference 0.1.0 MVP source' - git push origin HEAD:feat/mvp + persist-credentials: false - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 - if: hashFiles('go.mod') != '' with: go-version: stable cache: false - - name: Unit, wire behavior, fuzz, package and static checks + - run: mkdir -p dist/logs + - name: Unit, real DNS wire, race, fuzz, LuCI and package checks id: core - if: hashFiles('go.mod') != '' shell: bash run: | set -o pipefail - mkdir -p dist/logs bash scripts/check.sh 2>&1 | tee dist/logs/core.txt - - name: Install isolated kernel-lab dependencies - if: hashFiles('go.mod') != '' + - name: Install isolated kernel-lab tools + id: kernel_tools run: sudo apt-get update && sudo apt-get install -y nftables conntrack iproute2 - - name: Real dual-stack nftables and crash recovery + - name: Real IPv4/IPv6 redirects, profiles, recovery and NAT66 preservation id: kernel - if: hashFiles('go.mod') != '' shell: bash run: | set -o pipefail sudo python3 tests/netns.py 2>&1 | tee dist/logs/kernel.txt - - name: Target userspace opkg install and remove - id: rootfs - if: hashFiles('go.mod') != '' - continue-on-error: true + - name: Install pinned browser test runner + id: browser_tools + run: | + python3 -m pip install playwright==1.57.0 + python3 -m playwright install --with-deps chromium + - name: Chromium mode-set interactions and real backend validation + id: browser shell: bash run: | set -o pipefail - sudo bash tests/rootfs_install.sh 2>&1 | tee dist/logs/rootfs.txt - - name: Commit each failed phase separately - if: always() && github.event_name == 'push' && hashFiles('scripts/ci_failure.py') != '' + python3 tests/luci_browser.py 2>&1 | tee dist/logs/browser.txt + - name: Build the fixed r6 source for actual upgrade testing + id: legacy shell: bash + run: | + set -o pipefail + bash scripts/build_legacy.sh 2>&1 | tee dist/logs/legacy.txt + - name: Capture phase outcomes + if: always() env: CORE_RESULT: ${{ steps.core.outcome }} + KERNEL_TOOLS_RESULT: ${{ steps.kernel_tools.outcome }} KERNEL_RESULT: ${{ steps.kernel.outcome }} - ROOTFS_RESULT: ${{ steps.rootfs.outcome }} + BROWSER_TOOLS_RESULT: ${{ steps.browser_tools.outcome }} + BROWSER_RESULT: ${{ steps.browser.outcome }} + LEGACY_RESULT: ${{ steps.legacy.outcome }} run: | - for phase in core kernel rootfs; do - var="${phase^^}_RESULT" - if [ "${!var}" = failure ]; then python3 scripts/ci_failure.py "$phase"; fi - done - - name: Upload package and exact verification logs - if: always() && hashFiles('dist/*.ipk') != '' + mkdir -p dist/logs + python3 - <<'PY' + import json,os,pathlib + pathlib.Path('dist/outcomes.json').write_text(json.dumps({k[:-7].lower():v for k,v in os.environ.items() if k.endswith('_RESULT')})) + PY + - name: Upload exact verification evidence + if: always() uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 with: - name: netpreference-mvp-${{ github.run_id }} + name: netpreference-verification-${{ github.run_id }} path: | dist/*.ipk dist/SHA256SUMS dist/build-info.json dist/coverage.out + dist/outcomes.json dist/logs/ + dist/browser/ + dist/kernel-traffic.json + dist/ux-generated.uci retention-days: 30 + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + if: success() + with: + name: netpreference-legacy-${{ github.run_id }} + path: dist-legacy/*.ipk + retention-days: 7 + + sdk: + needs: verify + uses: ./.github/workflows/sdk-build.yml + with: + legacy_artifact: netpreference-legacy-${{ github.run_id }} + + record-failures: + needs: [verify, sdk] + if: always() && github.event_name == 'push' && github.ref != 'refs/heads/main' && (needs.verify.result == 'failure' || needs.sdk.result == 'failure') + runs-on: ubuntu-24.04 + timeout-minutes: 5 + permissions: + contents: write + actions: read + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + with: + ref: ${{ github.ref_name }} + fetch-depth: 0 + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 + with: + pattern: netpreference-* + path: .ci-artifacts + - name: One failure document and commit per failed phase + run: | + python3 - <<'PY' + import json,pathlib,subprocess + for report in sorted(pathlib.Path('.ci-artifacts').rglob('outcomes.json')): + for phase,result in json.loads(report.read_text()).items(): + if result == 'failure': + subprocess.run(['python3','scripts/ci_failure.py',phase,str(report.parent/'logs'/f'{phase}.txt')],check=True) + PY + + release: + needs: [verify, sdk] + if: github.event_name == 'push' && github.ref == 'refs/heads/main' + runs-on: ubuntu-24.04 + timeout-minutes: 5 + permissions: + contents: write + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + with: + persist-credentials: false + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 + with: + name: netpreference-immortalwrt-sdk-${{ github.run_id }} + path: dist-sdk + - name: Publish only a fully verified main push + env: + GH_TOKEN: ${{ github.token }} + shell: bash + run: | + set -euo pipefail + VERSION=$(sed -n 's/^PKG_VERSION:=//p' openwrt/luci-app-netpreference/Makefile) + REV=$(sed -n 's/^PKG_RELEASE:=//p' openwrt/luci-app-netpreference/Makefile) + TAG="v$VERSION" + (cd dist-sdk && sha256sum -c SHA256SUMS) + if gh release view "$TAG" >/dev/null 2>&1; then + echo "Release $TAG already exists; never overwrite an existing release." + exit 0 + fi + printf '%s\n' "NetPreference $VERSION-r$REV" "" \ + "Per-device defaults, named profiles/domain sets, domain-specific IPv4/IPv6 preference and inherited A/B." \ + "Official ImmortalWrt 24.10.4 x86_64 SDK package. Verification and SDK jobs passed for $GITHUB_SHA." \ + "Includes r6 config-preserving opkg upgrade and isolated dual-stack recovery tests." \ + "DNS timing is a preference, not forced IPv6. Target-router/LuCI browser acceptance remains separate." > "$RUNNER_TEMP/release-notes.md" + gh release create "$TAG" dist-sdk/*.ipk dist-sdk/SHA256SUMS dist-sdk/build-info.json \ + --target "$GITHUB_SHA" --title "NetPreference $VERSION" --notes-file "$RUNNER_TEMP/release-notes.md" diff --git a/.github/workflows/sdk-build.yml b/.github/workflows/sdk-build.yml index 3a991cc..b72ace4 100644 --- a/.github/workflows/sdk-build.yml +++ b/.github/workflows/sdk-build.yml @@ -1,22 +1,14 @@ name: ImmortalWrt SDK package - on: - push: - branches: [feat/mvp, main] - paths: - - '.github/workflows/sdk-build.yml' - - 'openwrt/**' - - 'cmd/**' - - 'internal/**' - - 'files/**' - - 'packaging/**' - - 'go.mod' - - 'LICENSE' + workflow_call: + inputs: + legacy_artifact: + type: string + required: false + default: '' workflow_dispatch: - permissions: - contents: write - + contents: read jobs: sdk-package: runs-on: ubuntu-24.04 @@ -24,114 +16,99 @@ jobs: env: SDK_URL: https://downloads.immortalwrt.org/releases/24.10.4/targets/x86/64/immortalwrt-sdk-24.10.4-x86-64_gcc-13.3.0_musl.Linux-x86_64.tar.zst SDK_SHA256: 4f5de9da8674d4acdb6bd2afe594ea079c9983690d9e2eb1661a99b8fcd7d270 - steps: - - name: Checkout - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 - - - name: Install host tools - run: | - sudo apt-get update - sudo apt-get install -y zstd rsync - - - name: Download and verify ImmortalWrt SDK + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + with: + fetch-depth: 0 + persist-credentials: false + - run: mkdir -p dist-sdk/logs + - name: Download prior-version upgrade fixture from verified job + if: inputs.legacy_artifact != '' + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 + with: + name: ${{ inputs.legacy_artifact }} + path: dist-legacy + - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 + if: inputs.legacy_artifact == '' + with: + go-version: stable + cache: false + - name: Prepare legacy fixture for standalone manual SDK build + if: inputs.legacy_artifact == '' + run: bash scripts/build_legacy.sh + - name: Install SDK host tools + id: sdk_tools + run: sudo apt-get update && sudo apt-get install -y zstd rsync + - name: Download and verify the official SDK + id: sdk_download shell: bash run: | set -euo pipefail mkdir -p "$RUNNER_TEMP/immortalwrt-sdk" - curl -fL --retry 3 --retry-delay 2 "$SDK_URL" -o "$RUNNER_TEMP/sdk.tar.zst" - echo "$SDK_SHA256 $RUNNER_TEMP/sdk.tar.zst" | sha256sum -c - + curl -fL --retry 3 --retry-delay 2 "$SDK_URL" -o "$RUNNER_TEMP/sdk.tar.zst" 2>&1 | tee dist-sdk/logs/sdk_download.txt + echo "$SDK_SHA256 $RUNNER_TEMP/sdk.tar.zst" | sha256sum -c - | tee -a dist-sdk/logs/sdk_download.txt tar --zstd -xf "$RUNNER_TEMP/sdk.tar.zst" -C "$RUNNER_TEMP/immortalwrt-sdk" - SDK_DIR="$(find "$RUNNER_TEMP/immortalwrt-sdk" -mindepth 1 -maxdepth 1 -type d -print -quit)" + SDK_DIR=$(find "$RUNNER_TEMP/immortalwrt-sdk" -mindepth 1 -maxdepth 1 -type d -print -quit) test -n "$SDK_DIR" echo "SDK_DIR=$SDK_DIR" >> "$GITHUB_ENV" - echo "Using SDK: $SDK_DIR" - - - name: Prepare SDK Go feed + - name: Prepare official Go packaging helper + id: sdk_feed shell: bash run: | set -euo pipefail cd "$SDK_DIR" - # NetPreference ships LuCI JS/static files directly. We only need the - # Go build helper from packages; luci-base and the other OpenWrt - # components remain runtime dependencies on the target router. - ./scripts/feeds update packages - ./scripts/feeds install golang - - - name: Register NetPreference package + ./scripts/feeds update packages 2>&1 | tee "$GITHUB_WORKSPACE/dist-sdk/logs/sdk_feed.txt" + ./scripts/feeds install golang 2>&1 | tee -a "$GITHUB_WORKSPACE/dist-sdk/logs/sdk_feed.txt" + git -C feeds/packages rev-parse HEAD > "$GITHUB_WORKSPACE/dist-sdk/packages-feed-commit.txt" + - name: Build and inspect official SDK IPK + id: sdk_build shell: bash run: | set -euo pipefail cd "$SDK_DIR" - rm -rf package/luci-app-netpreference ln -s "$GITHUB_WORKSPACE/openwrt/luci-app-netpreference" package/luci-app-netpreference - make defconfig - - - name: Build with official SDK + make defconfig 2>&1 | tee "$GITHUB_WORKSPACE/dist-sdk/logs/sdk_build.txt" + make package/luci-app-netpreference/clean V=s NETPREFERENCE_SRC="$GITHUB_WORKSPACE" 2>&1 | tee -a "$GITHUB_WORKSPACE/dist-sdk/logs/sdk_build.txt" + make package/luci-app-netpreference/compile V=s NETPREFERENCE_SRC="$GITHUB_WORKSPACE" -j"$(nproc)" 2>&1 | tee -a "$GITHUB_WORKSPACE/dist-sdk/logs/sdk_build.txt" + PKG=$(find bin -type f -name 'luci-app-netpreference_*.ipk' -print -quit) + test -n "$PKG" + cp "$PKG" "$GITHUB_WORKSPACE/dist-sdk/" + cd "$GITHUB_WORKSPACE" + python3 scripts/inspect_ipk.py dist-sdk/*.ipk > dist-sdk/build-info.json + python3 - <<'PY' + import json,os,pathlib + p=pathlib.Path('dist-sdk/build-info.json');d=json.loads(p.read_text()) + d.update(sdk_url=os.environ['SDK_URL'],sdk_sha256=os.environ['SDK_SHA256'],packages_feed_commit=pathlib.Path('dist-sdk/packages-feed-commit.txt').read_text().strip()) + p.write_text(json.dumps(d,indent=2)+'\n') + PY + git archive HEAD | gzip -n > dist-sdk/source.tar.gz + (cd dist-sdk && sha256sum *.ipk > SHA256SUMS) + cat dist-sdk/build-info.json + - name: Official target userspace install and r6 upgrade + id: sdk_rootfs shell: bash run: | set -euo pipefail - cd "$SDK_DIR" - make package/luci-app-netpreference/clean V=s NETPREFERENCE_SRC="$GITHUB_WORKSPACE" - make package/luci-app-netpreference/compile V=s NETPREFERENCE_SRC="$GITHUB_WORKSPACE" -j"$(nproc)" - PKG="$(find bin -type f -name 'luci-app-netpreference_*.ipk' -print -quit)" - test -n "$PKG" - mkdir -p "$GITHUB_WORKSPACE/dist-sdk" - cp "$PKG" "$GITHUB_WORKSPACE/dist-sdk/" - ( - cd "$GITHUB_WORKSPACE/dist-sdk" - sha256sum *.ipk > SHA256SUMS - ) - echo "Built package:" - ls -lh "$GITHUB_WORKSPACE/dist-sdk" - cat "$GITHUB_WORKSPACE/dist-sdk/SHA256SUMS" - - - name: Upload SDK-built IPK + PKG=$(find "$GITHUB_WORKSPACE/dist-sdk" -name '*.ipk' -print -quit) + sudo env NETPREFERENCE_IPK="$PKG" bash tests/rootfs_install.sh 2>&1 | tee dist-sdk/logs/sdk_rootfs.txt + - name: Capture SDK phase outcomes + if: always() + env: + SDK_TOOLS_RESULT: ${{ steps.sdk_tools.outcome }} + SDK_DOWNLOAD_RESULT: ${{ steps.sdk_download.outcome }} + SDK_FEED_RESULT: ${{ steps.sdk_feed.outcome }} + SDK_BUILD_RESULT: ${{ steps.sdk_build.outcome }} + SDK_ROOTFS_RESULT: ${{ steps.sdk_rootfs.outcome }} + run: | + mkdir -p dist-sdk/logs + python3 - <<'PY' + import json,os,pathlib + pathlib.Path('dist-sdk/outcomes.json').write_text(json.dumps({k[:-7].lower():v for k,v in os.environ.items() if k.endswith('_RESULT')})) + PY + - name: Upload package and evidence (inspect outcomes before installing) + if: always() uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 with: name: netpreference-immortalwrt-sdk-${{ github.run_id }} - path: | - dist-sdk/*.ipk - dist-sdk/SHA256SUMS + path: dist-sdk/ retention-days: 30 - - - name: Publish GitHub release - if: github.ref == 'refs/heads/main' - shell: bash - env: - GH_TOKEN: ${{ github.token }} - run: | - set -euo pipefail - PKG_VERSION="$(sed -n 's/^PKG_VERSION:=//p' openwrt/luci-app-netpreference/Makefile)" - PKG_RELEASE="$(sed -n 's/^PKG_RELEASE:=//p' openwrt/luci-app-netpreference/Makefile)" - test -n "$PKG_VERSION" - test -n "$PKG_RELEASE" - TAG="v$PKG_VERSION" - - if gh release view "$TAG" >/dev/null 2>&1; then - echo "Release $TAG already exists; skipping publication." - exit 0 - fi - - cat > "$RUNNER_TEMP/release-notes.md" <` 构建产物或交付附件取得 `.ipk` 和 `SHA256SUMS`。构建产物同时包含实际编译器版本及测试日志;下载到包并不代表所有现场验收项目已经通过。 +从本仓库 Actions 的 `netpreference-immortalwrt-sdk-` 构建产物或交付附件取得 `.ipk` 和 `SHA256SUMS`。构建产物同时包含实际编译器版本及测试日志;下载到包并不代表所有现场验收项目已经通过。 ```sh # 在路由器上,使用与当前固件匹配的软件源。 cd /tmp sha256sum -c SHA256SUMS opkg update -opkg install ./luci-app-netpreference_0.1.0-1_x86_64.ipk +opkg install ./luci-app-netpreference_0.2.0-r2_x86_64.ipk ``` -依赖 `luci-base`、`rpcd`、`uci`、`firewall4`、`nftables-json`、`ip-full`、`conntrack`。不捆绑安装或删除 nlbwmon;已有 nlbwmon 可直接复用。不要在实机使用 `--force-depends` 或强行安装不匹配内核的软件包。 +依赖 `luci-base`、`rpcd`、`uci`、`firewall4`、`nftables-json`、`ip-full`、`conntrack`。不捆绑安装或删除 nlbwmon;用户已有 nlbwmon 保持不变。不要在实机使用 `--force-depends` 或强行安装不匹配内核的软件包。 -安装后进入 **LuCI → Services / 服务 → NetPreference**。安装默认空闲,不自动选择设备。保持默认上游 `127.0.0.1:53`,确认 LAN 接口(默认 `br-lan`),先添加一台非关键测试设备并点击 **Save & Apply**。界面提供恢复按钮。MVP 页面使用英文标签。 +安装后进入 **LuCI → Services / 服务 → NetPreference**。安装默认空闲,不自动选择设备。保持默认上游 `127.0.0.1:53`,确认 LAN 接口(默认 `br-lan`),先添加一台非关键测试设备并点击 **Save & Apply**。界面提供恢复按钮。页面使用简体中文,分为“设备与流量”和“模式集与域名集”。 ## A/B 的实际定义 @@ -91,6 +114,6 @@ sudo bash tests/rootfs_install.sh 直接打包:`python3 scripts/build_ipk.py`。产物位于 `dist/`,采用 OpenWrt 24.10 的 tar/gzip `.ipk` 布局及静态 linux/amd64 程序。`openwrt/luci-app-netpreference/Makefile` 提供 SDK/feed 集成入口;SDK 构建是否已验证以测试记录为准。 -开发分支:`feat/mvp`。执行计划见 [EXECUTION.md](docs/EXECUTION.md),测试证据与未验证项见 [VERIFICATION.md](docs/VERIFICATION.md),中断失败及恢复记录在 [docs/failures](docs/failures/)。 +开发分支:`feat/0.2.0-policy-profiles`。执行计划见 [EXECUTION-0.2.0.md](docs/EXECUTION-0.2.0.md),测试证据与未验证项见 [VERIFICATION.md](docs/VERIFICATION.md),中断失败及恢复记录在 [docs/failures](docs/failures/)。 -许可证:MIT;编译进程序的 Go 标准库另附其 BSD 许可证。 \ No newline at end of file +许可证:MIT;编译进程序的 Go 标准库另附其 BSD 许可证。 diff --git a/cmd/netpreference/main.go b/cmd/netpreference/main.go index 9b3bcfa..7c384c7 100644 --- a/cmd/netpreference/main.go +++ b/cmd/netpreference/main.go @@ -123,7 +123,7 @@ func run(args []string) error { } } func rpc(ctx context.Context, args []string) error { - methods := map[string]any{"status": map[string]any{}, "devices": map[string]any{}, "traffic": map[string]any{}, "validate": map[string]any{}, "apply": map[string]any{}, "restore": map[string]any{}} + methods := map[string]any{"status": map[string]any{}, "devices": map[string]any{}, "traffic": map[string]any{}, "validate": map[string]any{}, "apply": map[string]any{}, "restore": map[string]any{}, "check_config": map[string]any{"config": ""}} if len(args) == 1 && args[0] == "list" { return json.NewEncoder(os.Stdout).Encode(methods) } @@ -133,23 +133,51 @@ func rpc(ctx context.Context, args []string) error { if _, ok := methods[args[1]]; !ok { return fmt.Errorf("unknown RPC method") } - raw, e := io.ReadAll(io.LimitReader(os.Stdin, 8193)) + text, e := readRPCInput(os.Stdin, args[1]) if e != nil { return e } - if len(raw) > 8192 { - return fmt.Errorf("RPC input too large") + if args[1] == "check_config" { + // Pure parse/validation. This works even with a stopped or broken daemon, + // and never writes UCI or performs DNS/firewall commands. + c, e := np.ParseUCI(text) + if e != nil { + return e + } + return json.NewEncoder(os.Stdout).Encode(map[string]any{"ok": true, "valid": true, "policies": len(c.Policies), "domain_sets": len(c.DomainSets)}) + } + return run([]string{args[1]}) +} + +func readRPCInput(input io.Reader, method string) (string, error) { + limit := int64(8192) + if method == "check_config" { + limit = 2 * 1024 * 1024 + } + raw, e := io.ReadAll(io.LimitReader(input, limit+1)) + if e != nil { + return "", e + } + if int64(len(raw)) > limit { + return "", fmt.Errorf("RPC input too large") } + var v map[string]any if len(raw) > 0 { - var v map[string]any if e = json.Unmarshal(raw, &v); e != nil { - return e + return "", e } - for k := range v { - if k != "ubus_rpc_session" { - return fmt.Errorf("unexpected RPC parameter %q", k) - } + } + for k := range v { + if k != "ubus_rpc_session" && !(method == "check_config" && k == "config") { + return "", fmt.Errorf("unexpected RPC parameter %q", k) } } - return run([]string{args[1]}) + if method == "check_config" { + text, ok := v["config"].(string) + if !ok || text == "" { + return "", fmt.Errorf("config must be nonempty UCI text") + } + return text, nil + } + return "", nil } diff --git a/cmd/netpreference/rpc_test.go b/cmd/netpreference/rpc_test.go new file mode 100644 index 0000000..33023eb --- /dev/null +++ b/cmd/netpreference/rpc_test.go @@ -0,0 +1,32 @@ +package main + +import ( + "strings" + "testing" +) + +func TestRPCInputBoundaries(t *testing.T) { + for _, tc := range []struct { + method, raw string + valid bool + }{ + {"status", `{}`, true}, + {"status", `{"ubus_rpc_session":"session"}`, true}, + {"apply", `{"config":"anything"}`, false}, + {"check_config", `{"config":"config global main"}`, true}, + {"check_config", `{"config":"config global main","ubus_rpc_session":"s"}`, true}, + {"check_config", `{"config":42}`, false}, + {"check_config", `{"path":"/etc/shadow"}`, false}, + {"check_config", `{"config":"ok","command":"true"}`, false}, + {"check_config", `{}`, false}, + {"check_config", `null`, false}, + {"check_config", `[]`, false}, + {"check_config", `{"config":"` + strings.Repeat("a", 2*1024*1024) + `"}`, false}, + {"apply", strings.Repeat(" ", 8193), false}, + } { + _, err := readRPCInput(strings.NewReader(tc.raw), tc.method) + if (err == nil) != tc.valid { + t.Errorf("method=%s len=%d valid=%v error=%v", tc.method, len(tc.raw), tc.valid, err) + } + } +} diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 4f1af08..3a1c439 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -135,13 +135,11 @@ not negative or imaginary rates. Only routed traffic is counted, not LAN-to-LAN bridged traffic or all traffic to the router itself. Flow/hardware offload can bypass these counters; offload is never changed automatically. -Cumulative totals read `nlbw -c json -g mac,family`, summing rx_bytes as download -and tx_bytes as upload. Totals refer to nlbwmon's **active accounting period**, not -lifetime totals, and are limited by its existing collection/configuration. No -`nlbw commit`, reset, enable, disable or package removal is done. When monitoring -is off, this plugin performs no nlbw sampling and installs no traffic counters; -normal DNS/neighbor/watchdog functions remain. Missing nlbwmon shows unavailable -totals rather than invented zero coverage. IPv6 share uses these period totals. +Cumulative totals integrate positive deltas from NetPreference's own nft counters, +separately for IPv4/IPv6 and each direction. They are diagnostic session totals, +not lifetime/billing counters. Disabling monitoring, service restart or counter +rebuild resets the session. nlbwmon is neither read nor configured by r6/0.2.0; +its pre-existing service/database remains independent. Flow offload may undercount. ## 6. Verification and primary references @@ -159,3 +157,36 @@ integrated core, tests and UI, with tools performing actual builds/execution. - LuCI scoped save vs global apply: https://github.com/openwrt/luci/blob/openwrt-24.10/modules/luci-base/htdocs/luci-static/resources/uci.js - OpenWrt IPK archive layout: https://github.com/openwrt/openwrt/blob/openwrt-24.10/scripts/ipkg-build - OpenWrt Go packaging: https://github.com/openwrt/packages/blob/openwrt-24.10/lang/golang/golang-package.mk + +## 7. Named profiles and domain sets (0.2.0) + +`device.profile` optionally selects a named profile. A profile owns timing +`policy` sections and may scope existing DNS `rule` sections. It does not own a +device's baseline or replace device mode/A/B. Missing/unmatched profile policies +leave defaults intact. Sets are flat named lists, globally reusable by profiles. +References are UCI section IDs, not mutable display names. UI profile/set sections +are named (not anonymous) so saving does not remap their IDs. + +Timing selection: choose the highest matching pattern specificity; an exact name +beats its same-length suffix, longer matches beat shorter ones, ties keep UCI +order. A set is scored by its best matching member, not set size or declaration +order. Only the winning policy applies; nil A/B/probe inherits from the device, +while explicit zero/false is retained. All effective device combinations are +validated before network modification. No recursive set/profile inheritance. + +DNS actions remain a separate pass: whole-device block first, then device scope, +pattern specificity, profile scope only on a complete tie, then UCI order. Timing +policies cannot override blocks. Explicit profile DNS actions can intentionally +change content according to this ordering. Local replies remain immediate. + +A/AAAA queries and probes each resolve their own action and upstream. An A-only +upstream override is not reused for AAAA probes. Engine snapshots own deep copies +of all slices/pointers. Evidence keys include the full immutable configuration +fingerprint; late probes from other profiles/configurations cannot leak evidence +across a switch. Equal manager heartbeat snapshots retain their cache. DNS TTL +and address existence still do not prove network reachability. + +Caps: 64 profiles, 128 sets, 256 patterns/set, 4096 total set patterns and 512 +timing policies. Sets compile into exact/suffix indexes; lookup is bounded by DNS +label count. Unknown references, ambiguous selectors and invalid inherited timing +are rejected, rather than silently falling back to a guessed advanced policy. diff --git a/docs/EXECUTION-0.2.0-r2.md b/docs/EXECUTION-0.2.0-r2.md new file mode 100644 index 0000000..62cc66e --- /dev/null +++ b/docs/EXECUTION-0.2.0-r2.md @@ -0,0 +1,32 @@ +# 0.2.0-r2 执行计划 + +基线:`8b03a9adee756e053091ea0163565ca47af06099`(0.2.0-r1);对照:main `38a69cbb529eb8fc1b820fa00d7cc439306112f4`(0.1.0-r6)。本轮在现有 `feat/0.2.0-policy-profiles` 开发,不合并 main、不发布正式 Release、不操作生产路由器。 + +## 1. 取证与基线(已完成) +1.1 固定上述两个 SHA,通过 Actions 源码归档获取完整树。下载与工具入口失败分别记录在 `docs/failures/0.2.0-r2/`,每次独立提交。 +1.2 比较 `internal/netpref/{traffic,firewall,platform,runtime}.go`、RPC、LuCI、打包脚本。重要事实:r6 与 r1 的 traffic/firewall/platform 实现相同;runtime 的变动是校验结果增加库计数。不能在没有实机诊断的情况下宣称已确认一个 r1 独有的计数器算法错误。 +1.3 `go test -race -count=1 ./...` 已通过。容器无常规 GitHub 网络与交互执行会话;使用同步命令,GitHub 连接器写入。真实 netns/SDK 验证由 Actions 执行。 + +## 2. 流量全链修复(负责人:本次执行者;待实现) +2.1 在 `internal/netpref/traffic_test.go` 及新增运行时回归测试中复现:空计数器被报告可用、Apply/设备发现重建清空会话、DNS 健康暂停导致观察不更新。保留红测证据,不把预期复现当作通过。 +2.2 修改 `traffic.go`:明确区分关闭、首样本、有效、缺失计数器/错误;每个协议族独立有效性;重建仅丢弃速率基线、保留已累计值;公开采样错误与缺失项。 +2.3 修改 `runtime.go`:仅 DNS 模式变化时刷新自有集合而非重建所有计数器;真实拓扑变化时重新建立基线;DNS fail-open 不应伪装为监控关闭。所有 nft 操作仍经过已有所有权/健康安全边界,不改共享服务。 +2.4 扩展 `tests/netns.py`:使用真实 IPv4/IPv6 转发流量,两次采样验证四个方向速率、累计、占比、模式切换保留累计。通过 unix control/CLI RPC 检查同一数据,再交给 LuCI 测试渲染。 + +## 3. 用户模型与 LuCI(负责人:本次执行者;待实现) +3.1 新增纯前端库模型 `files/www/luci-static/resources/netpreference/library.js`:自动生成命名 UCI ID;名称和显示与 ID 分离;只在用户新增/编辑输入时把普通域名规范为根域+子域匹配。未编辑的旧精确规则保持原义,避免静默扩大旧 DNS 阻断范围。 +3.2 重做 `view/netpreference/advanced.js`:域名集仅名称+列表;模式集内直接增删/排序无名规则;输入域名或选择域名集、四种模式及可选 A/B;参数留空继承设备,显式 0 保留。高级 DNS action 留在折叠区域,不删旧配置和未知字段。 +3.3 修改 `overview.js`:设备选择模式集只显示名称,保留设备全局策略;流量每族独立展示,状态/错误互不遮蔽;页面不显示内部 ID。 +3.4 为持久化前校验新增只读 `check_config` RPC:接收有界 UCI 文本,调用既有 `ParseUCI`,绝不执行网络或配置修改。LuCI 对整个待保存配置先做后端校验,再提交且仅提交 netpreference;保留原 validate 行为。 +3.5 新增模型/DOM/浏览器测试:中文名称、宽松域名、旧精确语义、重复/空输入、引用删除、A/B 继承与 0、后端拒绝时不 commit、刷新后规则稳定、旧 DNS action 不丢失。 + +## 4. 集成和构建(待执行) +4.1 本地运行 gofmt、Go race/vet、现有 fuzz、包检查、工作流检查、Node 合同测试、Chromium 页面交互测试。失败逐项独立记录并修复。 +4.2 `PKG_RELEASE` 递增至 2,维持 `PKG_VERSION=0.2.0`;通过原生 Git tree/commit 在分支原子提交,保留其它提交,不 force push。 +4.3 保持 feature push/PR 完整验证,SDK 继续使用固定官方 ImmortalWrt 24.10.4 x86_64 归档及校验和;仅 main 可发布正式 Release。移除本轮临时源码快照 workflow。 +4.4 验证 Actions 的真实 netns、官方 SDK、官方目标用户态 opkg 安装/r6 升级/恢复结果。每次失败按阶段独立文档和提交;修复后以对应 source SHA 的成功任务为准。 + +## 5. 交付(待执行) +5.1 取回实际 SDK IPK,校验 SHA256、包内版本/脚本/权限、配置保留行为;提供 IPK、校验和、源码与验证记录。 +5.2 更新本计划实际完成状态和 `VERIFICATION-0.2.0-r2.md`,列出命令、任务链接、失败及恢复、未验证项目。 +5.3 明确测试边界:隔离内核/官方用户态验证不等于已登录用户的真实路由器验收;不把流量软件路径观察声称为 flow offload 全量统计,不将 DNS 时序偏好声称为强制 IPv6。 diff --git a/docs/EXECUTION-0.2.0.md b/docs/EXECUTION-0.2.0.md new file mode 100644 index 0000000..f72c2a3 --- /dev/null +++ b/docs/EXECUTION-0.2.0.md @@ -0,0 +1,54 @@ +# NetPreference 0.2.0 主执行计划与完成记录 + +日期:2026-10-03。基线 `main@38a69cbb529eb8fc1b820fa00d7cc439306112f4` / `0.1.0-r6`;分支 `feat/0.2.0-policy-profiles`;目标 `0.2.0-r1`。本轮助手直接负责高难度核心实现和集成;没有虚构代理或独立审查。 + +授权仅限目标仓库分支、测试和构建,不合并 main、不发布开发 Release、不访问生产路由器。最终运行状态与产物精确来源固定在 [PR #2](https://github.com/LE-saber/NetPreference/pull/2) 验收清单及对应 artifact 的 build-info 中。实现/测试细节见 [验证报告](VERIFICATION-0.2.0.md),操作见 [使用说明](PROFILES-0.2.0.md)。 + +## 1. 取得基线与环境 — 已完成 + +1.1 通过 GitHub 连接器核实 main SHA、版本和写权限,从准确 SHA 建分支。读取 `internal/netpref/{config,policy,runtime,firewall}.go`、LuCI、SDK Makefile 和两份 workflow,提取设备策略、恢复所有权、nft 计数器和升级契约。 +1.2 容器直接网络不可用,采用只读 Actions 源码快照取得完整文件并核验 SHA256。实施后使用校验和保护的临时传输任务写回分支。临时 workflow 和 `.development/` 已从交付树移除。 +1.3 按 `scripts/check.sh` 建立 r6 基线;冷构建工具超时单独记录后分步完成。原 Go 核心覆盖率 76.9%,原功能 tests/fuzz/package/LuCI 契约通过。 +1.4 保留本地原始快照,不用不完整的本地 git 历史覆盖远端。每次导致中断的失败在 `docs/failures/0.2.0/` 独立提交,修复后重测;现有 001–011。 + +## 2. 数据模型与匹配核心 — 已实现并直接验证 + +2.1 修改 `config.go`,新增 `profiles.go`:旧 device 全字段仍是设备默认;新增可选 device.profile、命名 profile、扁平 domain_set 与归属于模式的 policy。旧 rule 保留,可选引用 Profile/DomainSet。 +2.2 Profile 只组织域名覆盖与可选 DNS action,不替换设备默认;无匹配直接回落。直接域名与集合二选一;集合不递归;引用稳定 UCI section ID,名称可单独修改。 +2.3 nullable A/B/probe 区分继承、显式 0、false。只取最具体单条策略,缺省字段直接继承设备,不叠加次优规则。所有实际继承组合要求 A<=750、B<=500、A+B<=1000ms;没有无限等待。 +2.4 集合按实际命中成员具体度排序,精确优先,同分按 UCI 顺序;保留通配包含根域的旧语义。分离配置和查询名规范化;查询不去空白,只作 ASCII 大小写处理和单一根域点规范化。延长 fuzz 发现双尾点重复剥除后,修为幂等并保留反例。DNS wire label 转义防止标签内点/非 ASCII 伪装。 +2.5 DNS action 与时序独立匹配:设备范围优先、然后域名具体度、同分时 Profile 范围和顺序;整机 block 最高,偏好不能解除阻断。本地否定和静态响应立即返回。 +2.6 `policy.go` 采用深拷贝不可变配置快照,A/AAAA 各自解析动作与上游;探测不得借用另一类型的专用上游或绕过阻断;证据缓存按配置隔离,旧在途探测不污染新模式,有效 IPv4 不被偏好删除。 +2.7 失败路径:非法引用、选择器冲突、继承超限在网络修改前拒绝,保留当前有效策略。未改变 `firewall.go` 所有权/恢复协议或共享 DNS/NAT66 配置。 +2.8 验证入口:profiles/profile_behavior/normalization 测试、两个保留的差分 fuzz 反例,以及完整 race、socket、内核实验。 + +## 3. LuCI 与 r6 兼容 — 已实现,现场边界明确 + +3.1 overview 保留设备默认、A/B、概览、流量、Apply/Restore,增加可选 Profile 下拉项;普通设置不被高级规则表挤占。 +3.2 新 advanced 页面四区:命名 Profiles、DomainSets、域名偏好覆盖、原 DNS action。稳定命名引用,留空与显式零区分,旧规则移动展示而非重建。 +3.3 Save 仅提交 netpreference 并验证;Save & Apply 更新当前模式。前端检查悬空引用与时限,后端独立验证;不调用全局 uci.apply。无效保存文件仍需修正,但旧运行策略不被无效 Apply 替换。 +3.4 保留 conffiles,不覆盖整份配置;真实 r6 fixture 检查旧字段/动作。SDK 新包能用正常 opkg 升级,不要求先卸载或用户重建配置。 +3.5 同步二进制、Makefile、包和文档版本;包测试使用确定的当前 IPK,不误选目录残留。8 项包测试及 LuCI Node API 契约通过;真实浏览器和目标路由器 procd 联调不在已完成声明内。 + +## 4. 自动化集成 — 已建立并执行,最终 head 必须重测 + +4.1 `bash scripts/check.sh`:Go race、vet、DNS/UCI fuzz、30 秒双 worker DomainSet fuzz、8 项包测试、5 项 workflow 守卫、LuCI 契约、Python/shell 语法。010 修复后独立 30 秒 fuzz 通过 610275 次;本地 race 核心覆盖率 80.5%;其他检查分步通过。011 记录整条命令的本地工具时限,最终全套以 Actions 为准。 +4.2 真实 UDP/TCP socket 验证不同域名 A/B、双向协议偏好、关闭主动探测、无 AAAA 时保留 IPv4、Profile 切换、旧在途探测和独立上游。 +4.3 `sudo python3 tests/netns.py` 在隔离 runner 验证 IPv4/IPv6 nft 重定向、设备隔离、Profile 切换、无效 reload 保留运行策略、显式 Restore、同 UDP tuple conntrack 恢复、SIGKILL guard、转发计数和原 NAT66 哨兵保留。008 修复测试完成屏障后分支 verify 已通过,最终源码再跑同套。 +4.4 `scripts/build_legacy.sh` 从准确 r6 SHA 构建真实旧包;`tests/rootfs_install.sh` 在官方 24.10.4 rootfs 使用真实 opkg 新装/删除/升级,逐字节核对旧配置,卸载保留用户修改的 conffile。为避免服务进入宿主,跳过在线 hooks;不能声称生产整机生命周期已验收。 +4.5 任何新断言失败均先记录、再定位、修复和重测;不以删测试或放宽断言换绿色。因 010 修改了产品源码,旧成功 IPK 不再作为最终交付。 + +## 5. Actions 与官方 SDK — 已实现,按准确提交验证交付 + +5.1 所有 feature 分支相关代码 push 与 PR 执行完整验证;成功后调用官方 SDK reusable workflow。默认只读;失败记录只在合适的非 main push 分支逐项提交,PR 不写目标分支。 +5.2 固定官方 ImmortalWrt 24.10.4 x86_64 SDK URL/SHA;官方 Go helper 编译静态包。检查包版本、架构、内容、二进制;记录实际 feed commit、source SHA、SHA256、源码快照和日志;SDK 产物必须通过真实 rootfs 升级。 +5.3 首次分支 run 37087556392 已成功证明完整 SDK/安装链路;后续规范化修复必须重新完整构建。最终只交付包含 010 修复且实际通过 verify、SDK/rootfs 的 artifact;run 与包哈希写入 PR 验收清单,不能把排队当作通过。 +5.4 Release 仅允许成功的 main push,已有 Release 不覆盖。feature/PR/手动 SDK 只产出 artifacts。本轮不合并 main,不发布正式版本。 +5.5 核对远端 head、PR、测试对应 SHA;下载官方 artifact,核验 ZIP/IPK 校验和与源码,执行只读 CLI 冒烟;交付包、SHA256、源码快照、使用说明和失败记录。详细执行证据跟随同一 artifact,避免混用不同构建的哈希。 +5.6 若工具读写或构建失败,保留分支和日志,逐次独立提交失败原因,再继续可逆工作。只有真实成功的结果可进入最终报告。 + +## 6. 后续现场验收与非目标 + +未访问用户实体路由器;其指定 LuCI 浏览器、procd 在线升级及 HomeProxy/SmartDNS 整机联调留给现场验收。建议首先在单台非关键设备验证保存/切换/恢复;不把已有隔离测试等同现场已完成。 + +不实现 NAT64、强制 IPv6、DoH/DoT 接管、连接层协议保证、递归集合或复杂 Profile 继承链。保留 r6 自有 nft 会话统计,不恢复 nlbwmon 累计依赖;不改共享 DNS、代理或 NAT66,不自动关闭 offload。 diff --git a/docs/PROFILES-0.2.0.md b/docs/PROFILES-0.2.0.md new file mode 100644 index 0000000..26d91dd --- /dev/null +++ b/docs/PROFILES-0.2.0.md @@ -0,0 +1,132 @@ +# 0.2.0 使用说明:设备默认 + 命名高级模式 + +## 一、最重要的关系 + +每台设备始终保留自己的普通双栈 / IPv6 优先 / IPv4 优先 / 自定义模式、A、B、主动探测及上游设置。选择 Profile 只是叠加该模式下的**域名覆盖**,不是把设备默认配置替换成公共配置。 + +```text +设备自己的默认策略 + └── 可选 Profile(例如“工作模式”) + ├── 域名偏好规则 → 直接域名,或引用一个命名域名集 + └── 可选 DNS 动作 → 直接域名,或引用一个命名域名集 +``` + +没有选择 Profile、没有命中该 Profile 的域名规则:继续使用设备默认。把设备的 Profile 改成“不使用高级模式”即可退出高级偏好,不需要重新填写默认 A/B。原有不属于任何 Profile 的 DNS action 仍然生效。 + +一个 Profile 可以给多台设备共用;未填写的字段分别继承各台设备的默认,因此同一个模式在不同设备上可以得到不同的 A/B。DomainSet 是可跨 Profile 共用的命名集合;修改共享集合会影响所有引用它的规则。当前不提供递归集合、Profile 继承链或自动复制模式。 + +## 二、LuCI 操作 + +入口:**服务 → NetPreference → 设备与状态 / 高级模式与域名集**。 + +普通用户只使用设备页即可。原有状态、设备默认、流量监控、Apply / Restore 都保留;设备编辑项增加可选的“高级模式 / Profile”。高级页面把复杂配置单独分为四部分: + +1. **命名模式 / Profiles**:新建稳定 ID,例如 `work`,填写显示名称“工作模式”。ID 使用 1–64 位字母、数字或下划线;名称可用中文。引用的是 ID,修改显示名称不会断开引用。 +2. **命名域名集 / DomainSets**:新建 `media`,名称“影音站点”,一行一个域名或通配模式。 +3. **域名偏好覆盖**:选择 Profile,直接填写域名或选择集合(二选一),选择偏好,按需在编辑窗口填写 A/B 和主动探测。留空不是零,而是继承设备。 +4. **DNS 动作**:原有域名 DNS 规则移到这里;没有丢失旧规则。可选 Profile 限定;留空则维持原来的常驻规则。 + +高级页 **Save** 保存模式库并验证,不切换当前运行策略;回到设备页选择模式后 **Save & Apply**。高级页 **Save & Apply** 则同时应用当前设备已经选择的模式。修改已被设备使用的共享 Profile 时,“应用”会更新这些设备。 + +保存只提交 `netpreference` 自身的 UCI 包,不调用全局 `uci.apply()`,不会顺带应用其他网络页面未提交的修改。前端检查悬空引用、选择器冲突和继承时限;后端仍独立验证。无效配置不能替换正在运行的有效策略。若后端报告保存文件中的其他错误,应按提示修复;不要把错误提示当作已应用成功。 + +删除 Profile 或 DomainSet 前,先移除设备/规则对它的引用;直接删除仍被引用的条目会被拒绝。模式库可在尚未分配给设备时先创建好。 + +## 三、域名与优先级 + +- `example.com`:仅该域名。 +- `*.example.com`:**包含 example.com 本身和所有下级域名**,保持 0.1.0 的既有语义;不会匹配 `notexample.com`。 +- `*`:全部域名;用于模式的默认覆盖时要有意选择。 +- 配置大小写与单个结尾根域点会规范化;国际化域名使用 punycode。禁止空通配后缀 `*.`、空标签、递归集合。 + +**偏好规则**只在设备选择的 Profile 中竞争,按命中域名的具体度排序;精确域名胜过同根通配,集合使用本次命中的最具体成员。完全同分按 UCI / LuCI 列表顺序,只选一条。没有多条规则逐级叠加:胜出规则未设置的字段直接回到设备默认。 + +**DNS action**与偏好分开匹配:先设备范围,再域名具体度,完全同分时 Profile 限定的 action 优先,最后按列表顺序。设备整机 block 最高;时序偏好不能解除 NXDOMAIN、NODATA 等内容策略。显式创建更高优先级 DNS action 是另外一回事,不是偏好规则的副作用。 + +所有“全局”规则仍只影响已经加入本插件的设备。未选择设备保持原 DNS 链路,不因创建 Profile / DomainSet 被自动接管。 + +## 四、A/B 与继承 + +A:从非首选地址查询进入策略处理起,等待首选地址证据的有限窗口;不是每次查完上游后再额外睡眠 A。 + +B:只有确认首选地址记录存在,才给非首选地址答复增加延迟,并受 A+B 总窗口限制。没有首选地址记录时保留有效的另一族答复,不无限等待、不默认删除 IPv4。 + +| 高级规则输入 | 结果 | +|---|---| +| 模式“继承设备默认” | 保持该设备的模式,仍可单独覆盖 A/B/探测 | +| A 或 B 留空 | 继承设备对应数值 | +| A 或 B 填 0 | 明确设为零,不会被默认值替代 | +| 主动探测“继承设备” | 使用设备开关 | +| 主动探测“关闭” | 明确关闭,即使设备开启 | +| 自定义模式、首选协议留空 | 继承设备有效首选族;IPv4/IPv6 优先设备按其实际族继承 | +| 普通双栈 | 不人为增加 A/AAAA 偏好延迟 | + +继承后的每个组合均要求 `0≤A≤750 ms`、`0≤B≤500 ms`、`A+B≤1000 ms`。后端检查所有已引用的设备以及尚未分配模式的默认组合。A/B 不改变原有普通上游超时;本地静态重写、拒绝和否定答复立即返回,不再附加时序。 + +主动探测使用首选查询类型自己的 DNS action 和上游,不能绕过该类型的阻断,也不会把只适用于 A 的上游自动拿来查询 AAAA。切换 Profile 后证据缓存按配置隔离,旧的在途探测不能污染新模式。 + +## 五、一个完整例子 + +目标:工作电脑默认 IPv4 优先,A=75、B=40;影音集合 IPv6 优先,A=250、B=150;其中一个会议域名仍 IPv4 优先,A=40、B=20。 + +下面是配置结构示例,**不是要求覆盖你现有的整个 `/etc/config/netpreference` 文件**。真实 MAC、接口和原有 global / device 项应保留,建议通过 LuCI 编辑。 + +```uci +config device 'workstation' + option mac '02:00:00:00:00:01' + option mode 'ipv4' + option wait_ms '75' + option delay_ms '40' + option profile 'work' + +config profile 'work' + option name '工作模式' + +config domain_set 'media' + option name '影音站点' + list domain '*.example.com' + list domain 'video.example.net' + +config policy 'media_v6' + option profile 'work' + option domain_set 'media' + option mode 'ipv6' + option wait_ms '250' + option delay_ms '150' + +config policy 'meeting_v4' + option profile 'work' + option domain 'meeting.example.com' + option mode 'ipv4' + option wait_ms '40' + option delay_ms '20' +``` + +`video.example.com` 命中影音集合;`meeting.example.com` 的精确规则更具体;`unlisted.example.org` 没有命中,仍使用电脑的 IPv4 默认 75/40。另一台默认双栈设备选择同一工作模式后,未命中的域名仍双栈。 + +切换到另一个已保存的 Profile,只需改设备的 Profile 下拉项并应用;不需要逐条改域名规则。 + +## 六、从 0.1.0-r6 升级 + +新包版本为 `0.2.0-r1`。使用官方 SDK 的 x86_64 构建包,正常执行 `opkg install` 升级即可,不需要先卸载,不需要重建配置。`/etc/config/netpreference` 继续声明为 conffile;旧 device / rule 原字段和原动作语义保留。旧配置没有 Profile 选项,升级后自然继续使用原设备默认和原 DNS action。 + +```sh +cd /tmp +sha256sum -c SHA256SUMS +opkg install ./luci-app-netpreference_0.2.0-r1_x86_64.ipk +netpreference version +``` + +不要加 `--force-maintainer` 去替换已修改的配置,也不要使用 `--force-depends` 掩盖不匹配的系统依赖。安装会重启本插件及刷新 rpcd;DNS 客户端可能需要重试正在进行的请求,不能承诺升级零中断。保留现有配置后刷新 LuCI 页面。 + +恢复仍用 `netpreference restore` 或页面 Restore,仅删除本插件所有权范围内的拦截,不回写旧版整份系统配置。HomeProxy、SmartDNS、NAT66、dnsmasq、nlbwmon 不被改写或卸载。流量统计继续采用 r6 的插件自身 nft 会话计数,不恢复 nlbwmon 累计依赖。 + +## 七、构建与验证边界 + +所有 feature 分支的相关代码提交和 PR 都执行完整验证,再调用官方 ImmortalWrt 24.10.4 SDK。开发分支只提供 Actions artifacts;正式 Release 仅由通过验证与 SDK 的 main push 创建,不覆盖已有 Release。 + +测试入口:`bash scripts/check.sh`;隔离内核实验 `sudo python3 tests/netns.py`;真实 opkg 升级实验先运行 `bash scripts/build_legacy.sh`,再运行 `sudo bash tests/rootfs_install.sh`。SDK 可复用 workflow 对实际 SDK 产物执行包内容校验和 rootfs 升级实验。 + +本地 UDP/TCP 测试证明 DNS 时序和规则行为;Linux namespace 实验证明相应 nft/conntrack/恢复行为;官方 rootfs 实验证明 opkg 格式、版本升级及配置保留。它们都不等同于你的实体路由器已完成 LuCI 浏览器、HomeProxy/SmartDNS 现场验收。 + +DNS 偏好不是强制连接协议:应用缓存、Happy Eyeballs、DoH/DoT、VPN DNS、HTTPS/SVCB 和实际 IPv6 可达性仍影响最终连接。软件/硬件 flow offload 也可能导致流量观察低估,插件不会自动关闭 offload。 diff --git a/docs/UX-TRAFFIC-0.2.0-r2.md b/docs/UX-TRAFFIC-0.2.0-r2.md new file mode 100644 index 0000000..ce2e684 --- /dev/null +++ b/docs/UX-TRAFFIC-0.2.0-r2.md @@ -0,0 +1,74 @@ +# 0.2.0-r2: usable configuration and observable traffic + +## 1. Configure without internal IDs + +1. In the domain-sets tab, add a name (for example AI services) and paste + `openai.com`, `anthropic.com`, `claude.ai`, separated by newlines, whitespace, + or commas. New inputs include the apex and all subdomains. Capitalization, + trailing dots and pasted HTTP(S) URLs are normalized. IDNs use punycode. +2. In mode sets, create Daily and add unnamed rows. Choose a saved set or enter + a domain, then choose dual stack, IPv6 first, IPv4 first or custom A/B. + Standard modes keep optional timing overrides collapsed; custom opens them. +3. Save, then select Daily on the device page. Unmatched names use that device's + own global mode/A/B. Blank timings inherit; zero is an intentional value. +4. More-specific domain matches still win. Equal specificity uses row order; + arrows reorder rows. DNS actions remain separate and retain precedence. + Existing DNS actions can be edited inside the collapsed compatibility area. +5. Renaming a library item keeps its references. Deleting a referenced set or + profile is blocked with a readable error. No manual stable IDs are required. + +The editor preflights the complete staged UCI config with a bounded, read-only +`check_config` RPC before scoped UCI save/commit. Bad A+B, references or values +cannot be committed by these views. It never executes UCI text as shell code. +Unchanged legacy exact patterns keep their old semantics; use the visible +include-subdomains button to opt in. This avoids silently broadening old blocks. + +## 2. Traffic investigation and repair + +Compared immutable r6 `38a69cb` with r1 `8b03a9a`: traffic.go, firewall.go and +platform.go were identical, and runtime's previous delta was validation counts. +No on-router nft/RPC diagnostic dump was supplied. Therefore a uniquely +r1-introduced arithmetic bug or the user's single exact root cause is NOT proven. +The following failures were actually reproduced and repaired: + +- Apply advertised an enabled monitor as off before its first tick. +- Missing named counters looked like available zero totals instead of errors. +- Profile-only Apply recreated the table and cleared diagnostic session totals. +- DNS health failure returned before traffic sampling and left stale values. + +FORWARD-only observation also excludes local proxy INPUT/OUTPUT paths. r2 uses +counter-only LAN PREROUTING (-310) upload and POSTROUTING (310) download chains, +scoped to trusted interfaces and discovered device MAC/IP identities. Existing +DNS redirect, expiring activation sets, watchdog, conntrack and ownership checks +are retained. No mark, routing, NAT66, proxy or shared UCI settings are changed. + +The runtime only refreshes its sets for preference changes. Necessary topology +rebuilds preserve completed totals and invalidate the rate baseline. Errors, +missing counters and warming-up are explicit; IPv4/IPv6 availability is separate. +DNS fail-open continues read-only samples. Missing intervals are not estimated. +Monitoring disable or process restart intentionally starts a new session. + +These are software-path, client-facing observations, including traffic to the +router. They do NOT report which family HomeProxy used for its WAN connection, +and flow/hardware offload can undercount. No automatic offload disable or +nlbwmon reconfiguration is performed. + +## 3. Upgrade and recovery + +Use the official SDK `luci-app-netpreference_0.2.0-r2_x86_64.ipk` after confirming +its SHA256. Ordinary `opkg install` upgrades r6/r1; do not uninstall first and do +not force dependencies. Refresh the LuCI page after upgrading to replace cached +JavaScript. Existing `/etc/config/netpreference` remains a conffile; no wholesale +configuration migration or overwrite is introduced. Restore affects only owned +NetPreference resources, not HomeProxy/SmartDNS/NAT66/nlbwmon. + +## 4. Evidence boundaries + +Tests include Go race and real DNS wire behavior, deterministic four-direction +sampling, unix control/CLI RPC, generated UI-to-backend inheritance, Chromium +DOM interactions, actual kernel namespace forwarding/local-proxy packet paths, +and official target uci.js/native UCI plus opkg upgrade tests. See the separate +verification report for actual outcomes, source SHA, artifacts and exclusions. +The kernel lab does not run the user's HomeProxy or firmware kernel; browser +hosting and target-uci ubus transport use declared fixtures. No live user-router +acceptance or real proxy WAN-family measurement is claimed. diff --git a/docs/VERIFICATION-0.2.0.md b/docs/VERIFICATION-0.2.0.md new file mode 100644 index 0000000..f1e7777 --- /dev/null +++ b/docs/VERIFICATION-0.2.0.md @@ -0,0 +1,66 @@ +# NetPreference 0.2.0 验证报告 + +日期:2026-10-03。目标:ImmortalWrt 24.10.4 x86_64;包版本 `0.2.0-r1`。分支:`feat/0.2.0-policy-profiles`。验收入口:[PR #2](https://github.com/LE-saber/NetPreference/pull/2)。 + +## 最终产物与历史证据的区别 + +开发过程中首次官方构建已成功,但延长 fuzz 又发现查询名重复规范化问题,已修复并加入保留的回归种子。因此 **run 37087556392 / 618915a 的 IPK 只是历史证据,不是最终推荐安装包**。最终交付必须使用包含 `normalization_test.go`、种子 `1b80e8a98011dc15` 和幂等 `normalizeQueryName` 的后续成功 SDK 构建。 + +最终 PR 的验收清单固定列出实际成功的 run / source SHA / IPK SHA256;每份 SDK artifact 自带 `build-info.json`、`SHA256SUMS`、`source.tar.gz`、`outcomes.json` 和完整日志。不把排队状态或仅存在 IPK 文件当作验证通过。文档不为了写入自己的新 commit SHA 而无限产生重复构建。 + +## 1. 核心验证 + +`bash scripts/check.sh` 包含 Go race、vet、DNS wire fuzz、UCI fuzz、**30 秒双 worker DomainSet 差分 fuzz**、8 项包测试、5 项 workflow 守卫和 LuCI JavaScript API 契约。 + +修复最终双尾点反例后,本地独立延长 fuzz 完整通过 **610275 次执行**;新增规范化幂等性与直接/集合双尾点一致性测试通过。重新执行的 race 单测全部通过,本地 Go 1.23.2 核心覆盖率 **80.5%**,DNS/UCI fuzz、包、workflow、LuCI、Python/shell 语法检查也分步通过。一次完整本地命令在 90 秒工具预算耗尽时被截断,单独记录失败 011;不把那次被截断的命令记为整套完成,最终整套结果以 Actions 为准。 + +覆盖范围:旧 r6 无迁移;匹配边界、大小写和单一根域点;DomainSet 最具体成员;Profile 隔离;显式 0/false 与缺省继承;设备有效协议族;无效引用及超限;最具体单条策略;DNS action 与时序分层;A/AAAA 各自的动作、上游和探测;并发 reload 与旧在途探测;wire label 不可伪装成点分域名。 + +LuCI JavaScript 是真实 Node.js 执行,但 `form/rpc/uci` 为 API doubles。它检查命名引用、选择器、继承/零值、旧动作、仅提交本插件的保存路径及错误处理。**没有将它称为真实浏览器或指定 LuCI 主题下的视觉验收。** + +## 2. 真实 DNS 与内核行为 + +本地/CI socket tests 同时执行 UDP/TCP,检查不同域名 A/B、对称 IPv4/IPv6 偏好、主动探测关闭、缺少首选记录时保留另一族答复、模式切换和缓存隔离。 + +历史分支 run [37088022877](https://github.com/LE-saber/NetPreference/actions/runs/37088022877) 的 verify job `111102399564` 已成功穿过真实 nft 重定向测量: + +| 情况 | 观测 | +|---|---| +| 未命中域名,设备 IPv6 默认 B=100ms | A 答复约 101ms,IPv4 地址保留 | +| `*.v4.test`,IPv4 偏好 A=90/B=180 | AAAA 约 181ms,IPv4/IPv6 × UDP/TCP 四组通过 | +| `fast.test`,IPv6 偏好 B=45 | A 约 46ms,四组通过 | +| work 切换 travel 普通双栈 | 同域名 AAAA 从约 181ms 降至约 0.69ms,delayed 不再增加 | +| 无效 Profile reload | 返回错误,仍保留当前策略及 NAT66 哨兵 | +| 常驻 NXDOMAIN | 模式切换后仍被阻断,不被偏好规则解除 | + +上述时延是具体实验观测,不是外网延迟服务保证。最终修复后的流水线会再次执行相同内核测试,不能拿历史 run 替代最终 head 的检查。 + +`sudo python3 tests/netns.py` 在 disposable runner 网络命名空间运行真实双栈 nft、conntrack、转发计数及 NAT66。未选择设备始终使用原 DNS。显式 Restore 后复用原 UDP 源端口返回原 DNS;SIGKILL 后独立 guard 恢复。 + +曾发现旧测试仅等待 nft 表消失,过早复用尚未清理的 DNAT tuple。修复后同时等表和同一旧 tuple 消失,仍保留 15 秒总上限与一次性 DNS 断言,不通过重试掩盖失败。修复 run 的日志为 `RECOVERY nft and cached DNAT cleared in 3.0756352890000045 seconds`,之后 IPv4/IPv6 查询正常。该观测不是所有环境下的 3 秒保证。 + +边界:UCI/ip inventory 部分为 fixtures;测试内核为 Actions Linux,不是目标 6.6.110 整机。未修改主机外部防火墙或用户路由器。 + +## 3. 官方 SDK、包格式和真实 opkg + +SDK 固定为 `immortalwrt-sdk-24.10.4-x86-64_gcc-13.3.0_musl.Linux-x86_64.tar.zst`,SHA256 为 `4f5de9da8674d4acdb6bd2afe594ea079c9983690d9e2eb1661a99b8fcd7d270`。官方 packages feed 实际 commit 写入每份 build-info,不用本地打包器产物冒充官方 SDK 包。 + +首次 SDK run [37087556392](https://github.com/LE-saber/NetPreference/actions/runs/37087556392) 已证明编译、静态 linux/amd64 二进制检查和官方 rootfs 升级链路可运行;该包因后续 fuzz 修复不再作为最终交付。最终 run 必须重新完成全部步骤。 + +`tests/rootfs_install.sh` 对实际 SDK IPK 在官方 ImmortalWrt 24.10.4 rootfs 用真实 opkg 执行:新装/版本检查/移除;从固定 main SHA 编译的真实 r6 安装;写入用户修改的旧配置;普通升级至 0.2.0-r1;确认旧配置逐字节不变;卸载仍保留修改后的 conffile。 + +opkg 把新默认配置写到 `netpreference-opkg` 的提示是预期 conffile 保护,不应使用 force-maintainer 覆盖用户配置。实验跳过在线服务 hooks,为缺失的非核心依赖设置仅存在于隔离 rootfs 的状态 fixture,未使用 force-depends;不等同生产 procd/rpcd/代理整机安装生命周期验收。 + +## 4. Actions 与发布门禁 + +相关代码提交在所有 feature branch 跑完整验证;PR 单独跑完整验证;只有 verify 成功才调用 SDK。SDK workflow 默认只读;主 workflow release 必须满足 main push、verify 成功、SDK/rootfs 成功,且不覆盖已有 Release。开发分支不创建正式 Release,本轮没有合并 main。 + +GitHub concurrency 可能自动替换旧 pending run,不能将取消的排队任务误称产品失败。应核对最终 commit 的成功检查,以及 SDK artifact 的各阶段 outcomes。 + +## 5. 失败记录与验证边界 + +`docs/failures/0.2.0/001` 至 `011` 每项独立提交。实际定位并修复空通配扩大、查询名去空白、重复尾点规范化、SIGKILL 测试完成条件;其余为容器网络/下载门禁、连接器路径、命令预算和附加归档检查路径问题。保留两个差分 fuzz 反例并将域名 fuzz 从 3 秒提高到 30 秒。 + +没有独立第三方审查代理;实现者完成核心工作与复核,容器和 Actions 执行真实测试。未执行目标实体路由器升级、真实 LuCI 浏览器、现场 HomeProxy/SmartDNS 联调、长期大规模压力测试或外网应用协议族统计。 + +DNS 偏好仍受客户端缓存、Happy Eyeballs、DoH/DoT、VPN、HTTPS/SVCB 与 IPv6 可达性影响。流量是插件会话观察,offload 可能低估;不会自动关闭 offload。共享 Profile/DomainSet 编辑会影响其引用者,目标机验收宜先在单台非关键设备上进行。 diff --git a/docs/failures/0.2.0-r2/001-container-clone-network.md b/docs/failures/0.2.0-r2/001-container-clone-network.md new file mode 100644 index 0000000..092d64a --- /dev/null +++ b/docs/failures/0.2.0-r2/001-container-clone-network.md @@ -0,0 +1,10 @@ +# 001 — 容器源码克隆被网络环境阻断 + +- 阶段:0.2.0-r2 修复准备。 +- 基线:`feat/0.2.0-policy-profiles`,`8b03a9adee756e053091ea0163565ca47af06099`。 +- 实际命令:`git clone https://github.com/LE-saber/NetPreference.git /mnt/data/netpreference-work/repo`。 +- 实际结果:退出码 128,`Could not resolve host: github.com`。 +- 原因:当前执行容器无法通过常规 git 网络访问 GitHub;GitHub 连接器已成功读取仓库及分支。 +- 影响:本地基线检查暂未执行,不代表项目代码失败。 +- 恢复:使用可用的源码下载/连接器能力获取已固定 SHA 的源码,在容器运行测试,通过 GitHub 连接器写入本分支。保留 main 和用户路由器不变。 +- 状态:本次失败独立提交;继续开发。 diff --git a/docs/failures/0.2.0-r2/002-source-archive-gate.md b/docs/failures/0.2.0-r2/002-source-archive-gate.md new file mode 100644 index 0000000..649f7d0 --- /dev/null +++ b/docs/failures/0.2.0-r2/002-source-archive-gate.md @@ -0,0 +1,9 @@ +# 002 — 固定 SHA 源码归档获取受阻 + +- 阶段:恢复容器源码获取。 +- 归档:`https://codeload.github.com/LE-saber/NetPreference/tar.gz/e8792ec1ea8fa24a17217e7e80d21c970f9cc9c2`。 +- 实际结果:web.open 返回 Internal Error;container.download 返回 `url not viewed in conversation before`。 +- 原因:下载工具要求可识别的已访问 URL,本次 web 打开未能建立该条件。 +- 影响:仅本地源码获取未完成;没有修改用户路由器或默认分支。 +- 恢复:读取此前同类故障的恢复记录,改用受支持归档入口;必要时通过 GitHub 文件读取能力恢复源码。 +- 状态:本次失败独立提交;继续开发。 diff --git a/docs/failures/0.2.0-r2/003-workflow-name-fetch.md b/docs/failures/0.2.0-r2/003-workflow-name-fetch.md new file mode 100644 index 0000000..7caacdc --- /dev/null +++ b/docs/failures/0.2.0-r2/003-workflow-name-fetch.md @@ -0,0 +1,7 @@ +# 003 — workflow 文件名形式的读取入口被连接器拒绝 + +- 操作:GitHub.fetch 读取 `/actions/workflows/r2-source-snapshot.yml/runs?per_page=1`。 +- 实际结果:`INVALID_ARGUMENT / HTTP 400 / URL is not an allowed public GitHub repository or search endpoint`。 +- 影响:无法通过该 URL 观察源码快照任务,不是 Actions 执行失败。 +- 恢复:使用原生 Actions workflow/run 工具或已验证的数字 ID 入口。 +- 状态:独立记录后继续开发。 diff --git a/docs/failures/0.2.0-r2/004-workflow-collection-fetch.md b/docs/failures/0.2.0-r2/004-workflow-collection-fetch.md new file mode 100644 index 0000000..78d0e55 --- /dev/null +++ b/docs/failures/0.2.0-r2/004-workflow-collection-fetch.md @@ -0,0 +1,7 @@ +# 004 — workflow 集合读取入口被连接器拒绝 + +- 操作:GitHub.fetch 读取 `/actions/workflows`。 +- 实际结果:`INVALID_ARGUMENT / HTTP 400 / URL is not an allowed public GitHub repository or search endpoint`。 +- 影响:不能从该集合发现 workflow ID;源码快照实际已成功,不受此错误影响。 +- 恢复结果:通过已支持的 `/actions/runs` 发现快照 run `37127708044`,原生 artifact 工具成功下载 `11275673957`。容器已解压 r1 与 r6 源码,开发恢复。 +- 后续:仅使用已验证的 runs 集合及原生 job/artifact 工具。 diff --git a/docs/failures/0.2.0-r2/005-streaming-exec-unavailable.md b/docs/failures/0.2.0-r2/005-streaming-exec-unavailable.md new file mode 100644 index 0000000..f9022f6 --- /dev/null +++ b/docs/failures/0.2.0-r2/005-streaming-exec-unavailable.md @@ -0,0 +1,7 @@ +# 005 — 基线测试交互式执行方式不可用 + +- 操作:通过 container.exec 的 session_name 启动 `go test -race -count=1 ./...`。 +- 实际结果:`StreamingExecNotEnabledContainerError`,未获得测试结果。 +- 原因:本容器不支持交互式持续会话。 +- 影响:不能把该次调用当作已执行或已通过的测试;不影响源代码。 +- 恢复:改为普通同步命令,分段运行测试并保留日志,不再使用 session_name。 diff --git a/docs/failures/0.2.0-r2/006-traffic-regression-red-tests.md b/docs/failures/0.2.0-r2/006-traffic-regression-red-tests.md new file mode 100644 index 0000000..2999843 --- /dev/null +++ b/docs/failures/0.2.0-r2/006-traffic-regression-red-tests.md @@ -0,0 +1,12 @@ +# 006 — 流量链路新增回归测试红测 + +基线:0.2.0-r1 `8b03a9a`。命令:`go test ./internal/netpref -run 'TestTraffic(Runtime|Missing|Profile|Continues)' -count=1`,实际退出 1。 + +本次一次测试批次复现四处问题: + +1. `TestTrafficRuntimeImmediateEnabled`:monitor=1 且 Apply 成功,但初始 runtime snapshot 报 enabled=false。 +2. `TestTrafficMissingObjectsAreNotAvailable`:nft JSON 为合法的空 nftables 数组时,四个命名 counter 都不存在,却返回 totals_available=true 且无错误,UI 只能无限等待有效采样。 +3. `TestTrafficProfileReloadPreservesCountersAndSession`:仅新增一个 Profile 再 Reload,仍产生 `delete table`,导致所有计数器和已累计会话被重建/清空。 +4. `TestTrafficContinuesDuringDNSFailOpen`:DNS 健康失败时,真实 nft 数值从基线增长,但 Tick 提前 return,观察值不再更新。 + +这是测试驱动修复前的预期红测,不能作为通过证据。r6 对照显示这些底层代码原本也存在;尚无用户路由器现场 nft/RPC 输出,不能断言其中某一项就是该用户实机故障的唯一原因。修复将覆盖实际观察到的链路弱点并补充可见诊断,后续用运行时、控制 socket、CLI RPC 和真实 netns 流量验证。 diff --git a/docs/failures/0.2.0-r2/007-reference-source-download.md b/docs/failures/0.2.0-r2/007-reference-source-download.md new file mode 100644 index 0000000..8017afe --- /dev/null +++ b/docs/failures/0.2.0-r2/007-reference-source-download.md @@ -0,0 +1,6 @@ +# 007 — 容器直接下载 LuCI 参考源码失败 + +- 操作:container.download 下载已通过 web 读取的官方 `https://openwrt.github.io/luci/jsapi/uci.js.html` 到容器,计划补充实际 UCI JavaScript 实现验证。 +- 实际结果:`ERROR: download failed`,没有获得参考源码文件,不作为测试证据。 +- 影响:不影响已在容器完成的 Go race、流量回归、前端模型与后端预校验合同测试;但不能把这些 API doubles 说成真实目标 LuCI 验证。 +- 恢复方案:直接在已有官方 ImmortalWrt rootfs 测试阶段读取目标镜像自带 `uci.js`,验证自动命名节、增删、选择器切换、排序和保存,再用目标 `/sbin/uci` 与本插件 `check_config` 校验回读结果。该镜像由现有已固定 SDK/rootfs 流程获取,不再重复容器直连下载。 diff --git a/docs/failures/0.2.0-r2/008-local-suite-timeout.md b/docs/failures/0.2.0-r2/008-local-suite-timeout.md new file mode 100644 index 0000000..ef2a1c2 --- /dev/null +++ b/docs/failures/0.2.0-r2/008-local-suite-timeout.md @@ -0,0 +1,7 @@ +# 008 — 本地整套检查达到容器执行时限 + +- 命令:`bash scripts/check.sh > ../evidence/r2-full-local.txt 2>&1`。 +- 实际结果:container.exec 报 `Command failed because it timed out`(请求时限 120 秒);该次整套任务不能记为通过。 +- 已留日志:Go race/覆盖率通过,internal/netpref 覆盖率 80.9%;DNS fuzz 3 秒通过;UCI fuzz 3 秒通过;域名匹配 fuzz 已运行并输出至 elapsed=9s,没有获得结束结果;打包尚未开始。 +- 原因边界:这是执行环境时限中断,尚无断言失败或产品错误证据。不能将被中断的 fuzz 记为通过,也不能仅据此断言匹配器失败。 +- 恢复:按阶段运行剩余域名 fuzz 和打包/工作流/UI 检查并保留日志;完整脚本还必须在 GitHub Actions 的正常执行环境通过。没有修改生产路由器。 diff --git a/docs/failures/0.2.0-r2/009-commit-metadata-connect-error.md b/docs/failures/0.2.0-r2/009-commit-metadata-connect-error.md new file mode 100644 index 0000000..2b6cb58 --- /dev/null +++ b/docs/failures/0.2.0-r2/009-commit-metadata-connect-error.md @@ -0,0 +1,8 @@ +# 009 — 写入前的 GitHub 连接器暂时中断 + +- 阶段:本地修复完成并通过分段验证,准备写入开发分支。 +- 操作:获取提交 56954ed 的 Git 树元数据;随后尝试独立记录失败、读取仓库信息。 +- 实际结果:这几次调用均返回 `UNKNOWN / ConnectError`。首次失败记录也未成功提交,因此保留为同一次连接中断事件,未声称已写入。 +- 恢复:原生 fetch_file 已重新读取本分支 Makefile(仍为 r1,blob d989d0efa29b3063034ca5125257fa4af597120b)。恢复后先独立提交本记录,再重新确认父提交并通过非强制 Git 操作写入。 +- 补充本地结果:独立域名 fuzz 30 秒通过(584806 次执行);包检查 8 项、工作流检查 5 项、Node 模型与视图合同、UI 生成配置到 Go 核心、Chromium 交互均通过。本地完整脚本超时不计通过;官方 SDK 与真实内核实验仍需在最终代码上执行。 +- 生产边界:没有修改 main、用户路由器或共享配置。 diff --git a/docs/failures/0.2.0-r2/ci-37130017251-1-sdk_rootfs.md b/docs/failures/0.2.0-r2/ci-37130017251-1-sdk_rootfs.md new file mode 100644 index 0000000..98080b0 --- /dev/null +++ b/docs/failures/0.2.0-r2/ci-37130017251-1-sdk_rootfs.md @@ -0,0 +1,47 @@ +# CI failure: sdk_rootfs + +Run: https://github.com/LE-saber/NetPreference/actions/runs/37130017251 + +Tested source: `94e9e04021ca28cb8e39471cefa2f210d9c07381`. Branch: `feat/0.2.0-policy-profiles`. + +This phase failed, and is NOT verified. See subsequent repair and successful run evidence. No production router was modified. + +```text + % Total % Received % Xferd Average Speed Time Time Time Current + Dload Upload Total Spent Left Speed + + 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0 +100 189k 100 189k 0 0 410k 0 --:--:-- --:--:-- --:--:-- 410k + % Total % Received % Xferd Average Speed Time Time Time Current + Dload Upload Total Spent Left Speed + + 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0 + 29 10.0M 29 3087k 0 0 6611k 0 0:00:01 --:--:-- 0:00:01 6612k +100 10.0M 100 10.0M 0 0 18.3M 0 --:--:-- --:--:-- --:--:-- 18.3M +immortalwrt-24.10.4-x86-64-rootfs.tar.gz: OK +arch all 1 +arch noarch 1 +arch x86_64 10 +Installing luci-app-netpreference (0.2.0-r2) to root... +Configuring luci-app-netpreference. +0.2.0 +Package: luci-app-netpreference +Version: 0.2.0-r2 +Depends: libc, luci-base, rpcd, uci, firewall4, nftables-json, ip-full, conntrack +Status: install user installed +Architecture: x86_64 +Conffiles: + /etc/config/netpreference e61c12ecce09e926ddcb8d360bed7e32702aeb7fe71cebf5c845721076eba1a1 +Installed-Time: 1791038522 + +AssertionError [ERR_ASSERTION]: 'pref_musi3cx9_3' == 'pref_musi3cx9_4' + at /home/runner/work/NetPreference/NetPreference/tests/luci_target_uci.js:46:57 { + generatedMessage: true, + code: 'ERR_ASSERTION', + actual: 'pref_musi3cx9_3', + expected: 'pref_musi3cx9_4', + operator: '==', + diff: 'simple' +} + +``` diff --git a/docs/failures/0.2.0-r2/ci-37131055598-1-browser.md b/docs/failures/0.2.0-r2/ci-37131055598-1-browser.md new file mode 100644 index 0000000..13201a9 --- /dev/null +++ b/docs/failures/0.2.0-r2/ci-37131055598-1-browser.md @@ -0,0 +1,16 @@ +# CI failure: browser + +Run: https://github.com/LE-saber/NetPreference/actions/runs/37131055598 + +Tested source: `6c86e6fa0e9bb8e7277176c707716862d2b738e6`. Branch: `feat/0.2.0-policy-profiles`. + +This phase failed, and is NOT verified. See subsequent repair and successful run evidence. No production router was modified. + +```text +Traceback (most recent call last): + File "/home/runner/work/NetPreference/NetPreference/tests/luci_browser.py", line 81, in + assert page.evaluate('app.model.profiles[0].rows[2].wait_ms') == '0' + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +AssertionError + +``` diff --git a/docs/failures/0.2.0-r2/ci-37131311097-1-sdk_rootfs.md b/docs/failures/0.2.0-r2/ci-37131311097-1-sdk_rootfs.md new file mode 100644 index 0000000..c65cd84 --- /dev/null +++ b/docs/failures/0.2.0-r2/ci-37131311097-1-sdk_rootfs.md @@ -0,0 +1,46 @@ +# CI failure: sdk_rootfs + +Run: https://github.com/LE-saber/NetPreference/actions/runs/37131311097 + +Tested source: `da62db061df3e3cfea40ef86827cec7efa6f76f7`. Branch: `feat/0.2.0-policy-profiles`. + +This phase failed, and is NOT verified. See subsequent repair and successful run evidence. No production router was modified. + +```text + % Total % Received % Xferd Average Speed Time Time Time Current + Dload Upload Total Spent Left Speed + + 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0 +100 189k 100 189k 0 0 1047k 0 --:--:-- --:--:-- --:--:-- 1049k + % Total % Received % Xferd Average Speed Time Time Time Current + Dload Upload Total Spent Left Speed + + 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0 +100 10.0M 100 10.0M 0 0 24.6M 0 --:--:-- --:--:-- --:--:-- 24.6M +immortalwrt-24.10.4-x86-64-rootfs.tar.gz: OK +arch all 1 +arch noarch 1 +arch x86_64 10 +Installing luci-app-netpreference (0.2.0-r2) to root... +Configuring luci-app-netpreference. +0.2.0 +Package: luci-app-netpreference +Version: 0.2.0-r2 +Depends: libc, luci-base, rpcd, uci, firewall4, nftables-json, ip-full, conntrack +Status: install user installed +Architecture: x86_64 +Conffiles: + /etc/config/netpreference e61c12ecce09e926ddcb8d360bed7e32702aeb7fe71cebf5c845721076eba1a1 +Installed-Time: 1791039925 + +AssertionError [ERR_ASSERTION]: 'pref_musixf66_3' == 'pref_musixf66_4' + at /home/runner/work/NetPreference/NetPreference/tests/luci_target_uci.js:46:57 { + generatedMessage: true, + code: 'ERR_ASSERTION', + actual: 'pref_musixf66_3', + expected: 'pref_musixf66_4', + operator: '==', + diff: 'simple' +} + +``` diff --git a/docs/failures/0.2.0/001-container-clone-network.md b/docs/failures/0.2.0/001-container-clone-network.md new file mode 100644 index 0000000..7fc1a9c --- /dev/null +++ b/docs/failures/0.2.0/001-container-clone-network.md @@ -0,0 +1,13 @@ +# 001 — 开发容器无法直接克隆仓库 + +- 日期:2026-10-03。 +- 基线:`main` / `38a69cbb529eb8fc1b820fa00d7cc439306112f4`。 +- 分支:`feat/0.2.0-policy-profiles`。 +- 阶段:取得源码,尚未修改产品代码。 +- 命令:`git clone --branch main https://github.com/LE-saber/NetPreference.git /mnt/data/NetPreference`。 +- 实际结果:exit 128,`Could not resolve host: github.com`。 +- 原因:当前执行容器的直接网络/DNS访问不可用;这不是仓库权限或产品故障。GitHub 连接器已成功读取最新 main 并建立开发分支。 +- 影响:不能依赖容器内 git clone、git push 或联网下载 SDK/Go 依赖。 +- 恢复路径:通过已授权 GitHub 连接器读取/提交源码;容器用于可离线执行的实现和测试;完整联网测试与官方 SDK 构建由 GitHub Actions 实际执行并检查结果。 +- 安全状态:未改 main,未访问或修改用户路由器,未改 HomeProxy/SmartDNS/NAT66。 +- 状态:已采用替代执行路径,继续开发;不把未执行的构建记为成功。 diff --git a/docs/failures/0.2.0/002-source-archive-url-gate.md b/docs/failures/0.2.0/002-source-archive-url-gate.md new file mode 100644 index 0000000..2b6e88a --- /dev/null +++ b/docs/failures/0.2.0/002-source-archive-url-gate.md @@ -0,0 +1,10 @@ +# 002 — 源码归档下载的工具 URL 门禁 + +- 日期:2026-10-03。 +- 分支:`feat/0.2.0-policy-profiles`。 +- 阶段:把已核实的 main 源码送入离线开发容器。 +- 操作:下载 `https://github.com/LE-saber/NetPreference/archive/38a69cbb529eb8fc1b820fa00d7cc439306112f4.tar.gz`。 +- 结果:下载工具报 `url not viewed in conversation before`;按要求尝试网页打开后返回 Cache miss,重试仍被门禁拒绝。没有得到归档文件。 +- 原因:二进制归档的 URL 门禁与当前工具下载路径不兼容;不是产品代码或 SDK 构建错误。 +- 恢复:通过只读权限、固定提交的 Actions 源码快照任务产生 artifact,再用 GitHub 原生 artifact 下载能力取回。源码快照临时 workflow 在开发交付前删除;它不会修改源代码、main 或发布 Release。 +- 状态:切换到 Actions artifact 传输路径,继续执行。 diff --git a/docs/failures/0.2.0/003-baseline-command-timeout.md b/docs/failures/0.2.0/003-baseline-command-timeout.md new file mode 100644 index 0000000..62f451a --- /dev/null +++ b/docs/failures/0.2.0/003-baseline-command-timeout.md @@ -0,0 +1,9 @@ +# 003 — 基线验证整条命令超出执行容器时限 + +- 日期:2026-10-03。 +- 基线产品源码:`38a69cbb529eb8fc1b820fa00d7cc439306112f4`(源码快照传输提交 `d43b321641f4def3e7761277db6c7685827d7a2f`)。 +- 命令:`bash scripts/check.sh`;工具执行上限 200 秒。 +- 实际结果:工具报告超时,进程已退出。日志已显示全部 Go race 单元/协议测试通过,覆盖率 76.9%;最后停在 DNS fuzz 的启动行。后续打包与 LuCI 检查尚未执行,不能算整套成功。 +- 已知原因:单次执行预算耗尽;未观察到产品断言失败,尚不能仅凭超时判断模糊测试是否存在卡死。使用 Go 1.23.2,首次构建缓存为空。 +- 恢复:保存原日志,将 fuzz、打包和 UI 检查分步执行并设置独立超时;后续 CI 使用完整套件再次确认。 +- 影响:仅开发验证中断,无路由器或 main 修改。 diff --git a/docs/failures/0.2.0/004-ui-wildcard-validation.md b/docs/failures/0.2.0/004-ui-wildcard-validation.md new file mode 100644 index 0000000..adf1420 --- /dev/null +++ b/docs/failures/0.2.0/004-ui-wildcard-validation.md @@ -0,0 +1,10 @@ +# 004 — 高级页面通配域名校验断言失败 + +- 日期:2026-10-03。 +- 分支:`feat/0.2.0-policy-profiles`。 +- 阶段:实现高级 LuCI 页面后的 API 契约测试。 +- 命令:`node tests/luci_contract.js`。 +- 实际结果:`AssertionError: true != true`,新加入的无效域名用例 `*.` 被当作合法通配符接受。其余 Go race 测试通过;不能据此宣称整套测试通过。 +- 原因:前端先去掉结尾点再判断 `*`,将无效的空通配后缀规范化为全匹配;后端规范化也需一致拒绝这一输入,避免意外扩大范围。 +- 修复:前后端在规范化之前排除 `*.`,增加后端回归断言,重跑完整 LuCI 契约和 Go 测试。普通 `*`、`*.example.com`、根域尾点语义不变。 +- 影响:仅开发测试失败,代码尚未部署至路由器;main 未改变。 diff --git a/docs/failures/0.2.0/005-domain-fuzz-normalization.md b/docs/failures/0.2.0/005-domain-fuzz-normalization.md new file mode 100644 index 0000000..5e93143 --- /dev/null +++ b/docs/failures/0.2.0/005-domain-fuzz-normalization.md @@ -0,0 +1,9 @@ +# 005 — 域名集差分 fuzz 发现查询名被错误去空白 + +- 日期:2026-10-03。 +- 阶段:完整本地验证中新加入的域名集差分 fuzz。 +- 命令:`go test ./internal/netpref -run '^$' -fuzz '^FuzzDomainSetMatchesLinearReference$' -fuzztime=3s -parallel=1`。 +- 实际结果:第 1696 次附近发现反例:集合 `*.example.com,api,example.com.*`,查询名 `api `,索引匹配得到 `api`,线性参考匹配不命中;保存种子 `8a7e95f812a8d963`。 +- 原因:配置域名规范化(可去掉用户输入两端空白)被错误复用于查询名。查询名中的空白不应被当成配置编辑空白移除,否则会扩大匹配范围。 +- 修复:分离查询名规范化和配置域名规范化。查询名仅统一大小写和根域尾点,不去掉标签内空白;保留 fuzz 反例并新增精确回归测试,之后重跑 fuzz 和整套验证。 +- 影响:尚未部署,main 未改变。此失败证明实际执行了新 matcher 的差分 fuzz,未以静态检查代替行为测试。 diff --git a/docs/failures/0.2.0/006-connector-branch-url.md b/docs/failures/0.2.0/006-connector-branch-url.md new file mode 100644 index 0000000..320afd3 --- /dev/null +++ b/docs/failures/0.2.0/006-connector-branch-url.md @@ -0,0 +1,8 @@ +# 006 — 连接器拒绝编码后的 branch 路径 + +- 日期:2026-10-03;分支 `feat/0.2.0-policy-profiles`。 +- 操作:通过 GitHub Fetch GET `/branches/feat%2F0.2.0-policy-profiles` 读取开发分支。 +- 实际结果:工具端 HTTP 400 / INVALID_ARGUMENT,`GitHub Fetch URL contains an invalid repository path`。 +- 原因:该连接器路径校验拒绝此编码形式;未执行任何仓库写入,不是 GitHub 分支缺失或产品故障。 +- 恢复:改用受支持的 Git data URL `/git/ref/heads/feat/0.2.0-policy-profiles`,成功取得 `29fb90feacf73da962073afbc43e2351ce592989`,并从对应 commit 读取 tree。 +- 状态:已恢复;checksum 校验源码传输成功,随后正常提交两份 CI workflow。main 和路由器均未改变。 diff --git a/docs/failures/0.2.0/007-connector-workflow-url.md b/docs/failures/0.2.0/007-connector-workflow-url.md new file mode 100644 index 0000000..e6eccb1 --- /dev/null +++ b/docs/failures/0.2.0/007-connector-workflow-url.md @@ -0,0 +1,8 @@ +# 007 — 连接器拒绝按 workflow 文件名查询 runs + +- 日期:2026-10-03;分支 `feat/0.2.0-policy-profiles`。 +- 操作:GitHub Fetch GET `/actions/workflows/ci.yml/runs?branch=feat%2F0.2.0-policy-profiles&per_page=1`。 +- 实际结果:工具端 HTTP 400 / INVALID_ARGUMENT,`not an allowed public GitHub repository or search endpoint`。 +- 原因:连接器允许的 GET URL 范围不包含该文件名形式的 workflow 子路径,并非 workflow 执行失败。 +- 恢复:使用 `/actions/runs?branch=feat%2F0.2.0-policy-profiles&per_page=1`,成功找到实际运行 `37087556392`;再通过 `/actions/runs/37087556392/jobs` 读取步骤。 +- 状态:已恢复。不得把工具查询失败误报为 CI 构建失败;构建完成状态以实际 jobs / artifacts 为准。 diff --git a/docs/failures/0.2.0/008-watchdog-test-completion-barrier.md b/docs/failures/0.2.0/008-watchdog-test-completion-barrier.md new file mode 100644 index 0000000..a5f4493 --- /dev/null +++ b/docs/failures/0.2.0/008-watchdog-test-completion-barrier.md @@ -0,0 +1,19 @@ +# 008 — PR 内核测试把删表误当作恢复已完成 + +- 日期:2026-10-03;分支 `feat/0.2.0-policy-profiles`。 +- 运行:https://github.com/LE-saber/NetPreference/actions/runs/37087764739 ,verify job `111101482509`。 +- 输入:PR head `a14c9c0c9202f624f936c64021c2ea6e3768ce02`,合并测试提交 `31c625accba51f60178ca645a1cde07ddb7ee1c7`。 +- 命令:`sudo python3 tests/netns.py`。 +- 实际结果:核心测试、Profile 双栈 UDP/TCP 时序、旧规则、无效引用回滚、显式 Restore、流量及 NAT66 均已通过;最后 SIGKILL 场景复用原 UDP 源端口 42054 时收到 `ConnectionRefusedError`。SDK 因 verify 失败被正确跳过,未发布 Release。 + +## 原因 + +检查 `Firewall.Remove` 和测试可知,恢复顺序是先删除本插件 nft 表,再逐个本地地址清理属于插件的 DNS conntrack。它们是两个不同的内核接口,删表完成不等于后续 conntrack 清理已完成。原测试仅等待 nft 表消失,随即复用旧 NAT 五元组,可能在清理仍执行时查询已被 SIGKILL 的 1053 端口。失败后的 finally 又终止 guard,日志中的 `conntrack: context canceled` 是该终止阶段的结果。此前同代码的分支内核实验成功,PR 的不同调度暴露了这个错误完成条件。 + +## 修复与验收 + +保留原 15 秒总恢复上限及原源端口,不盲目加 sleep,不重试 DNS 直到碰巧成功,也不删除 SIGKILL 断言。测试必须同时观察:本插件表消失、该固定五元组的插件 DNAT conntrack 消失;随后只做一次原端口 DNS 查询并断言返回原 DNS 答案。若实际 guard 未完成清理,测试仍然超时失败。对修正后的内核实验重复执行,保留实际日志。 + +- 产品的防火墙所有权、恢复顺序和边界没有因测试修改而放宽。 +- main / 实体路由器未修改。 +- 状态:根因已定位,正在修正测试完成屏障;修复后的实际 CI 结果另记于验证报告。 diff --git a/docs/failures/0.2.0/009-local-sdk-inspection-member-path.md b/docs/failures/0.2.0/009-local-sdk-inspection-member-path.md new file mode 100644 index 0000000..424a424 --- /dev/null +++ b/docs/failures/0.2.0/009-local-sdk-inspection-member-path.md @@ -0,0 +1,11 @@ +# 009 — 附加本地 SDK 冒烟检查的归档成员名错误 + +- 日期:2026-10-03;分支 `feat/0.2.0-policy-profiles`。 +- 已完成的构建:官方 SDK run `37087556392`,SDK 编译、包内容检查及真实 opkg r6 升级实验全部成功。 +- 阶段:下载并校验官方产物后,附加执行其二进制的只读 CLI 检查。 +- 实际失败:临时检查脚本按 `data.tar.gz` 精确读取外层归档成员,得到 `KeyError: filename 'data.tar.gz' not found`。官方 IPK 的实际成员含 `./` 前缀。失败的是新增本地检查脚本,不是包格式、SDK、生产代码或原有 `inspect_ipk.py`(原脚本已正确处理前缀)。 +- 修复:复用规范化成员名的方式,匹配移除单个 `./` 前缀后的路径;不修改包字节,不重新打包冒充官方产物。 +- 实际复测:官方 SDK 二进制 `version` 返回 `0.2.0`;`nft-preview` 分别成功解析真实 `legacy-r6.uci` 和 `profiles.uci`;悬空 Profile 引用返回非零及 `unknown profile`,未输出可应用的 nft 规则。 +- 边界:UCI/ip 是只读 fixture,未执行 nft 写入;此附加检查不替代已经通过的 CI 内核实验和真实 opkg 实验。 +- 官方包 SHA256:`be9cc1a139d67a11a53aabcb9c75cc7b4bc4fb2d8d1a29672e979aabdc9d4091`。 +- 状态:已修复并通过,无产品代码变更,无 main 或路由器修改。 diff --git a/docs/failures/0.2.0/010-query-normalization-idempotence.md b/docs/failures/0.2.0/010-query-normalization-idempotence.md new file mode 100644 index 0000000..f20f64f --- /dev/null +++ b/docs/failures/0.2.0/010-query-normalization-idempotence.md @@ -0,0 +1,10 @@ +# 010 — 延长差分 fuzz 发现查询名规范化非幂等 + +- 日期:2026-10-03;分支 `feat/0.2.0-policy-profiles`。 +- 阶段:首轮官方构建通过后,额外进行 30 秒双 worker DomainSet 差分 fuzz。 +- 命令:`go test ./internal/netpref -run '^$' -fuzz '^FuzzDomainSetMatchesLinearReference$' -fuzztime=30s -parallel=2`。 +- 实际结果:约 17.64 秒、19 万次执行后失败。保存反例 `1b80e8a98011dc15`:模式 `0`、输入查询名 `0..`;集合索引得到精确命中,线性匹配不命中。 +- 根因:`normalizeQueryName` 每次剥除一个结尾根域点;selector 与集合 matcher 在不同层重复调用,错误把非法的双尾点逐层变为合法域名。规范化不是幂等操作,因此直接域名与集合路径不一致。真实 DNS wire 解析已转义标签内的点,但内部匹配 API 仍必须一致处理这种边界。 +- 修复:只对单一结尾根域点做规范化,连续尾点保留为不匹配的原有结构;ASCII 大小写转换保持。增加幂等性、直接/集合一致性、双尾点不扩大匹配的回归测试并保留 fuzz 反例,再重跑延长 fuzz、完整本地 suite、分支/PR 与官方 SDK。 +- 交付约束:此前成功的 IPK 仅保留为历史构建证据,不作为最终交付包;修复后重新构建并核验新的官方产物。 +- 影响:开发验证中断,无 main 或实体路由器修改。状态:已定位,执行修复及复验。 diff --git a/docs/failures/0.2.0/011-local-recheck-command-budget.md b/docs/failures/0.2.0/011-local-recheck-command-budget.md new file mode 100644 index 0000000..563410b --- /dev/null +++ b/docs/failures/0.2.0/011-local-recheck-command-budget.md @@ -0,0 +1,9 @@ +# 011 — 延长 fuzz 后整条本地验证命令超过工具时限 + +- 日期:2026-10-03;分支 `feat/0.2.0-policy-profiles`。 +- 命令:修复失败 010 后运行 `bash scripts/check.sh`,容器工具上限 90 秒。 +- 结果:工具超时并停止进程;日志显示 Go race 测试全部通过(本地核心覆盖率 80.5%)、vet 已通过、DNS 与 UCI fuzz 各 3 秒通过。新增 30 秒域名 fuzz 已执行约 21 秒、约 39.8 万次,没有断言错误,但不能把这个被截断的整条执行记为完成。 +- 原因:本地重新编译加上延长 fuzz 的合计耗时超出单条工具预算,不是新观察到的产品断言失败。 +- 已有独立证据:同一修复的单独 30 秒域名差分 fuzz 已完整通过,610275 次执行;幂等性/双尾点回归通过。 +- 恢复:余下打包、workflow、LuCI 和语法检查分步完成;修复与延长 fuzz 一并提交,GitHub Actions 的完整 verify 作为最终整套验收,不降低测试长度或移除断言来迁就本地工具时限。 +- 影响:仅本地验证中断,无 main、正式 Release 或路由器修改。 diff --git a/docs/failures/0.2.0/012-local-tool-timeout-persistence.md b/docs/failures/0.2.0/012-local-tool-timeout-persistence.md new file mode 100644 index 0000000..d5b7737 --- /dev/null +++ b/docs/failures/0.2.0/012-local-tool-timeout-persistence.md @@ -0,0 +1,8 @@ +# 012 — 提高请求时限后,本地整条验证仍被工具截断 + +- 日期:2026-10-03;最终产品修复提交 `f8ae68cc87518d0f3a557c8266abacf3c6ec3227`。 +- 操作:在缓存已经建立后再次运行 `bash scripts/check.sh`,请求工具 timeout=180000ms。 +- 实际结果:工具仍返回超时;日志再次显示所有 Go race 单测成功、vet 成功、DNS/UCI fuzz 成功,停在域名 fuzz 的约 21 秒进度。没有新失败种子或产品断言。请求 180 秒不证明工具真的给了进程 180 秒,不能据此声称代码发生了 180 秒卡死。 +- 判断与限制:当前单次执行工具预算/截断行为不能可靠支持整个合并命令;不继续反复增大 timeout,也不删掉 30 秒 fuzz。已完成的独立 30 秒域名 fuzz、分步打包/UI/语法结果仍有效,但这两次被截断的整条命令都不算完整通过。 +- 执行转向:以同一实际提交的 GitHub Actions 完整 verify 和官方 SDK/rootfs 为最终集成验收。本文件仅增加失败证据,不改变产品或测试源码。 +- 状态:本地单条完整命令作为环境受限项保留;没有生产路由器或 main 修改。最终报告不得把此环境限制误记成已经修好的产品失败。 diff --git a/docs/failures/0.2.0/013-test-fixture-cross-protocol-port-collision.md b/docs/failures/0.2.0/013-test-fixture-cross-protocol-port-collision.md new file mode 100644 index 0000000..8769259 --- /dev/null +++ b/docs/failures/0.2.0/013-test-fixture-cross-protocol-port-collision.md @@ -0,0 +1,10 @@ +# 013 — 测试 DNS fixture 的 UDP 随机端口与 TCP 冲突 + +- 日期:2026-10-03;PR run `37089182102`,verify job `111106776826`,head `a8c9d5fc0e5780bd567c6e06ad6eb5c3a3007209`。 +- 命令:`bash scripts/check.sh` 中的 Go race 单元/协议测试。 +- 失败位置:`TestOldInflightProbeCannotPolluteNewProfile` 创建 fixture 时,`listen tcp4 127.0.0.1:39078: bind: address already in use`;尚未执行该用例的缓存隔离断言。SDK 和 Release 正确跳过。 +- 根因:旧 fixture 先让 UDP 自动选择端口,再假定同号 TCP 端口也可用。UDP 分配成功并不预留 TCP 端口,TCP 可能已经被其他 socket/TIME_WAIT 占用;第二次 bind 失败时 fixture 还没有注册 cleanup,旧代码同时漏关先建立的 UDP socket。这与 Profile 的运行时缓存逻辑不同,但导致完整测试不稳定,不能只重跑直到碰巧成功。 +- 修复方向:测试 fixture 先保留 TCP 自动选择的端口,再绑定同号 UDP;只对明确的地址占用错误有限次重新分配,任何其他错误直接失败;每个失败的候选 socket 必须关闭。对使用产品 ListenDNS(port=0) 的测试同样只在随机端口分配阶段处理明确冲突,DNS 查询和产品断言绝不重试或放宽。添加确定性注入冲突及失败资源释放测试。 +- 验收:重复执行新分配器回归与旧在途探测隔离用例,再执行分支和 PR 完整 verify、官方 SDK/rootfs。产品固定端口行为及配置不变,不重试或掩盖实际 DNS 错误。 +- 已有证据:同产品源码的上一 PR run `37089063061` 已通过完整 verify 与官方 SDK/rootfs;本次暴露 fixture 环境假设,最终仍需以修复后的最新检查为准。 +- 影响:仅隔离 CI 测试失败,无 main、正式 Release 或实体路由器修改。 diff --git a/files/usr/share/luci/menu.d/luci-app-netpreference.json b/files/usr/share/luci/menu.d/luci-app-netpreference.json index 979ad64..716cedb 100644 --- a/files/usr/share/luci/menu.d/luci-app-netpreference.json +++ b/files/usr/share/luci/menu.d/luci-app-netpreference.json @@ -2,7 +2,32 @@ "admin/services/netpreference": { "title": "NetPreference 网络偏好", "order": 65, - "action": {"type": "view", "path": "netpreference/overview"}, - "depends": {"acl": ["luci-app-netpreference"], "uci": {"netpreference": true}} + "action": { + "type": "firstchild" + }, + "depends": { + "acl": [ + "luci-app-netpreference" + ], + "uci": { + "netpreference": true + } + } + }, + "admin/services/netpreference/overview": { + "title": "设备与流量", + "order": 10, + "action": { + "type": "view", + "path": "netpreference/overview" + } + }, + "admin/services/netpreference/advanced": { + "title": "模式集与域名集", + "order": 20, + "action": { + "type": "view", + "path": "netpreference/advanced" + } } } diff --git a/files/usr/share/rpcd/acl.d/luci-app-netpreference.json b/files/usr/share/rpcd/acl.d/luci-app-netpreference.json index bf32417..a4e89dc 100644 --- a/files/usr/share/rpcd/acl.d/luci-app-netpreference.json +++ b/files/usr/share/rpcd/acl.d/luci-app-netpreference.json @@ -2,12 +2,32 @@ "luci-app-netpreference": { "description": "Manage NetPreference DNS policies; no generic command execution", "read": { - "ubus": {"netpreference": ["status", "devices", "traffic", "validate"]}, - "uci": ["netpreference"] + "ubus": { + "netpreference": [ + "status", + "devices", + "traffic", + "validate", + "check_config" + ] + }, + "uci": [ + "netpreference" + ] }, "write": { - "ubus": {"netpreference": ["apply", "restore"], "uci": ["commit"]}, - "uci": ["netpreference"] + "ubus": { + "netpreference": [ + "apply", + "restore" + ], + "uci": [ + "commit" + ] + }, + "uci": [ + "netpreference" + ] } } } diff --git a/files/www/luci-static/resources/netpreference/library.js b/files/www/luci-static/resources/netpreference/library.js new file mode 100644 index 0000000..fca0c0a --- /dev/null +++ b/files/www/luci-static/resources/netpreference/library.js @@ -0,0 +1,142 @@ +'use strict'; +'require baseclass'; + +// UI model only: the daemon's existing ParseUCI and matching engine remain the +// authority. IDs are generated once, persisted as named UCI sections and never +// derived from display names (renaming cannot break references). +var config = 'netpreference', serial = 0; +function list(value) { return value == null ? [] : Array.isArray(value) ? value.slice() : [value]; } +function display(pattern) { return String(pattern || '').replace(/^\*\./, ''); } +function domain(input) { + var value = String(input || '').trim().replace(/[。.。]/g, '.'); + if (value === '*') return '*'; + if (!value || value === '*.') throw new Error('请输入域名'); + value = value.replace(/^\*\./, '').replace(/^\./, ''); + // Accept a pasted website address as well as a hostname; never permit + // arbitrary URL schemes, credentials, ports in the stored DNS pattern. + if (/^[a-z][a-z0-9+.-]*:\/\//i.test(value) && !/^https?:\/\//i.test(value)) + throw new Error('请输入域名或 HTTP(S) 网址'); + var url; + try { url = new URL(/^https?:\/\//i.test(value) ? value : 'https://' + value); } + catch (_) { throw new Error('无法识别域名:' + input); } + if (url.username || url.password || /[\s*\\]/.test(value)) throw new Error('域名不应包含空格、账号或通配符碎片'); + value = url.hostname.toLowerCase().replace(/\.$/, ''); + if (!value || value.length > 253 || !value.split('.').every(function(s) { return /^[a-z0-9_-]{1,63}$/.test(s); })) + throw new Error('域名格式无效:' + input); + return '*.' + value; +} +function domains(text) { + var tokens = String(text || '').replace(/^\s*#.*$/gm, '').split(/[\s,;,;、]+/).filter(Boolean); + var unique = []; + tokens.forEach(function(t) { var p = domain(t); if (unique.indexOf(p) < 0) unique.push(p); }); + if (!unique.length || unique.length > 256) throw new Error('每个域名集需要 1–256 个域名'); + return unique; +} +function id(uci, model, prefix) { + var used = Object.create(null); + uci.sections(config).forEach(function(s) { used[s['.name']] = true; }); + model.sets.concat(model.profiles).forEach(function(s) { used[s.id] = true; }); + model.profiles.forEach(function(p) { p.rows.forEach(function(r) { used[r.id] = true; }); }); + var key; + do { key = prefix + '_' + Date.now().toString(36) + '_' + (++serial).toString(36); } while (used[key]); + return key; +} +function load(uci) { + var m = {sets: [], profiles: [], original: []}; + uci.sections(config, 'domain_set').forEach(function(s) { + var originals = list(s.domain); + m.sets.push({id:s['.name'], name:s.name || '', original:originals, text:originals.map(display).join('\n'), dirty:false}); + m.original.push(s['.name']); + }); + uci.sections(config, 'profile').forEach(function(s) { + var p = {id:s['.name'], name:s.name || '', rows:[]}; + uci.sections(config, 'policy').filter(function(r) { return r.profile === p.id; }).forEach(function(r) { + p.rows.push({id:r['.name'], kind:r.domain_set ? 'set' : 'domain', domain_set:r.domain_set || '', input:display(r.domain), original:r.domain || '', dirty:false, + mode:r.mode || 'inherit', prefer:r.prefer || '', wait_ms:r.wait_ms == null ? '' : r.wait_ms, delay_ms:r.delay_ms == null ? '' : r.delay_ms, + probe:r.probe == null ? '' : r.probe, enabled:r.enabled == null ? '1' : r.enabled}); + m.original.push(r['.name']); + }); + m.profiles.push(p); m.original.push(p.id); + }); + return m; +} +function newSet(uci,m) { var s={id:id(uci,m,'ds'), name:'', text:'', original:[], dirty:true}; m.sets.push(s); return s; } +function newProfile(uci,m) { var p={id:id(uci,m,'pf'),name:'',rows:[]};m.profiles.push(p);return p; } +function newRow(uci,m,p) { + var r={id:id(uci,m,'pref'),kind:'domain',input:'',original:'',dirty:true,domain_set:'',mode:'ipv6',prefer:'',wait_ms:'',delay_ms:'',probe:'',enabled:'1'}; + p.rows.push(r);return r; +} +function nameCheck(items, label) { + var names = Object.create(null); + items.forEach(function(item) { + var name = item.name.trim(), key = name.toLowerCase(); + if (!name || Array.from(name).length > 80 || /[\x00-\x1f\x7f]/.test(name)) throw new Error(label + ':请填写 1–80 字的名称'); + if (names[key]) throw new Error(label + '名称重复:' + name); + names[key] = true; + }); +} +function order(uci,m) { + // LuCI 25.300 intentionally skips reorderSections() while any delete is + // pending. Selector changes (domain -> domain_set) create such deletes, so + // persist content first, reload, then run this ordering pass separately. + // Anchor each row before its successor; DNS action order remains untouched. + m.profiles.forEach(function(p) { + for (var i=p.rows.length-2;i>=0;i--) { + if(!uci.move(config,p.rows[i].id,p.rows[i+1].id,false)) + throw new Error('无法保存模式集规则顺序'); + } + }); +} +function stage(uci,m) { + nameCheck(m.sets,'域名集');nameCheck(m.profiles,'模式集'); + if (m.sets.length>128 || m.profiles.length>64) throw new Error('域名集或模式集数量超出限制'); + var keep = Object.create(null), operations = [], rows = 0; + m.sets.forEach(function(s) {keep[s.id]=true;operations.push([s.id,'domain_set',{name:s.name.trim(),domain:s.dirty?domains(s.text):s.original.slice()}]);}); + m.profiles.forEach(function(p) { + keep[p.id]=true;operations.push([p.id,'profile',{name:p.name.trim()}]); + p.rows.forEach(function(r) { + rows++; keep[r.id]=true; + if(r.kind==='set' && !m.sets.some(function(s){return s.id===r.domain_set;})) throw new Error(p.name+':请选择已有域名集'); + operations.push([r.id,'policy',{profile:p.id,enabled:r.enabled,domain:r.kind==='domain'?(r.dirty?domain(r.input):r.original):'',domain_set:r.kind==='set'?r.domain_set:'', + mode:r.mode,prefer:r.prefer,wait_ms:r.wait_ms,delay_ms:r.delay_ms,probe:r.probe}]); + }); + }); + if(rows>512)throw new Error('域名规则最多 512 条'); + var removing = m.original.filter(function(key) {return !keep[key];}); + uci.sections(config).forEach(function(s) { + if (removing.indexOf(s['.name'])>=0) return; + // Policies edited by this model will be checked in their new form below. + if (s['.type']==='policy' && keep[s['.name']])return; + ['profile','domain_set'].forEach(function(k) { + if(s[k] && removing.indexOf(s[k])>=0)throw new Error('仍有设备或 DNS 动作在使用,请先取消引用再删除'); + }); + }); + removing.forEach(function(key){uci.remove(config,key);}); + operations.forEach(function(op) { + if(!uci.get(config,op[0]))uci.add(config,op[1],op[0]); + Object.keys(op[2]).forEach(function(k){uci.set(config,op[0],k,op[2][k]===''?null:op[2][k]);}); + }); + // Policy ordering is persisted after this first save/reload. See order(). + // A rejected preflight leaves only local UCI changes. Remember these IDs so + // removing a newly added item before retry also removes its staged section. + m.original = Array.from(new Set(m.original.concat(Object.keys(keep)))); +} +function quote(value) { + var text=String(value); + if(/[\x00\r\n]/.test(text))throw new Error('配置值不能包含换行或 NUL'); + return "'"+text.replace(/'/g,"'\\''")+"'"; +} +function serialize(uci) { + var lines = ["package netpreference"]; + uci.sections(config).forEach(function(s) { + // get() merges option deletions; sections() alone can still expose deleted + // options on supported LuCI versions. Validate exactly what will be saved. + s = uci.get(config, s['.name']) || s; + lines.push('config '+quote(s['.type'])+' '+quote(s['.name'])); + Object.keys(s).filter(function(k){return k[0]!=='.';}).forEach(function(k){ + list(s[k]).forEach(function(v){lines.push((Array.isArray(s[k])?' list ':' option ')+quote(k)+' '+quote(v));}); + }); + }); + return lines.join('\n')+'\n'; +} +return baseclass.extend({domain:domain,domains:domains,display:display,load:load,newSet:newSet,newProfile:newProfile,newRow:newRow,stage:stage,order:order,serialize:serialize}); diff --git a/files/www/luci-static/resources/view/netpreference/advanced.js b/files/www/luci-static/resources/view/netpreference/advanced.js new file mode 100644 index 0000000..897a4e4 --- /dev/null +++ b/files/www/luci-static/resources/view/netpreference/advanced.js @@ -0,0 +1,201 @@ +'use strict'; +'require view'; +'require form'; +'require rpc'; +'require uci'; +'require ui'; +'require dom'; +'require netpreference.library as library'; + +var callApply = rpc.declare({object:'netpreference',method:'apply',expect:{}}); +var callCheck = rpc.declare({object:'netpreference',method:'check_config',params:['config'],expect:{}}); +var callCommit = rpc.declare({object:'uci',method:'commit',params:['config']}); +function checked(r) { if (!r || r.ok===false) throw new Error(r && r.error || 'Request failed');return r; } +function reference(section, key, title, type, optional) { + var o = section.option(form.ListValue, key, title); + o.rmempty = optional; o.optional = optional; + // Rebuild on each render, including after adding a named section in this form. + o.load = function(sid) { + this.keylist = []; this.vallist = []; + this.value('', optional ? '不指定' : '请选择'); + var self = this; + uci.sections('netpreference', type, function(s) { + self.value(s['.name'], s.name || '未命名'); + }); + return form.ListValue.prototype.load.call(this, sid); + }; + o.validate = function(sid, value) { + if (!value) return optional ? true : '必须选择一项'; + var target = uci.get('netpreference', value); + return target && target['.type'] === type ? true : '引用不存在,请先创建并保存'; + }; + return o; +} +function domainValid(value) { + value = (value || '').trim().toLowerCase(); + if (value === '*.') return false; + value = value.replace(/\.$/, ''); + if (value === '*') return true; + value = value.replace(/^\*\./, ''); + return value.length > 0 && value.length <= 253 && value.split('.').every(function(label) { + return /^[a-z0-9_-]{1,63}$/.test(label); + }); +} +function selector(section) { + // Both fields stay visible: no hidden dependency can delete an old selector. + var o = section.option(form.Value, 'domain', '直接填写域名'); + o.placeholder = '*.example.com'; o.optional = true; + o.description = '与域名集二选一。*.example.com 包含根域;* 匹配所有域名。国际化域名请使用 punycode。'; + o.validate = function(sid, value) { return !value || domainValid(value) ? true : '域名格式无效'; }; + reference(section, 'domain_set', '或选择命名域名集', 'domain_set', true); +} +function enabled(section) { var o=section.option(form.Flag,'enabled','启用');o.default='1';o.rmempty=false; } + +/* EDITOR */ +function button(label,handler,attrs) { + return E('button',Object.assign({type:'button','class':'cbi-button',click:handler},attrs||{}),label); +} +function textbox(value,handler,attrs) { + return E('input',Object.assign({type:'text','class':'cbi-input-text',value:value,input:function(e){handler(e.target.value);}},attrs||{})); +} +function select(value,choices,handler,attrs) { + return E('select',Object.assign({'class':'cbi-input-select',change:function(e){handler(e.target.value);}},attrs||{}),choices.map(function(c){return E('option',{value:c[0],selected:c[0]===value ? '' : null},c[1]);})); +} +function field(label,node) { return E('label',{'class':'np-field'},[E('span',{},label),node]); } +function notice(err) {ui.addNotification(null,E('p',{},err.message||String(err)),'error');} +var modes=[['dual','普通双栈'],['ipv6','IPv6 优先'],['ipv4','IPv4 优先'],['custom','自定义 A/B']]; + +return view.extend({ + load:function(){return uci.load('netpreference');}, + render:function(){ + var self=this; + this.model=library.load(uci);this.tab='profiles';this.editor=E('div');this.redraw(); + var m=this.map=new form.Map('netpreference','', ''); + var o; + var r=m.section(form.GridSection,'rule','DNS 动作(兼容旧版规则)'); + r.anonymous=true;r.addremove=true;r.sortable=true; + r.description='动作与时序分开匹配;偏好规则不会解除阻断。先设备范围,再域名具体度,完全同分时 模式集规则优先,最后按列表顺序。本地阻断和静态响应立即返回,不附加 A/B。'; + enabled(r);reference(r,'profile','仅在此模式集下生效','profile',true); + o=r.option(form.Value,'device','设备范围(MAC 或 *)');o.default='*';o.rmempty=false;o.value('*','全部已加入设备'); + uci.sections('netpreference','device',function(s){if(s.mac)o.value(s.mac,s.name||s.mac);}); + selector(r); + o=r.option(form.ListValue,'qtype','查询类型');o.default='*';o.rmempty=false;['*','A','AAAA','HTTPS','SVCB'].forEach(function(v){o.value(v);}); + o=r.option(form.ListValue,'action','DNS 动作');o.default='nxdomain';o.rmempty=false; + [['forward','转发 / 指定上游'],['rewrite','静态地址重写'],['nxdomain','NXDOMAIN'],['nodata','NODATA'],['refused','REFUSED'],['sinkhole','0.0.0.0 / ::'],['ipv4_only','仅 IPv4(AAAA NODATA)'],['ipv6_only','仅 IPv6(A NODATA)']].forEach(function(v){o.value(v[0],v[1]);}); + o=r.option(form.DynamicList,'ipv4','静态 IPv4');o.datatype='ip4addr';o.depends('action','rewrite');o.modalonly=true;o.retain=true; + o=r.option(form.DynamicList,'ipv6','静态 IPv6');o.datatype='ip6addr';o.depends('action','rewrite');o.modalonly=true;o.retain=true; + o=r.option(form.Value,'upstream','规则上游 DNS');o.placeholder='127.0.0.1:53';o.depends('action','forward');o.modalonly=true;o.retain=true; + o=r.option(form.Value,'ttl','TTL(秒)');o.datatype='range(0,86400)';o.default='60';o.rmempty=false;o.modalonly=true; + return m.render().then(function(node){ + return E('div',{'class':'np-library'},[ + E('style',{},'.np-tabs,.np-row-main,.np-card-head,.np-actions{display:flex;gap:10px;flex-wrap:wrap;align-items:center}.np-tabs{margin:14px 0}.np-card{border:1px solid var(--border-color-medium,#ddd);border-radius:8px;padding:16px;margin:14px 0}.np-card-head{justify-content:space-between;margin-bottom:12px}.np-card-head input{flex:1;max-width:420px}.np-rule{background:var(--background-color-low,#f8f8f8);padding:12px;margin:12px 0;border-radius:6px}.np-field{display:flex;flex-direction:column;gap:6px;min-width:120px;margin:4px 0;flex:1}.np-field>span{font-size:12px;opacity:.8}.np-target{flex:2;min-width:240px}.np-target input{width:100%;margin-top:6px}.np-params{margin-top:10px}.np-params summary{cursor:pointer;font-size:12px}.np-params>div{display:flex;gap:12px;flex-wrap:wrap;margin-top:6px}.np-note{font-size:12px;opacity:.75;margin:8px 0}.np-card textarea{width:100%;min-height:140px;font-family:monospace;box-sizing:border-box}.np-actions{flex:0 0 auto}.np-actions button{min-width:34px}.np-empty{padding:18px;border:1px dashed #bbb;border-radius:6px}.np-dns-actions{margin:24px 0}.np-dns-actions>summary{cursor:pointer;font-weight:600}'), + E('h2',{},'模式集与域名集'), + E('p',{},'域名集保存常用域名;模式集将多条域名偏好打包。保存后,在设备页选择一个模式集即可切换。'), + E('p',{'class':'alert-message notice'},'没有匹配的域名,始终使用该设备的全局默认模式和 A/B。新输入 openai.com 即包含根域及全部子域名,不需要填写 *.。'), + self.editor, + E('details',{'class':'np-dns-actions'},[E('summary',{},'更多:DNS 阻断、静态重写和指定上游'),E('p',{'class':'np-note'},'保留旧版 DNS 动作及匹配语义。新建的域名集请先保存,再在这里引用。'),node]) + ]); + }); + }, + redraw:function(){ + var self=this, m=this.model, isSets=this.tab==='sets'; + var tabs=E('div',{'class':'np-tabs'},[ + button('模式集 ('+m.profiles.length+')',function(){self.tab='profiles';self.redraw();},{'class':'cbi-button '+(!isSets?'cbi-button-action':'')}), + button('域名集 ('+m.sets.length+')',function(){self.tab='sets';self.redraw();},{'class':'cbi-button '+(isSets?'cbi-button-action':'')}) + ]); + var items=isSets?m.sets:m.profiles; + var cards=items.map(function(item){return isSets?self.renderSet(item):self.renderProfile(item);}); + if(!cards.length)cards.push(E('p',{'class':'np-empty'},isSets?'还没有域名集。添加名称和域名即可。':'还没有模式集。新建后可以直接添加域名偏好规则。')); + dom.content(this.editor,[tabs,E('div',{},cards),button(isSets?'+ 添加域名集':'+ 添加模式集',function(){ + if(isSets)library.newSet(uci,m);else library.newProfile(uci,m);self.redraw(); + },{'class':'cbi-button cbi-button-add','data-action':isSets?'add-set':'add-profile'})]); + }, + renderSet:function(s){ + var self=this; + var legacy=!s.dirty && s.original.some(function(p){return p!=='*' && p.indexOf('*.')!==0;}); + return E('section',{'class':'np-card','data-set':s.id},[ + E('div',{'class':'np-card-head'},[ + textbox(s.name,function(v){s.name=v;},{placeholder:'域名集名称,例如 AI服务','aria-label':'域名集名称',maxlength:80}), + button('删除域名集',function(){ + if(self.model.profiles.some(function(p){return p.rows.some(function(r){return r.kind==='set'&&r.domain_set===s.id;});}) || uci.sections('netpreference','rule').some(function(r){return r.domain_set===s.id;}))return notice(new Error('这个域名集仍在使用,请先移除引用')); + self.model.sets=self.model.sets.filter(function(x){return x!==s;});self.redraw(); + }) + ]), + E('textarea',{rows:6,placeholder:'openai.com\nanthropic.com\nclaude.ai','aria-label':'域名列表',input:function(e){s.text=e.target.value;s.dirty=true;}},s.text), + E('p',{'class':'np-note'},'一行一个域名,也可用空格、逗号分隔或直接粘贴网址。自动去重并包含全部子域名。'), + legacy?E('p',{'class':'np-note'},['此旧集合含精确域名;未编辑时保持旧语义。 ',button('改为包含子域名',function(){s.dirty=true;self.redraw();})]):'' + ]); + }, + renderProfile:function(p){ + var self=this; + return E('section',{'class':'np-card','data-profile':p.id},[ + E('div',{'class':'np-card-head'},[ + textbox(p.name,function(v){p.name=v;},{placeholder:'模式集名称,例如 日常模式','aria-label':'模式集名称',maxlength:80}), + E('span',{},p.rows.length+' 条规则'), + button('删除模式集',function(){ + if(uci.sections('netpreference').some(function(s){return (s['.type']==='device'||s['.type']==='rule')&&s.profile===p.id;}))return notice(new Error('请先在设备或 DNS 动作中取消使用此模式集')); + self.model.profiles=self.model.profiles.filter(function(x){return x!==p;});self.redraw(); + }) + ]), + E('div',{},p.rows.map(function(r,index){return self.renderRule(p,r,index);})), + button('+ 添加规则',function(){library.newRow(uci,self.model,p);self.redraw();},{'class':'cbi-button cbi-button-add','data-action':'add-rule'}), + E('p',{'class':'np-note'},'更具体的域名优先;同等具体时上方规则优先。仅使用一条匹配规则,不会叠加 A/B。') + ]); + }, + renderRule:function(p,r,index){ + var self=this; + var choices=[['__direct__','输入域名']].concat(this.model.sets.map(function(s){return [s.id,s.name || '未命名域名集'];})); + var target=E('div',{'class':'np-target'},[ + field('匹配对象',select(r.kind==='set'?r.domain_set:'__direct__',choices,function(v){ + r.kind=v==='__direct__'?'domain':'set';if(r.kind==='set')r.domain_set=v;else if(!r.original)r.dirty=true;self.redraw(); + },{'aria-label':'输入域名或选择域名集'})), + r.kind==='domain'?textbox(r.input,function(v){r.input=v;r.dirty=true;},{placeholder:'example.com','aria-label':'直接域名'}):'' + ]); + var timing=E('details',{'class':'np-params',open:r.mode==='custom'?'':null},[ + E('summary',{},'A/B:'+((r.wait_ms===''&&r.delay_ms==='')?'继承设备(点击自定义)':(r.wait_ms===''?'继承':r.wait_ms)+' / '+(r.delay_ms===''?'继承':r.delay_ms)+' ms')), + E('div',{},[ + field('A:等待证据 (ms)',textbox(r.wait_ms,function(v){r.wait_ms=v;},{type:'number',min:0,max:750,step:1,placeholder:'继承设备','aria-label':'A'})), + field('B:额外延迟 (ms)',textbox(r.delay_ms,function(v){r.delay_ms=v;},{type:'number',min:0,max:500,step:1,placeholder:'继承设备','aria-label':'B'})), + r.mode==='custom'?field('优先协议族',select(r.prefer,[['','随设备'],['ipv6','IPv6'],['ipv4','IPv4']],function(v){r.prefer=v;},{'aria-label':'优先协议族'})):'', + field('主动探测',select(r.probe,[['','继承设备'],['1','开启'],['0','关闭']],function(v){r.probe=v;})) + ]), + E('p',{'class':'np-note'},'留空继承设备;0 表示不等待 / 不额外延迟。A+B 不超过 1000 ms。普通双栈不附加延迟。') + ]); + return E('div',{'class':'np-rule'},[ + E('div',{'class':'np-row-main'},[ + target, + field('偏好模式',select(r.mode,r.mode==='inherit'?[['inherit','继承设备(旧规则)']].concat(modes):modes,function(v){r.mode=v;self.redraw();},{'aria-label':'偏好模式'})), + E('div',{'class':'np-actions'},[ + E('label',{},[E('input',{type:'checkbox',checked:r.enabled!=='0'?'':null,change:function(e){r.enabled=e.target.checked?'1':'0';}}),'启用']), + button('↑',function(){p.rows.splice(index,1);p.rows.splice(index-1,0,r);self.redraw();},{disabled:index===0?'':null,title:'上移'}), + button('↓',function(){p.rows.splice(index,1);p.rows.splice(index+1,0,r);self.redraw();},{disabled:index===p.rows.length-1?'':null,title:'下移'}), + button('删除',function(){p.rows.splice(index,1);self.redraw();},{title:'删除规则'}) + ]) + ]), + r.mode!=='dual'?timing:'', + r.kind==='domain'&&!r.dirty&&r.original&&r.original!=='*'&&r.original.indexOf('*.')!==0?E('p',{'class':'np-note'},['旧规则保留精确匹配。 ',button('包含子域名',function(){r.dirty=true;self.redraw();})]):'' + ]); + }, + saveLibrary:function(apply){ + var self=this; + return this.map.save(function(){ + library.stage(uci,self.model); + return callCheck(library.serialize(uci)).then(checked); + }).then(function(){ + // Target LuCI skips reordering when selector deletions are part of the same + // save. After the first save reloads UCI, persist only the desired row order. + library.order(uci,self.model); + return uci.save(); + }).then(function(){return callCommit('netpreference');}).then(function(code){ + if(typeof code==='number'&&code!==0)throw new Error('UCI commit failed: '+code); + self.model=library.load(uci);self.redraw(); + return apply?callApply().then(checked):null; + }).then(function(){ui.addNotification(null,E('p',{},apply?'模式库已保存并应用。':'模式库已保存。到设备页选择模式集并应用后生效。'),'info');}).catch(notice); + }, + handleSave:function(){return this.saveLibrary(false);}, + handleSaveApply:function(){return this.saveLibrary(true);}, + handleReset:function(){ + var self=this;uci.unload('netpreference'); + return uci.load('netpreference').then(function(){self.model=library.load(uci);self.redraw();return self.map.reset();}); + } +}); diff --git a/files/www/luci-static/resources/view/netpreference/overview.js b/files/www/luci-static/resources/view/netpreference/overview.js index 2f87064..ac7c66e 100644 --- a/files/www/luci-static/resources/view/netpreference/overview.js +++ b/files/www/luci-static/resources/view/netpreference/overview.js @@ -6,12 +6,14 @@ 'require ui'; 'require poll'; 'require dom'; +'require netpreference.library as library'; var callStatus = rpc.declare({ object: 'netpreference', method: 'status', expect: {} }); var callDevices = rpc.declare({ object: 'netpreference', method: 'devices', expect: {} }); var callTraffic = rpc.declare({ object: 'netpreference', method: 'traffic', expect: {} }); var callApply = rpc.declare({ object: 'netpreference', method: 'apply', expect: {} }); var callRestore = rpc.declare({ object: 'netpreference', method: 'restore', expect: {} }); +var callCheck = rpc.declare({ object: 'netpreference', method: 'check_config', params: ['config'], expect: {} }); var callCommit = rpc.declare({ object: 'uci', method: 'commit', params: ['config'] }); function checked(result) { @@ -32,7 +34,7 @@ function rate(r) { } function total(t, available) { - return available ? bytes(t.upload_bytes) + ' ↑ ' + bytes(t.download_bytes) + ' ↓' : '不可用'; + return available && t ? bytes(t.upload_bytes) + ' ↑ ' + bytes(t.download_bytes) + ' ↓' : '不可用'; } function card(label, value, note) { @@ -77,7 +79,7 @@ return view.extend({ o = g.option(form.Flag, 'monitor', '启用流量观察'); o.default = '0'; o.rmempty = false; - o.description = '实时速率和累计流量都直接来自 NetPreference 自己的 nft 计数器,不依赖 nlbwmon。累计值用于粗略判断 IPv4 / IPv6 流量比例;关闭监控、重启服务或计数器重建后从 0 开始。启用流量分流/硬件卸载时可能低估。'; + o.description = '实时速率和累计流量都直接来自 NetPreference 自己的 nft 计数器,不依赖 nlbwmon。累计值用于粗略判断 IPv4 / IPv6 流量比例;关闭监控或重启服务后从 0 开始;切换模式集不清空累计。启用流量分流/硬件卸载时可能低估。'; var d = m.section(form.GridSection, 'device', '设备策略'); d.addremove = true; d.anonymous = true; d.sortable = true; @@ -91,11 +93,16 @@ return view.extend({ o.value(h.mac, (h.name || h.mac) + (ips ? ' · ' + ips : '')); }); - o = d.option(form.ListValue, 'mode', '策略模式'); o.default = 'dual'; o.rmempty = false; + o = d.option(form.ListValue, 'mode', '设备默认策略'); o.default = 'dual'; o.rmempty = false; [['dual', '普通双栈'], ['ipv6', 'IPv6 优先'], ['ipv4', 'IPv4 优先'], ['custom', '自定义偏好'], ['block', '阻断 DNS(REFUSED)']].forEach(function(v) { o.value(v[0], v[1]); }); + o = d.option(form.ListValue, 'profile', '模式集'); + o.value('', '不使用模式集'); o.rmempty = true; + o.description = '仅匹配域名覆盖上面的设备默认策略。未匹配域名仍使用本设备的模式与 A/B。在“模式集与域名集”页面创建和保存模式。'; + uci.sections('netpreference', 'profile', function(s) { o.value(s['.name'], s.name || '未命名模式集'); }); + o = d.option(form.ListValue, 'prefer', '自定义优先协议族'); - o.value('ipv6', 'IPv6'); o.value('ipv4', 'IPv4'); o.default = 'ipv6'; o.depends('mode', 'custom'); o.modalonly = true; + o.value('ipv6', 'IPv6'); o.value('ipv4', 'IPv4'); o.default = 'ipv6'; o.depends('mode', 'custom'); o.modalonly = true; o.retain = true; o = d.option(form.ListValue, '_preset', '偏好强度预设'); o.modalonly = true; o.value('soft', '温和:A=75 ms,B=40 ms'); @@ -133,26 +140,6 @@ return view.extend({ o.placeholder = '127.0.0.1:53'; o.description = '可选。传输失败、SERVFAIL 或 REFUSED 时会回退到原始 DNS 链。'; - var r = m.section(form.GridSection, 'rule', '域名规则'); - r.addremove = true; r.anonymous = true; r.sortable = true; - r.description = '“全部已加入设备”只作用于 NetPreference 管理的设备。设备级规则优先于全局规则;随后按最长域名/精确匹配决定,仍相同时按列表顺序。*.example.com 包含根域 example.com。'; - o = r.option(form.Flag, 'enabled', '启用'); o.default = '1'; o.rmempty = false; - o = r.option(form.Value, 'device', '作用范围(MAC 或 *)'); o.default = '*'; o.rmempty = false; - o.value('*', '全部已加入设备'); - uci.sections('netpreference', 'device', function(s) { if (s.mac) o.value(s.mac, s.name || s.mac); }); - - o = r.option(form.Value, 'domain', '域名'); o.placeholder = '*.example.com'; o.rmempty = false; - o = r.option(form.ListValue, 'qtype', '查询类型'); o.default = '*'; o.rmempty = false; - ['*', 'A', 'AAAA', 'HTTPS', 'SVCB'].forEach(function(v) { o.value(v); }); - - o = r.option(form.ListValue, 'action', '动作'); o.default = 'nxdomain'; o.rmempty = false; - [['forward', '转发 / 指定上游'], ['rewrite', '静态地址重写'], ['nxdomain', '返回 NXDOMAIN'], ['nodata', '返回 NODATA'], ['refused', '返回 REFUSED'], ['sinkhole', '黑洞到 0.0.0.0 / ::'], ['ipv4_only', '仅 IPv4:AAAA 返回 NODATA'], ['ipv6_only', '仅 IPv6:A 返回 NODATA']].forEach(function(v) { o.value(v[0], v[1]); }); - - o = r.option(form.DynamicList, 'ipv4', '静态 IPv4 地址'); o.datatype = 'ip4addr'; o.depends('action', 'rewrite'); o.modalonly = true; - o = r.option(form.DynamicList, 'ipv6', '静态 IPv6 地址'); o.datatype = 'ip6addr'; o.depends('action', 'rewrite'); o.modalonly = true; - o = r.option(form.Value, 'upstream', '规则专用上游 DNS'); o.depends('action', 'forward'); o.modalonly = true; - o = r.option(form.Value, 'ttl', '覆盖 TTL(秒)'); o.datatype = 'range(0,86400)'; o.default = '60'; o.rmempty = false; o.modalonly = true; - this.statusBox = E('div', { 'class': 'cbi-section', 'style': 'margin-bottom:1em;' }, '正在读取运行状态…'); this.trafficBox = E('div', { 'class': 'cbi-section' }); @@ -190,13 +177,21 @@ return view.extend({ }, refresh: function() { - var self = this; - return Promise.all([callStatus(), callTraffic()]).then(function(res) { - var s = checked(res[0]), t = checked(res[1]); + var self=this; + return Promise.all([ + callStatus().then(checked).then(function(s){self.renderStatus(s);}).catch(function(err){ + dom.content(self.statusBox,E('div',{'class':'alert-message error'},'状态读取失败:'+(err.message||String(err)))); + }), + callTraffic().then(checked).then(function(t){self.renderTraffic(t);}).catch(function(err){ + dom.content(self.trafficBox,E('div',{'class':'alert-message error'},'流量 RPC 读取失败:'+(err.message||String(err)))); + }) + ]); + }, + renderStatus: function(s) { var state = statusText(s); var stateNote = s.active ? '已选设备的 DNS 策略正在工作' : s.desired ? '为避免断网,当前保持故障开放' : '后台服务运行,但没有启用策略'; - dom.content(self.statusBox, [ + dom.content(this.statusBox, [ E('div', { 'style': 'display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;margin-bottom:12px;' }, [ E('div', {}, [ E('h3', { 'style': 'margin:0;' }, '运行概览'), @@ -216,8 +211,10 @@ return view.extend({ }, s.error || s.discovery_warning) : '' ]); + }, + renderTraffic: function(t) { if (!t.enabled) { - dom.content(self.trafficBox, [ + dom.content(this.trafficBox, [ E('h3', {}, '流量观察'), E('p', {}, '流量观察当前关闭。NetPreference 不会采样或累计流量;其它系统服务不受影响。') ]); @@ -230,33 +227,31 @@ return view.extend({ }))); (t.rows || []).forEach(function(row) { - var h = row.host, ip = (h.ipv4 || []).concat(h.ipv6 || []).join(', '); + var h = row.host || {}, ip = (h.ipv4 || []).concat(h.ipv6 || []).join(', '); table.appendChild(E('tr', { 'class': 'tr' }, [ E('td', { 'class': 'td', 'title': ip }, [E('strong', {}, h.name || h.mac), E('br'), E('small', {}, h.mac)]), E('td', { 'class': 'td' }, rate(row.ipv4_rate)), E('td', { 'class': 'td' }, rate(row.ipv6_rate)), - E('td', { 'class': 'td' }, total(row.totals.ipv4, t.totals_available)), - E('td', { 'class': 'td' }, total(row.totals.ipv6, t.totals_available)), - E('td', { 'class': 'td' }, t.totals_available ? (100 * row.ipv6_ratio).toFixed(1) + '%' : '—') + E('td', { 'class': 'td' }, total((row.totals || {}).ipv4, row.ipv4_available === undefined ? t.totals_available : row.ipv4_available)), + E('td', { 'class': 'td' }, total((row.totals || {}).ipv6, row.ipv6_available === undefined ? t.totals_available : row.ipv6_available)), + E('td', { 'class': 'td' }, (row.ipv4_available === undefined ? t.totals_available : row.ipv4_available && row.ipv6_available) ? (100 * (row.ipv6_ratio || 0)).toFixed(1) + '%' : '—') ])); }); var body = [ E('h3', {}, '流量观察'), - E('p', {}, '实时速率与会话累计都来自 NetPreference 自己的 nft 计数器。会话累计从监控开始后的相邻采样字节差持续相加,仅用于粗略判断 IPv4 / IPv6 流量比例;关闭监控、服务重启或计数器重建后会从 0 开始。') + E('p', {}, '实时速率与会话累计都来自 NetPreference 自己的 LAN 边界 nft 计数器(包含路由器本地代理通信)。显示设备侧协议族,不等于代理的 WAN 出口协议族。会话累计从监控开始后的相邻采样字节差持续相加,仅用于粗略判断 IPv4 / IPv6 流量比例;关闭监控或服务重启后从 0 开始;切换模式或计数器重建保留已采样的累计,缺失区间不估算。') ]; + if (t.state === 'warming_up') body.push(E('p', {}, '监控已开启,正在建立速率基线,等待下一次采样。')); if (t.caveat || t.error) body.push(E('p', { 'style': 'opacity:.75;' }, (t.caveat || '') + ' ' + (t.error || ''))); if ((t.rows || []).length) body.push(table); else body.push(E('p', {}, '暂时没有可显示的设备流量数据。')); - dom.content(self.trafficBox, body); - }).catch(function(err) { - dom.content(self.statusBox, E('div', { 'class': 'alert-message error' }, '服务不可用:' + (err.message || String(err)))); - }); + dom.content(this.trafficBox, body); }, handleSaveApply: function() { var self = this; - return this.map.save().then(function() { return callCommit('netpreference'); }).then(function(code) { + return this.map.save(function() { return callCheck(library.serialize(uci)).then(checked); }).then(function() { return callCommit('netpreference'); }).then(function(code) { if (typeof code === 'number' && code !== 0) throw new Error('UCI 提交失败:' + code); return callApply(); }).then(checked).then(function() { diff --git a/internal/netpref/config.go b/internal/netpref/config.go index cbe1005..02191c2 100644 --- a/internal/netpref/config.go +++ b/internal/netpref/config.go @@ -11,19 +11,26 @@ import ( "strings" ) -const Version = "0.1.0" +const Version = "0.2.0" const DNSPort = 1053 const MaxDevices = 128 // Config is validated before publication and must then be treated as immutable. type Config struct { - Enabled bool `json:"enabled"` - Monitor bool `json:"monitor"` - Interfaces []string `json:"interfaces"` - Upstream string `json:"upstream"` - TimeoutMS int `json:"timeout_ms"` - Devices []Device `json:"devices"` - Rules []Rule `json:"rules"` + Enabled bool `json:"enabled"` + Monitor bool `json:"monitor"` + Interfaces []string `json:"interfaces"` + Upstream string `json:"upstream"` + TimeoutMS int `json:"timeout_ms"` + Devices []Device `json:"devices"` + Rules []Rule `json:"rules"` + Profiles []Profile `json:"profiles,omitempty"` + DomainSets []DomainSet `json:"domain_sets,omitempty"` + Policies []Policy `json:"policies,omitempty"` + + // Derived immutable data, rebuilt before an engine snapshot is published. + setMatchers map[string]*domainMatcher + fingerprint [32]byte } type Device struct { ID string `json:"id"` @@ -36,18 +43,21 @@ type Device struct { DelayMS int `json:"delay_ms"` Probe bool `json:"probe"` Upstream string `json:"upstream"` + Profile string `json:"profile,omitempty"` } type Rule struct { - ID string `json:"id"` - Enabled bool `json:"enabled"` - Device string `json:"device"` // empty or * = global; otherwise device MAC - Domain string `json:"domain"` // exact, *.suffix (includes apex), or * - QType string `json:"qtype"` // empty or * = all; A, AAAA, HTTPS, SVCB - Action string `json:"action"` - IPv4 []string `json:"ipv4"` - IPv6 []string `json:"ipv6"` - Upstream string `json:"upstream"` - TTL int `json:"ttl"` + ID string `json:"id"` + Enabled bool `json:"enabled"` + Device string `json:"device"` // empty or * = global; otherwise device MAC + Domain string `json:"domain"` // exact, *.suffix (includes apex), or * + QType string `json:"qtype"` // empty or * = all; A, AAAA, HTTPS, SVCB + Action string `json:"action"` + IPv4 []string `json:"ipv4"` + IPv6 []string `json:"ipv6"` + Upstream string `json:"upstream"` + TTL int `json:"ttl"` + Profile string `json:"profile,omitempty"` + DomainSet string `json:"domain_set,omitempty"` } func DefaultConfig() Config { @@ -106,7 +116,6 @@ func ValidDomain(s string) bool { return true } s = strings.TrimPrefix(s, "*.") - s = strings.TrimSuffix(s, ".") if len(s) == 0 || len(s) > 253 { return false } @@ -195,9 +204,9 @@ func (c *Config) Validate() error { return fmt.Errorf("rule %s refers to unknown device", r.ID) } } - r.Domain = strings.ToLower(strings.TrimSuffix(r.Domain, ".")) - if !ValidDomain(r.Domain) { - return fmt.Errorf("invalid domain %q", r.Domain) + r.Domain = normalizeDomain(r.Domain) + if err := validSelector(r.Domain, r.DomainSet); err != nil { + return fmt.Errorf("rule %s: %w", r.ID, err) } switch r.QType { case "", "*", "A", "AAAA", "HTTPS", "SVCB": @@ -236,7 +245,7 @@ func (c *Config) Validate() error { } } } - return nil + return c.validateProfiles() } // UCITokens reads UCI export syntax without invoking a shell or evaluating values. @@ -398,6 +407,7 @@ func ParseUCI(text string) (Config, error) { d.Mode = get("mode", d.Mode) d.Prefer = get("prefer", d.Prefer) d.Upstream = get("upstream", "") + d.Profile = get("profile", "") d.Enabled, e = boolean("enabled", true) if e != nil { return c, e @@ -416,7 +426,7 @@ func ParseUCI(text string) (Config, error) { } c.Devices = append(c.Devices, d) case "rule": - r := Rule{ID: s.id, Device: get("device", "*"), Domain: get("domain", ""), QType: get("qtype", "*"), Action: get("action", "nxdomain"), Upstream: get("upstream", ""), IPv4: s.values["ipv4"], IPv6: s.values["ipv6"]} + r := Rule{Profile: get("profile", ""), DomainSet: get("domain_set", ""), ID: s.id, Device: get("device", "*"), Domain: get("domain", ""), QType: get("qtype", "*"), Action: get("action", "nxdomain"), Upstream: get("upstream", ""), IPv4: s.values["ipv4"], IPv6: s.values["ipv6"]} r.Enabled, e = boolean("enabled", true) if e != nil { return c, e @@ -426,6 +436,39 @@ func ParseUCI(text string) (Config, error) { return c, e } c.Rules = append(c.Rules, r) + case "profile": + c.Profiles = append(c.Profiles, Profile{ID: s.id, Name: get("name", s.id), Description: get("description", "")}) + case "domain_set": + c.DomainSets = append(c.DomainSets, DomainSet{ID: s.id, Name: get("name", s.id), Domains: s.values["domain"]}) + case "policy": + p := Policy{ID: s.id, Profile: get("profile", ""), Domain: get("domain", ""), DomainSet: get("domain_set", ""), Mode: get("mode", "inherit"), Prefer: get("prefer", "")} + p.Enabled, e = boolean("enabled", true) + if e != nil { + return c, e + } + // Empty fields inherit. A literal zero/false is a real override. + if get("wait_ms", "") != "" { + v, err := num("wait_ms", 0) + if err != nil { + return c, fmt.Errorf("policy %s wait_ms: %w", s.id, err) + } + p.WaitMS = &v + } + if get("delay_ms", "") != "" { + v, err := num("delay_ms", 0) + if err != nil { + return c, fmt.Errorf("policy %s delay_ms: %w", s.id, err) + } + p.DelayMS = &v + } + if get("probe", "") != "" { + v, err := boolean("probe", false) + if err != nil { + return c, fmt.Errorf("policy %s probe: %w", s.id, err) + } + p.Probe = &v + } + c.Policies = append(c.Policies, p) default: return c, fmt.Errorf("unknown section type %q", s.kind) } diff --git a/internal/netpref/dns.go b/internal/netpref/dns.go index cbfbb73..767c6a2 100644 --- a/internal/netpref/dns.go +++ b/internal/netpref/dns.go @@ -69,6 +69,41 @@ func nameAt(b []byte, off int) ([]string, int, error) { } return nil, 0, errors.New("too many compression pointers") } + +// Preserve DNS label boundaries and ASCII-only case equivalence. Literal dots, +// whitespace and non-ASCII bytes inside a label must not alias ordinary names. +func canonicalName(labels []string) string { + var out strings.Builder + for i, label := range labels { + if i > 0 { + out.WriteByte('.') + } + for j := 0; j < len(label); j++ { + b := label[j] + if b >= 'A' && b <= 'Z' { + b += 'a' - 'A' + } + if b >= 'a' && b <= 'z' || b >= '0' && b <= '9' || b == '-' || b == '_' { + out.WriteByte(b) + } else { + fmt.Fprintf(&out, "\\%03d", b) + } + } + } + return out.String() +} + +// A probe changes only the query type/ID, not the original wire labels. +func probeQuery(q Question, typ uint16) []byte { + var id [2]byte + _, _ = rand.Read(id[:]) + q.ID = binary.BigEndian.Uint16(id[:]) + q.Type = typ + b := questionWire(q) + put16(b, 2, 0x0100) + return b +} + func ParseQuestion(b []byte) (Question, error) { q := Question{UDPLimit: 512} if len(b) < 12 { @@ -87,7 +122,7 @@ func ParseQuestion(b []byte) (Question, error) { return q, io.ErrUnexpectedEOF } q.Labels = labs - q.Name = strings.ToLower(strings.Join(labs, ".")) + q.Name = canonicalName(labs) q.Type = u16(b, end) q.Class = u16(b, end+2) q.End = end + 4 @@ -266,7 +301,7 @@ func AddressEvidence(b []byte, q Question) (bool, time.Duration) { return false, time.Second } if u16(b, end+2) == 1 { - rs = append(rs, rr{strings.ToLower(strings.Join(labs, ".")), u16(b, end), binary.BigEndian.Uint32(b[end+4 : end+8]), end + 10, n}) + rs = append(rs, rr{canonicalName(labs), u16(b, end), binary.BigEndian.Uint32(b[end+4 : end+8]), end + 10, n}) } pos = end + 10 + n } @@ -278,7 +313,7 @@ func AddressEvidence(b []byte, q Question) (bool, time.Duration) { if r.typ == 5 && allowed[r.owner] { labs, _, e := nameAt(b, r.start) if e == nil { - target := strings.ToLower(strings.Join(labs, ".")) + target := canonicalName(labs) if !allowed[target] { allowed[target] = true changed = true diff --git a/internal/netpref/dns_test.go b/internal/netpref/dns_test.go index 3d11679..83626d5 100644 --- a/internal/netpref/dns_test.go +++ b/internal/netpref/dns_test.go @@ -15,11 +15,7 @@ import ( // fixtureUpstream uses real UDP and TCP sockets; tests do not use public DNS. func fixtureUpstream(t *testing.T, fn func([]byte, string) []byte) string { t.Helper() - u, e := net.ListenUDP("udp4", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)}) - if e != nil { - t.Fatal(e) - } - tcp, e := net.Listen("tcp4", u.LocalAddr().String()) + u, tcp, e := listenFixtureUpstream() if e != nil { t.Fatal(e) } @@ -186,7 +182,7 @@ func TestActualUDPAndTCPService(t *testing.T) { c := testConfig() c.Upstream = up e := NewEngine(c) - s, err := ListenDNS("127.0.0.1:0", e, func(net.IP) string { return testMAC }) + s, err := listenFixtureDNS("127.0.0.1:0", e, func(net.IP) string { return testMAC }) if err != nil { t.Fatal(err) } @@ -209,7 +205,7 @@ func TestTCPPipeliningPreferredFirst(t *testing.T) { c.Devices[0].DelayMS = 100 c.Devices[0].Probe = false e := NewEngine(c) - s, err := ListenDNS("127.0.0.1:0", e, func(net.IP) string { return testMAC }) + s, err := listenFixtureDNS("127.0.0.1:0", e, func(net.IP) string { return testMAC }) if err != nil { t.Fatal(err) } @@ -249,7 +245,7 @@ func TestTCPPipeliningPreferredFirst(t *testing.T) { } func TestServiceStopsIdleTCP(t *testing.T) { e := NewEngine(testConfig()) - s, err := ListenDNS("127.0.0.1:0", e, func(net.IP) string { return testMAC }) + s, err := listenFixtureDNS("127.0.0.1:0", e, func(net.IP) string { return testMAC }) if err != nil { t.Fatal(err) } diff --git a/internal/netpref/firewall.go b/internal/netpref/firewall.go index 51294ba..139d63e 100644 --- a/internal/netpref/firewall.go +++ b/internal/netpref/firewall.go @@ -92,11 +92,21 @@ func BuildNFT(c *Config, hosts []Host, replace bool) string { trusted := append([]string{"lo"}, c.Interfaces...) fmt.Fprintf(&b, " chain listener_guard { type filter hook input priority -5; policy accept;\n iifname != { %s } meta l4proto { tcp, udp } th dport 1053 drop\n }\n", quoteList(trusted)) if c.Monitor { - b.WriteString(" chain observe { type filter hook forward priority -10; policy accept;\n") + // Count at the LAN boundary, not only FORWARD. HomeProxy/TProxy may + // deliver a connection locally (PREROUTING -> INPUT, OUTPUT -> POSTROUTING). + // These chains only count; they neither alter marks/NAT nor accept/drop a + // packet on behalf of another chain. Offloaded paths may still be absent. + b.WriteString(" chain observe_upload { type filter hook prerouting priority -310; policy accept;\n") + for _, h := range hosts { + p := counterPrefix(h.MAC) + for _, id := range []string{"4", "6"} { + fmt.Fprintf(&b, " iifname { %s } ether saddr %s meta nfproto ipv%s counter name %s_%s_up\n", quoteList(c.Interfaces), h.MAC, id, p, id) + } + } + b.WriteString(" }\n chain observe_download { type filter hook postrouting priority 310; policy accept;\n") for _, h := range hosts { p := counterPrefix(h.MAC) for _, f := range []struct{ id, proto string }{{"4", "ip"}, {"6", "ip6"}} { - fmt.Fprintf(&b, " iifname { %s } ether saddr %s meta nfproto ipv%s counter name %s_%s_up\n", quoteList(c.Interfaces), h.MAC, f.id, p, f.id) fmt.Fprintf(&b, " oifname { %s } %s daddr @%s_v%s counter name %s_%s_down\n", quoteList(c.Interfaces), f.proto, p, f.id, p, f.id) } } diff --git a/internal/netpref/normalization_test.go b/internal/netpref/normalization_test.go new file mode 100644 index 0000000..322a6c7 --- /dev/null +++ b/internal/netpref/normalization_test.go @@ -0,0 +1,38 @@ +package netpref + +import "testing" + +func TestQueryNormalizationIdempotentRootDot(t *testing.T) { + for _, tc := range []struct{ input, want string }{ + {"API.Example.Com.", "api.example.com"}, + {"api.example.com", "api.example.com"}, + {"0..", "0.."}, {"API..", "api.."}, + {"api...", "api..."}, {"api ", "api "}, + {".", ""}, {"..", ".."}, {"", ""}, + } { + got := normalizeQueryName(tc.input) + if got != tc.want || normalizeQueryName(got) != got { + t.Fatalf("normalize %q: got %q, twice %q, want %q", tc.input, got, normalizeQueryName(got), tc.want) + } + } +} + +func TestDomainSelectorsRejectRepeatedRootDots(t *testing.T) { + c := Config{DomainSets: []DomainSet{{ID: "set", Domains: []string{"api.test", "*.example.test"}}}} + c.compileDomainSets() + for _, name := range []string{"api.test..", "api.test...", "example.test..", "sub.example.test.."} { + for _, pattern := range []string{"api.test", "*.example.test"} { + if score, _ := selectorMatch(&c, pattern, "", name); score >= 0 { + t.Fatalf("direct selector %q accepted %q", pattern, name) + } + } + if score, _ := selectorMatch(&c, "", "set", name); score >= 0 { + t.Fatalf("set selector accepted %q", name) + } + } + for _, name := range []string{"API.TEST.", "example.test.", "sub.example.test."} { + if score, _ := selectorMatch(&c, "", "set", name); score < 0 { + t.Fatalf("valid rooted query rejected: %q", name) + } + } +} diff --git a/internal/netpref/policy.go b/internal/netpref/policy.go index 1295a4d..3e8e48f 100644 --- a/internal/netpref/policy.go +++ b/internal/netpref/policy.go @@ -2,8 +2,11 @@ package netpref import ( "context" + "crypto/sha256" + "encoding/json" "fmt" "net/netip" + "slices" "strings" "sync" "sync/atomic" @@ -40,7 +43,8 @@ func domainScore(pattern, name string) int { return -1 } -// Device-specific scope wins, then longest suffix/exactness; ties use UCI order. +// Device scope wins, then matched domain specificity. Profile-scoped actions +// win only a complete tie, then UCI order. Timing policies never compete here. func MatchRule(c *Config, d *Device, q Question) *Rule { best := -1 var result *Rule @@ -49,13 +53,20 @@ func MatchRule(c *Config, d *Device, q Question) *Rule { if !r.Enabled || r.Device != "" && r.Device != "*" && r.Device != d.MAC { continue } + if r.Profile != "" && r.Profile != d.Profile { + continue + } if r.QType != "" && r.QType != "*" && r.QType != qtypeName(q.Type) { continue } - s := domainScore(r.Domain, q.Name) + s, _ := selectorMatch(c, r.Domain, r.DomainSet, q.Name) if s < 0 { continue } + s *= 2 + if r.Profile != "" { + s++ + } if r.Device == d.MAC { s += 10000 } @@ -192,10 +203,66 @@ func NewEngine(c Config) *Engine { e.SetConfig(c) return e } -func (e *Engine) SetConfig(c Config) { e.config.Store(&c) } -func (e *Engine) Config() *Config { return e.config.Load() } -func (e *Engine) evidenceKey(d *Device, q Question, up string) string { - return fmt.Sprintf("%s|%s|%s|%d", d.MAC, up, q.Name, q.Type) + +// SetConfig takes ownership of a deep immutable snapshot, not the caller's +// slice backing arrays or nullable policy fields. A stable content fingerprint +// isolates evidence across profile/action/parameter changes, while the ordinary +// 3-second manager heartbeat with identical configuration keeps its cache. +func (e *Engine) SetConfig(c Config) { + c.Devices = slices.Clone(c.Devices) + c.Profiles = slices.Clone(c.Profiles) + c.DomainSets = slices.Clone(c.DomainSets) + for i := range c.DomainSets { + c.DomainSets[i].Domains = slices.Clone(c.DomainSets[i].Domains) + } + c.Rules = slices.Clone(c.Rules) + for i := range c.Rules { + c.Rules[i].IPv4 = slices.Clone(c.Rules[i].IPv4) + c.Rules[i].IPv6 = slices.Clone(c.Rules[i].IPv6) + } + c.Policies = slices.Clone(c.Policies) + for i := range c.Policies { + p := &c.Policies[i] + if p.WaitMS != nil { + v := *p.WaitMS + p.WaitMS = &v + } + if p.DelayMS != nil { + v := *p.DelayMS + p.DelayMS = &v + } + if p.Probe != nil { + v := *p.Probe + p.Probe = &v + } + } + c.Interfaces = slices.Clone(c.Interfaces) + // Config contains only JSON primitives/slices; marshaling cannot fail. + raw, _ := json.Marshal(c) + c.fingerprint = sha256.Sum256(raw) + if old := e.config.Load(); old != nil && old.fingerprint == c.fingerprint { + return + } + c.compileDomainSets() + e.config.Store(&c) +} +func (e *Engine) Config() *Config { return e.config.Load() } +func (e *Engine) evidenceKey(c *Config, d *Device, q Question, up string) string { + return fmt.Sprintf("%x|%s|%s|%s|%d", c.fingerprint, d.MAC, up, q.Name, q.Type) +} + +// Resolve each query type independently. An A-only resolver override must not +// silently become the AAAA probe's resolver (and vice versa). +func dnsRoute(c *Config, d *Device, q Question) (string, *Rule) { + up := c.Upstream + if d.Upstream != "" { + up = d.Upstream + } + r := MatchRule(c, d, q) + if r != nil && r.Upstream != "" { + up = r.Upstream + } + return up, r } func (e *Engine) upstream(ctx context.Context, raw []byte, up string, c *Config) ([]byte, error) { call := func(s string) ([]byte, error) { @@ -257,33 +324,28 @@ func (e *Engine) Handle(ctx context.Context, raw []byte, mac string) []byte { if d.Mode == "block" { return Reply(q, 5, nil, 0) } - up := c.Upstream - if d.Upstream != "" { - up = d.Upstream - } - r := MatchRule(c, d, q) + up, r := dnsRoute(c, d, q) if r != nil { if b, local := LocalRule(q, r); local { if q.Type == TypeA || q.Type == TypeAAAA { positive, ttl := AddressEvidence(b, q) - e.cache.publish(e.evidenceKey(d, q, up), positive, ttl) + e.cache.publish(e.evidenceKey(c, d, q, up), positive, ttl) } return b } - if r.Upstream != "" { - up = r.Upstream - } } - prefer := d.Preferred() - delaying := (d.Mode == "ipv4" || d.Mode == "ipv6" || d.Mode == "custom") && (q.Type == 1 || q.Type == 28) && q.Type != prefer + policy := ResolvePreference(c, d, q.Name) + prefer := policy.Preferred() + delaying := policy.Delays(q.Type) var obs *observation started := time.Now() if delaying { pq := q pq.Type = prefer - key := e.evidenceKey(d, pq, up) + pup, pr := dnsRoute(c, d, pq) + key := e.evidenceKey(c, d, pq, pup) obs, _ = e.cache.watch(key) - if d.Probe && e.cache.beginProbe(obs) { + if policy.Probe && e.cache.beginProbe(obs) { select { case e.probes <- struct{}{}: go func() { @@ -291,19 +353,15 @@ func (e *Engine) Handle(ctx context.Context, raw []byte, mac string) []byte { pctx, cancel := context.WithTimeout(context.Background(), time.Duration(c.TimeoutMS)*time.Millisecond) defer cancel() // Probes also obey the preferred-family domain policy; never bypass a block. - pr := MatchRule(c, d, pq) var b []byte var err error - pup := up if pr != nil { if local, ok := LocalRule(pq, pr); ok { b = local - } else if pr.Upstream != "" { - pup = pr.Upstream } } if b == nil { - b, err = e.upstream(pctx, MakeQuery(q.Name, prefer), pup, c) + b, err = e.upstream(pctx, probeQuery(q, prefer), pup, c) } if err == nil { actual, er := ParseQuestion(b) @@ -327,13 +385,13 @@ func (e *Engine) Handle(ctx context.Context, raw []byte, mac string) []byte { } if q.Type == 1 || q.Type == 28 { positive, ttl := AddressEvidence(b, q) - e.cache.publish(e.evidenceKey(d, q, up), positive, ttl) + e.cache.publish(e.evidenceKey(c, d, q, up), positive, ttl) } positiveAnswer, _ := AddressEvidence(b, q) if delaying && positiveAnswer { // A is measured from arrival, not after upstream latency. B is applied only // after positive preferred-family evidence. A+B is globally bounded at 1s. - remaining := time.Until(started.Add(time.Duration(d.WaitMS) * time.Millisecond)) + remaining := time.Until(started.Add(time.Duration(policy.WaitMS) * time.Millisecond)) if remaining > 0 { timer := time.NewTimer(remaining) select { @@ -348,9 +406,9 @@ func (e *Engine) Handle(ctx context.Context, raw []byte, mac string) []byte { } } } - if e.cache.positive(obs) && d.DelayMS > 0 { - until := time.Now().Add(time.Duration(d.DelayMS) * time.Millisecond) - cap := started.Add(time.Duration(d.WaitMS+d.DelayMS) * time.Millisecond) + if e.cache.positive(obs) && policy.DelayMS > 0 { + until := time.Now().Add(time.Duration(policy.DelayMS) * time.Millisecond) + cap := started.Add(time.Duration(policy.WaitMS+policy.DelayMS) * time.Millisecond) if until.After(cap) { until = cap } diff --git a/internal/netpref/profile_behavior_test.go b/internal/netpref/profile_behavior_test.go new file mode 100644 index 0000000..a7e6c98 --- /dev/null +++ b/internal/netpref/profile_behavior_test.go @@ -0,0 +1,222 @@ +package netpref + +import ( + "context" + "net" + "sync" + "sync/atomic" + "testing" + "time" +) + +func wireEngine(t *testing.T, c Config) (*Engine, string) { + t.Helper() + if err := c.Validate(); err != nil { + t.Fatal(err) + } + e := NewEngine(c) + s, err := listenFixtureDNS("127.0.0.1:0", e, func(net.IP) string { return testMAC }) + if err != nil { + t.Fatal(err) + } + t.Cleanup(s.Close) + return e, s.Addr() +} +func wireQuery(t *testing.T, addr, proto, name string, typ uint16) (time.Duration, []byte) { + t.Helper() + raw := MakeQuery(name, typ) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + start := time.Now() + b, err := Exchange(ctx, raw, proto+"://"+addr) + elapsed := time.Since(start) + if err != nil { + t.Fatal(err) + } + q, _ := ValidateQuery(raw) + if err := ValidateResponse(b, q); err != nil { + t.Fatal(err) + } + t.Logf("%s %s %s: %s", proto, name, qtypeName(typ), elapsed) + return elapsed, b +} + +// Measure the actual UDP/TCP client-facing replies, not merely resolved structs. +func TestProfileDomainWireTimingAndSwitch(t *testing.T) { + for _, proto := range []string{"udp", "tcp"} { + t.Run(proto, func(t *testing.T) { + c := profileConfig() + c.Upstream = fixtureUpstream(t, normalAnswer) + c.Devices[0].Mode = "ipv4" + c.Devices[0].WaitMS = 100 + c.Devices[0].DelayMS = 65 + c.Policies = []Policy{ + {ID: "media", Enabled: true, Profile: "work", DomainSet: "media", Mode: "ipv6", WaitMS: intp(100), DelayMS: intp(160)}, + {ID: "short", Enabled: true, Profile: "work", Domain: "short.test", Mode: "ipv6", WaitMS: intp(100), DelayMS: intp(45)}, + {ID: "passive", Enabled: true, Profile: "work", Domain: "passive.test", Mode: "ipv6", WaitMS: intp(90), DelayMS: intp(200), Probe: boolp(false)}, + {ID: "dual", Enabled: true, Profile: "travel", Domain: "*", Mode: "dual"}, + } + // Keep IDs in the common UCI namespace distinct from the set named media. + c.Policies[0].ID = "media_policy" + e, addr := wireEngine(t, c) + cases := []struct { + name string + typ uint16 + min time.Duration + delayed bool + }{ + {"video.test", TypeA, 140 * time.Millisecond, true}, + {"sub.media.test", TypeA, 140 * time.Millisecond, true}, + {"short.test", TypeA, 35 * time.Millisecond, true}, + {"notmedia.test", TypeAAAA, 55 * time.Millisecond, true}, + {"video.test", TypeAAAA, 0, false}, + {"notmedia.test", TypeA, 0, false}, + {"passive.test", TypeA, 75 * time.Millisecond, false}, + } + for _, tc := range cases { + before := e.Delayed.Load() + elapsed, b := wireQuery(t, addr, proto, tc.name, tc.typ) + q, _ := ValidateQuery(MakeQuery(tc.name, tc.typ)) + positive, _ := AddressEvidence(b, q) + if !positive || elapsed < tc.min || elapsed > time.Second { + t.Fatalf("unexpected response/timing: %s positive=%v", elapsed, positive) + } + if (e.Delayed.Load() > before) != tc.delayed { + t.Fatal("wrong delay policy", tc.name) + } + } + // A config switch must not erase the device default or leave the old profile active. + c.Devices[0].Profile = "travel" + e.SetConfig(c) + before := e.Delayed.Load() + wireQuery(t, addr, proto, "video.test", TypeA) + if e.Delayed.Load() != before { + t.Fatal("old profile applied after switch") + } + c.Devices[0].Profile = "" + e.SetConfig(c) + elapsed, _ := wireQuery(t, addr, proto, "video.test", TypeAAAA) + if elapsed < 55*time.Millisecond { + t.Fatal("device default was lost") + } + }) + } +} + +func TestProfileProbeUsesPreferredFamilyRouteAndBlock(t *testing.T) { + var wrongAAAA, correctAAAA atomic.Int64 + aOnly := fixtureUpstream(t, func(raw []byte, p string) []byte { + q, _ := ValidateQuery(raw) + if q.Type == TypeAAAA { + wrongAAAA.Add(1) + return Reply(q, 0, nil, 0) + } + return normalAnswer(raw, p) + }) + preferred := fixtureUpstream(t, func(raw []byte, p string) []byte { + q, _ := ValidateQuery(raw) + if q.Type == TypeAAAA { + correctAAAA.Add(1) + } + return normalAnswer(raw, p) + }) + c := profileConfig() + c.Upstream = preferred + c.Policies = []Policy{{ID: "bias", Enabled: true, Profile: "work", Domain: "*", Mode: "ipv6", WaitMS: intp(150), DelayMS: intp(100)}} + c.Rules = []Rule{{ID: "a_route", Enabled: true, Domain: "*", QType: "A", Action: "forward", Upstream: aOnly}} + e, addr := wireEngine(t, c) + elapsed, _ := wireQuery(t, addr, "udp", "route.test", TypeA) + if elapsed < 85*time.Millisecond || wrongAAAA.Load() != 0 || correctAAAA.Load() != 1 { + t.Fatal("probe used nonpreferred-family resolver", elapsed, wrongAAAA.Load(), correctAAAA.Load()) + } + c.Rules = append(c.Rules, Rule{ID: "noaaaa", Enabled: true, Domain: "blocked.test", QType: "AAAA", Action: "nodata"}) + e.SetConfig(c) + before := e.Delayed.Load() + _, b := wireQuery(t, addr, "tcp", "blocked.test", TypeA) + q, _ := ValidateQuery(MakeQuery("blocked.test", TypeA)) + positive, _ := AddressEvidence(b, q) + if !positive || e.Delayed.Load() != before || correctAAAA.Load() != 1 { + t.Fatal("AAAA local block bypassed or valid A removed") + } +} + +func TestOldInflightProbeCannotPolluteNewProfile(t *testing.T) { + var once sync.Once + arrived := make(chan struct{}) + release := make(chan struct{}) + c := profileConfig() + c.Upstream = fixtureUpstream(t, func(raw []byte, p string) []byte { + q, _ := ValidateQuery(raw) + if q.Type == TypeAAAA { + once.Do(func() { close(arrived) }) + <-release + } + return normalAnswer(raw, p) + }) + // Always unblock before fixture cleanup, including assertion failures. + var unblock sync.Once + t.Cleanup(func() { unblock.Do(func() { close(release) }) }) + c.Policies = []Policy{ + {ID: "old", Enabled: true, Profile: "work", Domain: "*", Mode: "ipv6", WaitMS: intp(100), DelayMS: intp(80)}, + {ID: "new", Enabled: true, Profile: "travel", Domain: "*", Mode: "ipv6", WaitMS: intp(80), DelayMS: intp(200), Probe: boolp(false)}, + } + e := NewEngine(c) + oldDone := make(chan struct{}) + go func() { defer close(oldDone); e.Handle(context.Background(), MakeQuery("race.test", TypeA), testMAC) }() + select { + case <-arrived: + case <-time.After(time.Second): + t.Fatal("probe did not start") + } + c.Devices[0].Profile = "travel" + e.SetConfig(c) + unblock.Do(func() { close(release) }) + <-oldDone + before := e.Delayed.Load() + start := time.Now() + b := e.Handle(context.Background(), MakeQuery("race.test", TypeA), testMAC) + if len(b) == 0 || e.Delayed.Load() != before || time.Since(start) < 65*time.Millisecond { + t.Fatal("old profile's evidence crossed generation") + } +} + +func TestWireLabelsCannotAliasDottedOrUnicodeNames(t *testing.T) { + c := profileConfig() + var probeOK atomic.Bool + c.Upstream = fixtureUpstream(t, func(raw []byte, p string) []byte { + q, _ := ValidateQuery(raw) + if q.Type == TypeAAAA && len(q.Labels) == 2 && q.Labels[0] == "api.media" { + probeOK.Store(true) + } + return normalAnswer(raw, p) + }) + c.Policies = []Policy{{ID: "v6", Enabled: true, Profile: "work", Domain: "*", Mode: "ipv6", WaitMS: intp(150), DelayMS: intp(20)}} + c.Rules = []Rule{{ID: "exact", Enabled: true, Domain: "api.media.test", Action: "nxdomain"}, {ID: "unicode", Enabled: true, Domain: "k.test", Action: "nxdomain"}} + e := NewEngine(c) + for _, labels := range [][]string{{"api.media", "test"}, {"api ", "test"}, {"\u212a", "test"}} { + q := Question{ID: 17, Type: TypeA, Class: 1, Labels: labels} + raw := questionWire(q) + put16(raw, 2, 0x0100) + actual, err := ValidateQuery(raw) + if err != nil { + t.Fatal(err) + } + b := e.Handle(context.Background(), raw, testMAC) + if u16(b, 2)&15 != 0 { + t.Fatal("wire label aliased local block", actual.Name) + } + if err := ValidateResponse(b, actual); err != nil { + t.Fatal(err) + } + } + if !probeOK.Load() { + t.Fatal("probe changed wire labels") + } + // A forged reply containing split labels must not validate as the same question. + q, _ := ValidateQuery(questionWire(Question{ID: 17, Type: TypeA, Class: 1, Labels: []string{"api.media", "test"}})) + forged := normalAnswer(MakeQuery("api.media.test", TypeA), "udp") + put16(forged, 0, 17) + if ValidateResponse(forged, q) == nil { + t.Fatal("ambiguous labels passed response validation") + } +} diff --git a/internal/netpref/profiles.go b/internal/netpref/profiles.go new file mode 100644 index 0000000..a98fd67 --- /dev/null +++ b/internal/netpref/profiles.go @@ -0,0 +1,369 @@ +package netpref + +import ( + "errors" + "fmt" + "strings" + "unicode" + "unicode/utf8" +) + +const ( + MaxProfiles = 64 + MaxDomainSets = 128 + MaxPolicies = 512 + MaxPatternsPerSet = 256 + MaxDomainPatterns = 4096 +) + +// A profile groups domain preferences and optionally DNS action rules. It never +// replaces a device's default. References use the stable section ID, not Name. +type Profile struct { + ID string `json:"id"` + Name string `json:"name"` + Description string `json:"description,omitempty"` +} +type DomainSet struct { + ID string `json:"id"` + Name string `json:"name"` + Domains []string `json:"domains"` +} + +// Policy is independent from Rule (DNS content/action). One best policy wins; +// unset fields inherit directly from the device, not from less specific rules. +// Pointers distinguish a missing value from a deliberate 0 or false override. +type Policy struct { + ID string `json:"id"` + Enabled bool `json:"enabled"` + Profile string `json:"profile"` + Domain string `json:"domain,omitempty"` + DomainSet string `json:"domain_set,omitempty"` + Mode string `json:"mode,omitempty"` + Prefer string `json:"prefer,omitempty"` + WaitMS *int `json:"wait_ms,omitempty"` + DelayMS *int `json:"delay_ms,omitempty"` + Probe *bool `json:"probe,omitempty"` +} + +// Preference is a resolved, request-local value. It is safe to adjust without +// mutating the device or any other client's shared profile. +type Preference struct { + Mode string `json:"mode"` + Prefer string `json:"prefer"` + WaitMS int `json:"wait_ms"` + DelayMS int `json:"delay_ms"` + Probe bool `json:"probe"` + Profile string `json:"profile,omitempty"` + Policy string `json:"policy,omitempty"` + Pattern string `json:"pattern,omitempty"` +} + +func (p Preference) Preferred() uint16 { + if p.Mode == "ipv4" || p.Mode == "custom" && p.Prefer == "ipv4" { + return TypeA + } + return TypeAAAA +} +func (p Preference) Delays(qtype uint16) bool { + return (p.Mode == "ipv4" || p.Mode == "ipv6" || p.Mode == "custom") && + (qtype == TypeA || qtype == TypeAAAA) && qtype != p.Preferred() +} +func devicePreference(d *Device) Preference { + return Preference{Mode: d.Mode, Prefer: d.Prefer, WaitMS: d.WaitMS, DelayMS: d.DelayMS, Probe: d.Probe, Profile: d.Profile} +} +func applyPolicy(d *Device, p *Policy) Preference { + result := devicePreference(d) + if p.Mode != "" && p.Mode != "inherit" { + result.Mode = p.Mode + } + if p.Prefer != "" { + result.Prefer = p.Prefer + } else if result.Mode == "custom" && (d.Mode == "ipv4" || d.Mode == "ipv6") { + // Inherit the device's effective family, not an inactive custom-mode field. + result.Prefer = d.Mode + } + if p.WaitMS != nil { + result.WaitMS = *p.WaitMS + } + if p.DelayMS != nil { + result.DelayMS = *p.DelayMS + } + if p.Probe != nil { + result.Probe = *p.Probe + } + result.Policy = p.ID + return result +} + +func normalizeDomain(s string) string { + s = strings.TrimSpace(s) + if s == "*." { + return s + } // Do not turn an empty wildcard suffix into all domains. + return strings.ToLower(strings.TrimSuffix(s, ".")) +} + +// Query labels are wire data: unlike configuration input, whitespace is not padding. +func normalizeQueryName(s string) string { + // Removing one dot repeatedly would turn invalid "name.." into "name". + // A selector and its compiled set may both normalize; keep this idempotent. + if strings.HasSuffix(s, ".") && !strings.HasSuffix(s, "..") { + s = strings.TrimSuffix(s, ".") + } + b := []byte(s) + for i := range b { + if b[i] >= 'A' && b[i] <= 'Z' { + b[i] += 'a' - 'A' + } + } + return string(b) +} +func validSelector(domain, set string) error { + if (domain == "") == (set == "") { + return errors.New("choose exactly one domain or domain_set") + } + if domain != "" && !ValidDomain(domain) { + return fmt.Errorf("invalid domain %q", domain) + } + if set != "" && !idRE.MatchString(set) { + return fmt.Errorf("invalid domain_set reference %q", set) + } + return nil +} +func validLabel(name string) bool { + if !utf8.ValidString(name) || strings.TrimSpace(name) == "" || utf8.RuneCountInString(name) > 80 { + return false + } + for _, r := range name { + if unicode.IsControl(r) { + return false + } + } + return true +} +func validTiming(a, b int) bool { return a >= 0 && a <= 750 && b >= 0 && b <= 500 && a+b <= 1000 } + +func (c *Config) validateProfiles() error { + if len(c.Profiles) > MaxProfiles || len(c.DomainSets) > MaxDomainSets || len(c.Policies) > MaxPolicies { + return errors.New("limit: 64 profiles / 128 domain sets / 512 domain policies") + } + // UCI IDs share a single namespace, including the mandatory global section. + ids := map[string]bool{"main": true} + addID := func(id string) error { + if !idRE.MatchString(id) || ids[id] { + return fmt.Errorf("invalid/duplicate section id %q", id) + } + ids[id] = true + return nil + } + for _, d := range c.Devices { + if err := addID(d.ID); err != nil { + return err + } + } + for _, r := range c.Rules { + if err := addID(r.ID); err != nil { + return err + } + } + profiles := map[string]bool{} + names := map[string]bool{} + for i := range c.Profiles { + p := &c.Profiles[i] + if err := addID(p.ID); err != nil { + return err + } + p.Name = strings.TrimSpace(p.Name) + key := strings.ToLower(p.Name) + if !validLabel(p.Name) || names[key] { + return fmt.Errorf("profile %s: invalid/duplicate name", p.ID) + } + if !utf8.ValidString(p.Description) || utf8.RuneCountInString(p.Description) > 256 { + return fmt.Errorf("profile %s: description too long/invalid", p.ID) + } + profiles[p.ID], names[key] = true, true + } + sets := map[string]bool{} + names = map[string]bool{} + count := 0 + for i := range c.DomainSets { + s := &c.DomainSets[i] + if err := addID(s.ID); err != nil { + return err + } + s.Name = strings.TrimSpace(s.Name) + key := strings.ToLower(s.Name) + if !validLabel(s.Name) || names[key] { + return fmt.Errorf("domain_set %s: invalid/duplicate name", s.ID) + } + names[key], sets[s.ID] = true, true + if len(s.Domains) == 0 || len(s.Domains) > MaxPatternsPerSet { + return fmt.Errorf("domain_set %s: provide 1..256 domains", s.ID) + } + seen := map[string]bool{} + for j, pattern := range s.Domains { + pattern = normalizeDomain(pattern) + if !ValidDomain(pattern) || seen[pattern] { + return fmt.Errorf("domain_set %s: invalid/duplicate domain %q", s.ID, pattern) + } + s.Domains[j] = pattern + seen[pattern] = true + count++ + } + } + if count > MaxDomainPatterns { + return errors.New("limit: 4096 total domain-set patterns") + } + checkRefs := func(profile, set string) error { + if profile != "" && !profiles[profile] { + return fmt.Errorf("unknown profile %q", profile) + } + if set != "" && !sets[set] { + return fmt.Errorf("unknown domain_set %q", set) + } + return nil + } + for _, d := range c.Devices { + if err := checkRefs(d.Profile, ""); err != nil { + return fmt.Errorf("device %s: %w", d.ID, err) + } + } + for _, r := range c.Rules { + if err := checkRefs(r.Profile, r.DomainSet); err != nil { + return fmt.Errorf("rule %s: %w", r.ID, err) + } + } + for i := range c.Policies { + p := &c.Policies[i] + if err := addID(p.ID); err != nil { + return err + } + if p.Profile == "" { + return fmt.Errorf("policy %s requires a profile", p.ID) + } + if err := checkRefs(p.Profile, p.DomainSet); err != nil { + return fmt.Errorf("policy %s: %w", p.ID, err) + } + p.Domain = normalizeDomain(p.Domain) + if err := validSelector(p.Domain, p.DomainSet); err != nil { + return fmt.Errorf("policy %s: %w", p.ID, err) + } + switch p.Mode { + case "", "inherit", "dual", "ipv4", "ipv6", "custom": + default: + return fmt.Errorf("policy %s: invalid mode %q", p.ID, p.Mode) + } + if p.Prefer != "" && p.Prefer != "ipv4" && p.Prefer != "ipv6" { + return fmt.Errorf("policy %s: invalid preferred family", p.ID) + } + // Validate standalone profiles against the ordinary defaults, and all their + // actual device combinations (including disabled devices/rules for safe reuse). + base := DefaultDevice() + effective := applyPolicy(&base, p) + if !validTiming(effective.WaitMS, effective.DelayMS) { + return fmt.Errorf("policy %s: A=0..750, B=0..500 and A+B<=1000 ms", p.ID) + } + for j := range c.Devices { + d := &c.Devices[j] + if d.Profile != p.Profile { + continue + } + effective = applyPolicy(d, p) + if !validTiming(effective.WaitMS, effective.DelayMS) { + return fmt.Errorf("policy %s + device %s: inherited A+B exceeds 1000 ms", p.ID, d.ID) + } + if effective.Mode == "custom" && effective.Prefer != "ipv4" && effective.Prefer != "ipv6" { + return fmt.Errorf("policy %s + device %s: custom mode needs ipv4/ipv6 prefer", p.ID, d.ID) + } + } + } + c.compileDomainSets() + return nil +} + +// A set is indexed once, not expanded into rules or scanned for every query. +// Exact matches and successive label suffixes are O(number of DNS labels). +type domainMatcher struct { + exact map[string]bool + suffix map[string]bool + any bool +} + +func newDomainMatcher(patterns []string) *domainMatcher { + m := &domainMatcher{exact: map[string]bool{}, suffix: map[string]bool{}} + for _, p := range patterns { + p = normalizeDomain(p) + if p == "*" { + m.any = true + } else if strings.HasPrefix(p, "*.") { + m.suffix[p[2:]] = true + } else { + m.exact[p] = true + } + } + return m +} +func (m *domainMatcher) match(name string) (int, string) { + name = normalizeQueryName(name) + best, pattern := -1, "" + if m.any { + best, pattern = 0, "*" + } + if m.exact[name] { + return len(name)*2 + 1, name + } + for suffix := name; suffix != ""; { + if m.suffix[suffix] { + return len(suffix) * 2, "*." + suffix + } + i := strings.IndexByte(suffix, '.') + if i < 0 { + break + } + suffix = suffix[i+1:] + } + return best, pattern +} +func (c *Config) compileDomainSets() { + c.setMatchers = make(map[string]*domainMatcher, len(c.DomainSets)) + for _, s := range c.DomainSets { + c.setMatchers[s.ID] = newDomainMatcher(s.Domains) + } +} +func selectorMatch(c *Config, domain, set, name string) (int, string) { + name = normalizeQueryName(name) + if set == "" { + return domainScore(normalizeDomain(domain), name), normalizeDomain(domain) + } + if m := c.setMatchers[set]; m != nil { + return m.match(name) + } + // Pure fallback for callers constructing a Config directly in tests/tools. + // Never mutate the published Config while servicing a DNS request. + for _, s := range c.DomainSets { + if s.ID == set { + return newDomainMatcher(s.Domains).match(name) + } + } + return -1, "" +} +func ResolvePreference(c *Config, d *Device, name string) Preference { + result := devicePreference(d) + if d.Profile == "" || d.Mode == "block" { + return result + } + best := -1 + for i := range c.Policies { + p := &c.Policies[i] + if !p.Enabled || p.Profile != d.Profile { + continue + } + score, pattern := selectorMatch(c, p.Domain, p.DomainSet, name) + if score > best { + best = score + result = applyPolicy(d, p) + result.Pattern = pattern + } + } + return result +} diff --git a/internal/netpref/profiles_test.go b/internal/netpref/profiles_test.go new file mode 100644 index 0000000..30e3909 --- /dev/null +++ b/internal/netpref/profiles_test.go @@ -0,0 +1,333 @@ +package netpref + +import ( + "context" + "encoding/json" + "os" + "strings" + "testing" +) + +func intp(v int) *int { return &v } +func boolp(v bool) *bool { return &v } +func profileConfig() Config { + c := testConfig() + c.Profiles = []Profile{{ID: "work", Name: "Work"}, {ID: "travel", Name: "Travel"}} + c.Devices[0].Profile = "work" + c.DomainSets = []DomainSet{{ID: "media", Name: "Media", Domains: []string{"*.media.test", "video.test"}}} + return c +} +func readFixture(t *testing.T, name string) Config { + t.Helper() + raw, err := os.ReadFile("../../tests/fixtures/" + name) + if err != nil { + t.Fatal(err) + } + c, err := ParseUCI(string(raw)) + if err != nil { + t.Fatal(err) + } + return c +} +func TestLegacyR6NoMigrationOrValueLoss(t *testing.T) { + c := readFixture(t, "legacy-r6.uci") + if !c.Enabled || !c.Monitor || len(c.Rules) != 3 || len(c.Devices) != 2 { + t.Fatal(c) + } + d := c.Devices[0] + if d.Mode != "custom" || d.Prefer != "ipv4" || d.WaitMS != 0 || d.DelayMS != 0 || d.Probe || d.Upstream != "tcp://127.0.0.1:5333" { + t.Fatal(d) + } + if d.Profile != "" || len(c.Profiles)+len(c.Policies)+len(c.DomainSets) != 0 { + t.Fatal("legacy config gained advanced policies") + } + p := ResolvePreference(&c, &d, "anything.test") + if p.Policy != "" || p.Mode != d.Mode || p.WaitMS != 0 || p.DelayMS != 0 || p.Probe { + t.Fatal(p) + } + q := Question{Name: "sub.example.com", Type: TypeA} + if r := MatchRule(&c, &d, q); r == nil || r.ID != "legacy_static" { + t.Fatal(r) + } + before, _ := json.Marshal(c) + if err := c.Validate(); err != nil { + t.Fatal(err) + } + after, _ := json.Marshal(c) + if string(before) != string(after) { + t.Fatal("validation not idempotent") + } +} +func TestParseProfilePresenceAndNormalization(t *testing.T) { + c := readFixture(t, "profiles.uci") + if c.DomainSets[0].Domains[0] != "*.media.test" { + t.Fatal(c.DomainSets) + } + if c.Policies[0].Probe != nil || c.Policies[0].WaitMS == nil || *c.Policies[0].WaitMS != 250 { + t.Fatal(c.Policies[0]) + } + z := c.Policies[1] + if z.Probe == nil || *z.Probe || z.WaitMS == nil || *z.WaitMS != 0 || z.DelayMS == nil || *z.DelayMS != 0 { + t.Fatal(z) + } + inherit := c.Policies[2] + if inherit.Probe != nil || inherit.WaitMS != nil || inherit.DelayMS != nil { + t.Fatal("empty values must inherit", inherit) + } +} +func TestAdvancedValidationRejectsUnsafeReferencesAndCombinations(t *testing.T) { + cases := []struct { + name string + mutate func(*Config) + }{ + {"missing-device-profile", func(c *Config) { c.Devices[0].Profile = "missing" }}, + {"missing-policy-profile", func(c *Config) { c.Policies[0].Profile = "missing" }}, + {"unowned-policy", func(c *Config) { c.Policies[0].Profile = "" }}, + {"missing-policy-set", func(c *Config) { c.Policies[0].Domain = ""; c.Policies[0].DomainSet = "missing" }}, + {"missing-action-profile", func(c *Config) { c.Rules = []Rule{{ID: "r", Domain: "*", Action: "nodata", Profile: "missing"}} }}, + {"missing-action-set", func(c *Config) { c.Rules = []Rule{{ID: "r", DomainSet: "missing", Action: "nodata"}} }}, + {"two-action-selectors", func(c *Config) { c.Rules = []Rule{{ID: "r", Domain: "*", DomainSet: "media", Action: "nodata"}} }}, + {"two-policy-selectors", func(c *Config) { c.Policies[0].DomainSet = "media" }}, + {"no-selector", func(c *Config) { c.Policies[0].Domain = "" }}, + {"bad-pattern", func(c *Config) { c.DomainSets[0].Domains = []string{"foo.*.test"} }}, + {"recursive-set", func(c *Config) { c.DomainSets[0].Domains = []string{"@media"} }}, + {"duplicate-pattern", func(c *Config) { c.DomainSets[0].Domains = []string{"A.TEST", "a.test."} }}, + {"empty-set", func(c *Config) { c.DomainSets[0].Domains = nil }}, + {"id-collision", func(c *Config) { c.DomainSets[0].ID = "work" }}, + {"reserved-id", func(c *Config) { c.Profiles[0].ID = "main" }}, + {"duplicate-name", func(c *Config) { c.Profiles[1].Name = " WORK " }}, + {"bad-label", func(c *Config) { c.Profiles[0].Name = "\n" }}, + {"infinite-wait", func(c *Config) { c.Policies[0].WaitMS = intp(-1) }}, + {"huge-delay", func(c *Config) { c.Policies[0].DelayMS = intp(501) }}, + {"over-total", func(c *Config) { c.Policies[0].WaitMS = intp(750); c.Policies[0].DelayMS = intp(500) }}, + {"inherited-over-total", func(c *Config) { + c.Devices[0].WaitMS = 750 + c.Devices[0].DelayMS = 250 + c.Policies[0].DelayMS = intp(500) + }}, + {"bad-policy-mode", func(c *Config) { c.Policies[0].Mode = "block" }}, + {"bad-prefer", func(c *Config) { c.Policies[0].Prefer = "nat64" }}, + {"invalid-inherited-custom-family", func(c *Config) { c.Devices[0].Prefer = "garbage"; c.Policies[0].Mode = "custom" }}, + {"empty-wildcard", func(c *Config) { c.Policies[0].Domain = "*." }}, + {"double-trailing-dot", func(c *Config) { c.Policies[0].Domain = "example.test.." }}, + {"too-many-profiles", func(c *Config) { c.Profiles = make([]Profile, MaxProfiles+1) }}, + {"too-many-policies", func(c *Config) { c.Policies = make([]Policy, MaxPolicies+1) }}, + {"too-many-sets", func(c *Config) { c.DomainSets = make([]DomainSet, MaxDomainSets+1) }}, + {"too-many-patterns-per-set", func(c *Config) { c.DomainSets[0].Domains = make([]string, MaxPatternsPerSet+1) }}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + c := profileConfig() + c.Policies = []Policy{{ID: "p", Enabled: true, Profile: "work", Domain: "*", Mode: "inherit"}} + tc.mutate(&c) + if err := c.Validate(); err == nil { + t.Fatal("invalid advanced configuration accepted") + } + }) + } + raw, _ := os.ReadFile("../../tests/fixtures/profiles.uci") + for _, replacement := range []string{"option probe 'yes'", "option wait_ms 'forever'", "option delay_ms '1.5'"} { + broken := strings.Replace(string(raw), "option probe '0'", replacement, 1) + if _, err := ParseUCI(broken); err == nil { + t.Fatal("invalid UCI value accepted", replacement) + } + } +} +func TestDomainPolicySelectionAndDirectDeviceInheritance(t *testing.T) { + c := profileConfig() + d := &c.Devices[0] + d.Mode = "ipv4" + d.WaitMS = 75 + d.DelayMS = 40 + c.Policies = []Policy{ + {ID: "set_policy", Enabled: true, Profile: "work", DomainSet: "media", Mode: "ipv6", DelayMS: intp(200)}, + {ID: "exact", Enabled: true, Profile: "work", Domain: "api.media.test", Mode: "dual"}, + {ID: "exact_later", Enabled: true, Profile: "work", Domain: "api.media.test", Mode: "ipv6"}, + {ID: "unused_profile", Enabled: true, Profile: "travel", Domain: "*", Mode: "ipv6"}, + {ID: "zero", Enabled: true, Profile: "work", Domain: "zero.test", Mode: "custom", Prefer: "ipv4", WaitMS: intp(0), DelayMS: intp(0), Probe: boolp(false)}, + } + if err := c.Validate(); err != nil { + t.Fatal(err) + } + cases := []struct { + name, policy, mode string + a, b int + probe bool + }{ + {"media.test", "set_policy", "ipv6", 75, 200, true}, + {"deep.a.media.test", "set_policy", "ipv6", 75, 200, true}, + {"VIDEO.TEST.", "set_policy", "ipv6", 75, 200, true}, + {"api.media.test", "exact", "dual", 75, 40, true}, + {"notmedia.test", "", "ipv4", 75, 40, true}, + {"media.test.evil.test", "", "ipv4", 75, 40, true}, + {"zero.test", "zero", "custom", 0, 0, false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got := ResolvePreference(&c, d, tc.name) + if got.Policy != tc.policy || got.Mode != tc.mode || got.WaitMS != tc.a || got.DelayMS != tc.b || got.Probe != tc.probe { + t.Fatal(got) + } + }) + } + d.Profile = "travel" + if got := ResolvePreference(&c, d, "api.media.test"); got.Policy != "unused_profile" { + t.Fatal(got) + } + d.Profile = "" + if got := ResolvePreference(&c, d, "media.test"); got.Policy != "" || got.Mode != "ipv4" { + t.Fatal(got) + } + d.Profile = "work" + d.Mode = "block" + if got := ResolvePreference(&c, d, "media.test"); got.Policy != "" || got.Mode != "block" { + t.Fatal("whole-device block overridden", got) + } +} +func TestSetSpecificityAndDNSActionLayers(t *testing.T) { + c := profileConfig() + d := &c.Devices[0] + c.DomainSets[0].Domains = append(c.DomainSets[0].Domains, "api.media.test", "*") + c.Policies = []Policy{ + {ID: "broad", Enabled: true, Profile: "work", Domain: "*.media.test", Mode: "ipv4"}, + {ID: "set", Enabled: true, Profile: "work", DomainSet: "media", Mode: "ipv6"}, + } + c.Rules = []Rule{ + {ID: "legacy", Enabled: true, Domain: "api.media.test", Action: "nxdomain"}, + {ID: "profile_broad", Enabled: true, Profile: "work", Domain: "*.media.test", Action: "forward"}, + {ID: "other_profile", Enabled: true, Profile: "travel", Domain: "api.media.test", Action: "forward"}, + } + if err := c.Validate(); err != nil { + t.Fatal(err) + } + if got := ResolvePreference(&c, d, "api.media.test"); got.Policy != "set" || got.Pattern != "api.media.test" { + t.Fatal(got) + } + q := Question{Name: "api.media.test", Type: TypeA} + if got := MatchRule(&c, d, q); got.ID != "legacy" { + t.Fatal("preference/profile broad action escaped exact legacy block", got) + } + c.Rules = append(c.Rules, Rule{ID: "profile_exact", Enabled: true, Profile: "work", DomainSet: "media", Action: "nodata"}) + if err := c.Validate(); err != nil { + t.Fatal(err) + } + if got := MatchRule(&c, d, q); got.ID != "profile_exact" { + t.Fatal("profile did not win exact tie", got) + } + c.Rules = append(c.Rules, Rule{ID: "device_block", Enabled: true, Device: testMAC, Domain: "*", Action: "refused"}) + if got := MatchRule(&c, d, q); got.ID != "device_block" { + t.Fatal("device scope no longer takes precedence", got) + } +} +func TestProfileSnapshotOwnsAllMutableData(t *testing.T) { + c := profileConfig() + c.Policies = []Policy{{ID: "p", Enabled: true, Profile: "work", DomainSet: "media", Mode: "ipv6", DelayMS: intp(90), Probe: boolp(false)}} + c.Rules = []Rule{{ID: "r", Enabled: true, Domain: "static.test", Action: "rewrite", IPv4: []string{"192.0.2.1"}}} + e := NewEngine(c) + first := e.Config() + e.SetConfig(c) + if e.Config() != first { + t.Fatal("identical heartbeat discarded configuration/cache namespace") + } + c.Devices[0].Mode = "block" + *c.Policies[0].DelayMS = 500 + *c.Policies[0].Probe = true + c.DomainSets[0].Domains[0] = "*.different.test" + c.Rules[0].IPv4[0] = "192.0.2.2" + c.Interfaces[0] = "changed" + p := ResolvePreference(first, &first.Devices[0], "a.media.test") + if p.Mode != "ipv6" || p.DelayMS != 90 || p.Probe || first.Interfaces[0] != "br-lan" || first.Rules[0].IPv4[0] != "192.0.2.1" { + t.Fatal("caller mutation leaked into snapshot", p) + } + e.SetConfig(c) + if e.Config().fingerprint == first.fingerprint { + t.Fatal("configuration change did not isolate evidence") + } +} +func TestBadProfileApplyKeepsCurrentPolicyAndFirewall(t *testing.T) { + m, f := testManager(t) + if err := m.Apply(context.Background(), true); err != nil { + t.Fatal(err) + } + previous := m.Engine.Config() + f.calls = nil + f.config += "\nconfig policy 'broken'\n option profile 'missing'\n option domain '*'\n" + if err := m.Apply(context.Background(), true); err == nil { + t.Fatal("bad profile accepted") + } + if m.Engine.Config() != previous || !f.table || !m.Status().Active { + t.Fatal("failed validation altered live state") + } + for _, call := range f.calls { + if call.name != "uci" || strings.Join(call.args, " ") != "-q export netpreference" { + t.Fatal("wrote before validation", call) + } + } +} +func FuzzDomainSetMatchesLinearReference(f *testing.F) { + f.Add("*.example.com,api.example.com,*", "API.Example.Com.") + f.Add("*.example.com,*.sub.example.com", "notexample.com") + f.Fuzz(func(t *testing.T, patterns, name string) { + if len(patterns) > 4096 || len(name) > 253 { + return + } + var list []string + for _, p := range strings.Split(patterns, ",") { + p = normalizeDomain(p) + if ValidDomain(p) { + list = append(list, p) + } + } + if len(list) > 32 { + return + } + name = normalizeQueryName(name) + got, pattern := newDomainMatcher(list).match(name) + want := -1 + for _, p := range list { + if s := domainScore(p, name); s > want { + want = s + } + } + if got != want || got >= 0 && domainScore(pattern, name) != got { + t.Fatalf("%q %q: got %d/%q want %d", patterns, name, got, pattern, want) + } + }) +} + +func TestQueryWhitespaceIsNotConfigurationPadding(t *testing.T) { + c := profileConfig() + c.DomainSets[0].Domains = []string{"api", "*.media.test"} + c.Policies = []Policy{{ID: "timing", Enabled: true, Profile: "work", DomainSet: "media", Mode: "ipv6"}} + c.Rules = []Rule{{ID: "local", Enabled: true, Domain: "api", Action: "nxdomain"}} + if err := c.Validate(); err != nil { + t.Fatal(err) + } + for _, name := range []string{"api ", " api", "media.test ", " sub.media.test "} { + if p := ResolvePreference(&c, &c.Devices[0], name); p.Policy != "" { + t.Fatal("trimmed query matched timing", name) + } + if r := MatchRule(&c, &c.Devices[0], Question{Name: name, Type: TypeA}); r != nil { + t.Fatal("trimmed query matched action", name) + } + } +} + +func TestCustomDomainInheritsEffectiveDeviceFamily(t *testing.T) { + d := DefaultDevice() + d.Mode = "ipv4" + d.Prefer = "ipv6" + p := Policy{Mode: "custom"} + if got := applyPolicy(&d, &p); got.Preferred() != TypeA { + t.Fatal(got) + } + d.Mode = "ipv6" + d.Prefer = "ipv4" + if got := applyPolicy(&d, &p); got.Preferred() != TypeAAAA { + t.Fatal(got) + } + p.Prefer = "ipv4" + if got := applyPolicy(&d, &p); got.Preferred() != TypeA { + t.Fatal(got) + } +} diff --git a/internal/netpref/runtime.go b/internal/netpref/runtime.go index 2257532..a5bb060 100644 --- a/internal/netpref/runtime.go +++ b/internal/netpref/runtime.go @@ -11,6 +11,7 @@ import ( "net/http" "os" "path/filepath" + "slices" "strings" "sync" "sync/atomic" @@ -140,7 +141,8 @@ func (m *Manager) Apply(ctx context.Context, force bool) error { m.lastErr = e.Error() return e } - if _, e = m.Firewall.Inspect(ctx); e != nil { + exists, e := m.Firewall.Inspect(ctx) + if e != nil { m.lastErr = e.Error() return e } @@ -155,7 +157,19 @@ func (m *Manager) Apply(ctx context.Context, force bool) error { return e } hosts := m.Inventory.Hosts() - if e = m.Firewall.Apply(ctx, &c, hosts); e != nil { + // DNS/profile-only changes need no table replacement. Named counters stay + // alive while selected MAC/address sets are refreshed atomically. + rebuild := !exists || !old.Enabled || old.Monitor != c.Monitor || + !slices.Equal(old.Interfaces, c.Interfaces) || !sameHosts(oldhosts, hosts) + if rebuild { + if old.Enabled && old.Monitor { + m.Traffic.Sample(ctx, oldhosts) + } + e = m.Firewall.Apply(ctx, &c, hosts) + } else { + e = m.Firewall.Refresh(ctx, &c, hosts, true) + } + if e != nil { _ = m.Inventory.Refresh(ctx, &old) m.lastErr = e.Error() return e @@ -173,6 +187,7 @@ func (m *Manager) Apply(ctx context.Context, force bool) error { var rollback error if old.Enabled { rollback = m.Firewall.Apply(ctx, &old, oldhosts) + m.Traffic.Rebase() } else { rollback = m.Firewall.Remove(ctx) } @@ -198,8 +213,13 @@ func (m *Manager) Apply(ctx context.Context, force bool) error { m.Engine.SetConfig(c) m.active = true m.lastErr = "" - m.Traffic.Reset() - if !c.Monitor { + if rebuild { + m.Traffic.Rebase() + } + if c.Monitor { + // An enabled monitor is never advertised as off while awaiting first tick. + m.Traffic.Sample(ctx, hosts) + } else { m.Traffic.Off() } return nil @@ -260,6 +280,15 @@ func (m *Manager) Tick(ctx context.Context) { return } hosts := m.Inventory.Hosts() + // Observation is a read-only activity, independent of DNS health. Even on + // a fail-open return, publish fresh samples or an explicit diagnostic error. + defer func() { + if c.Monitor { + m.Traffic.Sample(ctx, hosts) + } else { + m.Traffic.Off() + } + }() healthy := m.Health(ctx, &c) == nil if !healthy { m.active = false @@ -286,8 +315,13 @@ func (m *Manager) Tick(ctx context.Context) { exists, er := m.Firewall.Inspect(ctx) if er == nil { if !exists || !sameHosts(m.hosts, hosts) { + if c.Monitor && exists { + m.Traffic.Sample(ctx, m.hosts) + } er = m.Firewall.Apply(ctx, &c, hosts) - m.Traffic.Reset() + if er == nil { + m.Traffic.Rebase() + } } else { er = m.Firewall.Refresh(ctx, &c, hosts, true) } @@ -305,11 +339,6 @@ func (m *Manager) Tick(ctx context.Context) { m.active = true m.Engine.SetConfig(c) m.lastErr = "" - if c.Monitor { - m.Traffic.Sample(ctx, hosts) - } else { - m.Traffic.Off() - } } func (m *Manager) pauseLocked(ctx context.Context, c Config, err error) { m.active = false @@ -406,7 +435,7 @@ func ListenControl(path string, m *Manager) (*ControlServer, error) { var c Config c, err = LoadConfig(r.Context(), m.Runner) if err == nil { - result = map[string]any{"valid": true, "devices": len(c.Devices), "rules": len(c.Rules)} + result = map[string]any{"valid": true, "devices": len(c.Devices), "rules": len(c.Rules), "profiles": len(c.Profiles), "domain_sets": len(c.DomainSets), "policies": len(c.Policies)} } default: w.WriteHeader(404) diff --git a/internal/netpref/test_sockets_test.go b/internal/netpref/test_sockets_test.go new file mode 100644 index 0000000..650c2bb --- /dev/null +++ b/internal/netpref/test_sockets_test.go @@ -0,0 +1,126 @@ +package netpref + +import ( + "errors" + "fmt" + "net" + "syscall" + "testing" +) + +const fixtureBindAttempts = 16 + +// Test-only allocation: TCP and UDP have separate port namespaces. Reserve the +// TCP ephemeral port first, then bind UDP without releasing that reservation. +// Retry only EADDRINUSE during setup; never retry queries or their assertions. +func fixtureSocketPair(openTCP func() (net.Listener, error), openUDP func(net.Addr) (*net.UDPConn, error)) (*net.UDPConn, net.Listener, error) { + for i := 0; i < fixtureBindAttempts; i++ { + tcp, err := openTCP() + if err != nil { + return nil, nil, err + } + udp, err := openUDP(tcp.Addr()) + if err == nil { + return udp, tcp, nil + } + tcp.Close() + if !errors.Is(err, syscall.EADDRINUSE) { + return nil, nil, err + } + } + return nil, nil, fmt.Errorf("fixture exhausted %d port reservations: %w", fixtureBindAttempts, syscall.EADDRINUSE) +} + +func listenFixtureUpstream() (*net.UDPConn, net.Listener, error) { + return fixtureSocketPair(func() (net.Listener, error) { + return net.Listen("tcp4", "127.0.0.1:0") + }, func(addr net.Addr) (*net.UDPConn, error) { + a, err := net.ResolveUDPAddr("udp4", addr.String()) + if err != nil { + return nil, err + } + return net.ListenUDP("udp4", a) + }) +} + +// The production listener deliberately fails on a occupied fixed port. Tests +// request port 0 instead, so only transient allocation collisions may be retried. +func listenFixtureDNS(addr string, e *Engine, identify func(net.IP) string) (*DNSService, error) { + _, port, err := net.SplitHostPort(addr) + if err != nil || port != "0" { + return nil, fmt.Errorf("fixture listener requires an ephemeral port: %q", addr) + } + for i := 0; i < fixtureBindAttempts; i++ { + s, err := ListenDNS(addr, e, identify) + if !errors.Is(err, syscall.EADDRINUSE) { + return s, err + } + } + return nil, fmt.Errorf("fixture DNS exhausted port reservations: %w", syscall.EADDRINUSE) +} + +type reservationFixture struct{ closed bool } + +func (*reservationFixture) Accept() (net.Conn, error) { return nil, errors.New("unused accept") } +func (r *reservationFixture) Close() error { r.closed = true; return nil } +func (*reservationFixture) Addr() net.Addr { + return &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 12345} +} + +func TestFixturePortCollisionReleasesReservation(t *testing.T) { + var reservations []*reservationFixture + udp := new(net.UDPConn) // Sentinel; this allocation test does not perform IO. + u, tcp, err := fixtureSocketPair(func() (net.Listener, error) { + r := new(reservationFixture) + reservations = append(reservations, r) + return r, nil + }, func(net.Addr) (*net.UDPConn, error) { + if len(reservations) == 1 { + return nil, &net.OpError{Op: "listen", Net: "udp4", Err: syscall.EADDRINUSE} + } + return udp, nil + }) + if err != nil || u != udp || len(reservations) != 2 || tcp != reservations[1] { + t.Fatalf("wrong retry result: %v, reservations=%d", err, len(reservations)) + } + if !reservations[0].closed || reservations[1].closed { + t.Fatal("failed reservation leaked, or successful reservation closed early") + } + tcp.Close() +} + +func TestFixturePortAllocationBoundsAndOtherErrors(t *testing.T) { + for _, failure := range []error{syscall.EADDRINUSE, syscall.EACCES} { + var reservations []*reservationFixture + u, tcp, err := fixtureSocketPair(func() (net.Listener, error) { + r := new(reservationFixture) + reservations = append(reservations, r) + return r, nil + }, func(net.Addr) (*net.UDPConn, error) { return nil, failure }) + want := 1 + if failure == syscall.EADDRINUSE { + want = fixtureBindAttempts + } + if u != nil || tcp != nil || !errors.Is(err, failure) || len(reservations) != want { + t.Fatalf("unexpected retry/return: %v, reservations=%d", err, len(reservations)) + } + for _, r := range reservations { + if !r.closed { + t.Fatal("failed socket reservation leaked") + } + } + } + _, _, err := fixtureSocketPair(func() (net.Listener, error) { return nil, syscall.EACCES }, + func(net.Addr) (*net.UDPConn, error) { t.Fatal("UDP called after TCP failure"); return nil, nil }) + if !errors.Is(err, syscall.EACCES) { + t.Fatal(err) + } +} + +func TestFixtureServiceRejectsFixedPort(t *testing.T) { + for _, addr := range []string{"127.0.0.1:1053", "invalid"} { + if s, err := listenFixtureDNS(addr, nil, nil); err == nil || s != nil { + t.Fatal("test-only retry helper must not hide fixed port conflicts", addr) + } + } +} diff --git a/internal/netpref/testdata/fuzz/FuzzDomainSetMatchesLinearReference/1b80e8a98011dc15 b/internal/netpref/testdata/fuzz/FuzzDomainSetMatchesLinearReference/1b80e8a98011dc15 new file mode 100644 index 0000000..42a9856 --- /dev/null +++ b/internal/netpref/testdata/fuzz/FuzzDomainSetMatchesLinearReference/1b80e8a98011dc15 @@ -0,0 +1,3 @@ +go test fuzz v1 +string("0") +string("0..") diff --git a/internal/netpref/testdata/fuzz/FuzzDomainSetMatchesLinearReference/8a7e95f812a8d963 b/internal/netpref/testdata/fuzz/FuzzDomainSetMatchesLinearReference/8a7e95f812a8d963 new file mode 100644 index 0000000..2d3a5f6 --- /dev/null +++ b/internal/netpref/testdata/fuzz/FuzzDomainSetMatchesLinearReference/8a7e95f812a8d963 @@ -0,0 +1,3 @@ +go test fuzz v1 +string("*.example.com,api,example.com.*") +string("API .") diff --git a/internal/netpref/traffic.go b/internal/netpref/traffic.go index 7abd0e9..bf682d6 100644 --- a/internal/netpref/traffic.go +++ b/internal/netpref/traffic.go @@ -3,7 +3,9 @@ package netpref import ( "context" "encoding/json" + "fmt" "strconv" + "strings" "sync" "time" ) @@ -22,14 +24,18 @@ type Rates struct { Valid bool `json:"valid"` } type TrafficRow struct { - Host Host `json:"host"` - Totals HostTotals `json:"totals"` - V4 Rates `json:"ipv4_rate"` - V6 Rates `json:"ipv6_rate"` - IPv6Ratio float64 `json:"ipv6_ratio"` + Host Host `json:"host"` + Totals HostTotals `json:"totals"` + V4 Rates `json:"ipv4_rate"` + V6 Rates `json:"ipv6_rate"` + IPv6Ratio float64 `json:"ipv6_ratio"` + V4Available bool `json:"ipv4_available"` + V6Available bool `json:"ipv6_available"` } type TrafficSnapshot struct { Enabled bool `json:"enabled"` + State string `json:"state"` + MissingCounters []string `json:"missing_counters,omitempty"` At string `json:"at"` Interval float64 `json:"interval_seconds"` TotalsAvailable bool `json:"totals_available"` @@ -43,8 +49,10 @@ func ParseCounters(b []byte) (map[string]uint64, error) { var v struct { NFTables []struct { Counter *struct { - Name string - Bytes json.Number + Name string + Family string + Table string + Bytes json.Number } `json:"counter"` } `json:"nftables"` } @@ -54,10 +62,16 @@ func ParseCounters(b []byte) (map[string]uint64, error) { out := map[string]uint64{} for _, r := range v.NFTables { if r.Counter != nil { + if (r.Counter.Family != "" && r.Counter.Family != "inet") || (r.Counter.Table != "" && r.Counter.Table != TableName) { + continue + } n, e := strconv.ParseUint(string(r.Counter.Bytes), 10, 64) if e != nil { return nil, e } + if _, exists := out[r.Counter.Name]; exists { + return nil, fmt.Errorf("duplicate named counter %s", r.Counter.Name) + } out[r.Counter.Name] = n } } @@ -74,7 +88,7 @@ type Traffic struct { } func NewTraffic(r Runner) *Traffic { - return &Traffic{runner: r, totals: map[string]HostTotals{}} + return &Traffic{runner: r, totals: map[string]HostTotals{}, snapshot: TrafficSnapshot{State: "off", Rows: []TrafficRow{}}} } func (t *Traffic) Reset() { t.mu.Lock() @@ -82,7 +96,16 @@ func (t *Traffic) Reset() { t.prev = nil t.totals = map[string]HostTotals{} t.at = time.Time{} - t.snapshot = TrafficSnapshot{Rows: []TrafficRow{}} + t.snapshot = TrafficSnapshot{State: "off", Rows: []TrafficRow{}} +} + +// Rebase invalidates only the raw-counter generation. Completed diagnostic +// totals survive profile changes, host discovery and owned table recreation. +func (t *Traffic) Rebase() { + t.mu.Lock() + defer t.mu.Unlock() + t.prev = nil + t.at = time.Time{} } func (t *Traffic) Off() { t.mu.Lock() @@ -90,17 +113,20 @@ func (t *Traffic) Off() { t.prev = nil t.totals = map[string]HostTotals{} t.at = time.Time{} - t.snapshot = TrafficSnapshot{Rows: []TrafficRow{}} + t.snapshot = TrafficSnapshot{State: "off", Rows: []TrafficRow{}} } func (t *Traffic) Snapshot() TrafficSnapshot { t.mu.RLock(); defer t.mu.RUnlock(); return t.snapshot } func (t *Traffic) Sample(ctx context.Context, hosts []Host) { - now := time.Now() + t.sampleAt(ctx, hosts, time.Now()) +} +func (t *Traffic) sampleAt(ctx context.Context, hosts []Host, now time.Time) { s := TrafficSnapshot{ Enabled: true, + State: "warming_up", At: now.UTC().Format(time.RFC3339), Rows: []TrafficRow{}, - Source: "rates and session totals=nft software-path counters", - Caveat: "Session totals are diagnostic only and reset when monitoring/service counters reset. Flow/hardware offload can undercount traffic that bypasses the software path.", + Source: "LAN family rates and session totals=nft software-path counters", + Caveat: "Session totals are diagnostic only. They reset on monitoring disable/service restart, not profile changes. Counter gaps are not estimated. Includes router/local-proxy traffic; client-facing IP family is not the proxy WAN family. Flow/hardware offload can undercount bypassed traffic.", } b, e := t.runner.Run(ctx, "nft", []string{"-j", "list", "table", "inet", TableName}, nil) @@ -109,8 +135,23 @@ func (t *Traffic) Sample(ctx context.Context, hosts []Host) { counters, e = ParseCounters(b) } s.TotalsAvailable = e == nil + if e == nil { + for _, h := range hosts { + for _, suffix := range []string{"_4_up", "_4_down", "_6_up", "_6_down"} { + name := counterPrefix(h.MAC) + suffix + if _, ok := counters[name]; !ok { + s.MissingCounters = append(s.MissingCounters, name) + } + } + } + if len(s.MissingCounters) > 0 { + s.TotalsAvailable = false + e = fmt.Errorf("missing %d named counters (%s); check the owned nft table and LAN discovery", len(s.MissingCounters), strings.Join(s.MissingCounters, ", ")) + } + } if e != nil { s.Error = "traffic counters: " + e.Error() + s.State = "unavailable" } t.mu.Lock() @@ -122,26 +163,26 @@ func (t *Traffic) Sample(ctx context.Context, hosts []Host) { s.Interval = now.Sub(t.at).Seconds() } - sampleFamily := func(prefix string, total *Totals) Rates { + sampleFamily := func(prefix string, total *Totals) (Rates, bool) { u, uok := counters[prefix+"_up"] d, dok := counters[prefix+"_down"] pu, puok := t.prev[prefix+"_up"] pd, pdok := t.prev[prefix+"_down"] valid := uok && dok && puok && pdok && u >= pu && d >= pd && s.Interval > 0 if !valid { - return Rates{} + return Rates{}, uok && dok } du, dd := u-pu, d-pd total.Up += du total.Down += dd - return Rates{float64(du) / s.Interval, float64(dd) / s.Interval, true} + return Rates{float64(du) / s.Interval, float64(dd) / s.Interval, true}, true } for _, h := range hosts { v := t.totals[h.MAC] p := counterPrefix(h.MAC) - v4 := sampleFamily(p+"_4", &v.V4) - v6 := sampleFamily(p+"_6", &v.V6) + v4, a4 := sampleFamily(p+"_4", &v.V4) + v6, a6 := sampleFamily(p+"_6", &v.V6) t.totals[h.MAC] = v all := v.V4.Up + v.V4.Down + v.V6.Up + v.V6.Down @@ -149,7 +190,13 @@ func (t *Traffic) Sample(ctx context.Context, hosts []Host) { if all > 0 { ratio = float64(v.V6.Up+v.V6.Down) / float64(all) } - s.Rows = append(s.Rows, TrafficRow{h, v, v4, v6, ratio}) + s.Rows = append(s.Rows, TrafficRow{Host: h, Totals: v, V4: v4, V6: v6, IPv6Ratio: ratio, V4Available: a4, V6Available: a6}) + if e == nil && v4.Valid && v6.Valid { + s.State = "ready" + } + if e != nil && (a4 || a6) { + s.State = "partial" + } } t.prev = counters t.at = now diff --git a/internal/netpref/traffic_runtime_test.go b/internal/netpref/traffic_runtime_test.go new file mode 100644 index 0000000..2553579 --- /dev/null +++ b/internal/netpref/traffic_runtime_test.go @@ -0,0 +1,170 @@ +package netpref + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "strings" + "testing" + "time" +) + +// Same named objects emitted by nft -j list table, including the ownership +// marker used by the runtime. This exercises more than the view's JSON labels. +func trafficObjects(v int) string { + return fmt.Sprintf(`{"nftables":[{"table":{"family":"inet","name":"netpreference","comment":%q}},{"counter":{"family":"inet","table":"netpreference","name":"m020000000001_4_up","bytes":%d}},{"counter":{"name":"m020000000001_4_down","bytes":%d}},{"counter":{"name":"m020000000001_6_up","bytes":%d}},{"counter":{"name":"m020000000001_6_down","bytes":%d}}]}`, OwnerComment, v, v*2, v*3, v*4) +} +func monitoredManager(t *testing.T) (*Manager, *fakeRunner) { + t.Helper() + m, f := testManager(t) + f.config = strings.Replace(f.config, "option enabled '0'", "option enabled '1'\n option monitor '1'", 1) + f.counters = trafficObjects(100) + if err := m.Apply(context.Background(), false); err != nil { + t.Fatal(err) + } + return m, f +} +func TestTrafficRuntimeImmediateEnabled(t *testing.T) { + m, _ := monitoredManager(t) + if !m.Traffic.Snapshot().Enabled { + t.Fatal("monitor configured on but initial runtime snapshot reports off") + } +} +func TestTrafficMissingObjectsAreNotAvailable(t *testing.T) { + tr := NewTraffic(&fakeRunner{counters: `{"nftables":[]}`}) + tr.Sample(context.Background(), []Host{{MAC: "02:00:00:00:00:01"}}) + if s := tr.Snapshot(); s.TotalsAvailable || s.Error == "" { + t.Fatalf("missing named counters silently marked available: %+v", s) + } +} +func TestTrafficProfileReloadPreservesCountersAndSession(t *testing.T) { + m, f := monitoredManager(t) + ctx := context.Background() + m.Traffic.Sample(ctx, m.hosts) + time.Sleep(time.Millisecond) + f.counters = trafficObjects(200) + m.Tick(ctx) + before := m.Traffic.Snapshot() + if len(before.Rows) != 1 || before.Rows[0].Totals.V6.Down != 400 { + t.Fatal(before) + } + f.config += "\nconfig profile 'daily'\n option name 'Daily'\n" + start := len(f.calls) + if err := m.Apply(ctx, false); err != nil { + t.Fatal(err) + } + for _, call := range f.calls[start:] { + if call.name == "nft" && strings.Contains(call.input, "delete table") { + t.Fatal("profile-only change rebuilt all traffic counters") + } + } + after := m.Traffic.Snapshot() + if len(after.Rows) != 1 || after.Rows[0].Totals != before.Rows[0].Totals { + t.Fatal("profile Apply erased accumulated traffic", after) + } + // Verify the same live object survives the control socket boundary. + srv, err := ListenControl(t.TempDir()+"/control.sock", m) + if err != nil { + t.Fatal(err) + } + defer srv.Close() + raw, err := Control(ctx, srv.path, "traffic") + if err != nil { + t.Fatal(err) + } + var rpc TrafficSnapshot + if err = json.Unmarshal(raw, &rpc); err != nil { + t.Fatal(err) + } + if rpc.Rows[0].Totals != after.Rows[0].Totals || rpc.Rows[0].IPv6Ratio != 0.7 { + t.Fatal("runtime/control contract lost family totals", string(raw)) + } +} +func TestTrafficContinuesDuringDNSFailOpen(t *testing.T) { + m, f := monitoredManager(t) + ctx := context.Background() + m.Traffic.Sample(ctx, m.hosts) + time.Sleep(time.Millisecond) + m.Health = func(context.Context, *Config) error { return errors.New("upstream DNS unavailable") } + f.counters = trafficObjects(300) + m.Tick(ctx) + s := m.Traffic.Snapshot() + if m.Status().Active || m.Engine.Config().Enabled { + t.Fatal("DNS failure did not fail open") + } + if len(s.Rows) != 1 || s.Rows[0].Totals.V4.Up != 200 || s.Rows[0].Totals.V6.Down != 800 { + t.Fatal("DNS health failure stopped independent traffic observation", s) + } +} + +func TestObservationIncludesRouterLocalProxyPath(t *testing.T) { + c := DefaultConfig() + c.Monitor = true + rules := BuildNFT(&c, []Host{{MAC: "02:00:00:00:00:01", IPv4: []string{"192.0.2.2"}, IPv6: []string{"fd42::2"}}}, false) + for _, hook := range []string{"chain observe_upload { type filter hook prerouting priority -310", "chain observe_download { type filter hook postrouting priority 310"} { + if !strings.Contains(rules, hook) { + t.Fatal("traffic must include INPUT/OUTPUT proxy paths", rules) + } + } + if strings.Contains(rules, "hook forward") { + t.Fatal("double counting with an additional forward counter") + } + c.Monitor = false + rules = BuildNFT(&c, nil, false) + if strings.Contains(rules, "chain observe") { + t.Fatal("monitor off installed observation rules") + } +} + +func TestTrafficIndependentFamiliesMissingResetAndGap(t *testing.T) { + f := &fakeRunner{counters: trafficObjects(100)} + tr := NewTraffic(f) + ctx := context.Background() + hosts := []Host{{MAC: "02:00:00:00:00:01"}} + now := time.Unix(100, 0) + tr.sampleAt(ctx, hosts, now) + f.counters = trafficObjects(200) + tr.sampleAt(ctx, hosts, now.Add(2*time.Second)) + s := tr.Snapshot() + if s.Rows[0].V4.Up != 50 || s.Rows[0].V6.Down != 200 || s.Rows[0].IPv6Ratio != 0.7 { + t.Fatal(s) + } + tr.Rebase() + f.counters = trafficObjects(1000) + tr.sampleAt(ctx, hosts, now.Add(3*time.Second)) + if s = tr.Snapshot(); s.Rows[0].V4.Valid || s.Rows[0].Totals.V6.Down != 400 { + t.Fatal("cross-generation spike/reset", s) + } + f.counters = trafficObjects(1100) + tr.sampleAt(ctx, hosts, now.Add(5*time.Second)) + if s = tr.Snapshot(); s.Rows[0].Totals.V4.Up != 200 || s.Rows[0].Totals.V6.Down != 800 { + t.Fatal(s) + } + f.counters = `{"nftables":[{"counter":{"name":"m020000000001_4_up","bytes":1200}},{"counter":{"name":"m020000000001_4_down","bytes":2400}}]}` + tr.sampleAt(ctx, hosts, now.Add(7*time.Second)) + s = tr.Snapshot() + if s.State != "partial" || s.TotalsAvailable || !s.Rows[0].V4Available || s.Rows[0].V6Available || !s.Rows[0].V4.Valid || s.Rows[0].V6.Valid || len(s.MissingCounters) != 2 { + t.Fatal(s) + } + f.counters = `broken` + tr.sampleAt(ctx, hosts, now.Add(9*time.Second)) + s = tr.Snapshot() + if s.State != "unavailable" || !s.Enabled || s.Rows[0].V4.Valid || s.Error == "" { + t.Fatal(s) + } + f.counters = trafficObjects(2000) + tr.sampleAt(ctx, hosts, now.Add(11*time.Second)) + s = tr.Snapshot() + if s.Rows[0].V4.Valid || s.Rows[0].Totals.V4.Up != 300 || s.Rows[0].Totals.V6.Down != 800 { + t.Fatal("gap estimated rather than rebased", s) + } + for _, data := range []string{ + `{"nftables":[{"counter":{"name":"x","bytes":-1}}]}`, + `{"nftables":[{"counter":{"name":"x","bytes":1}},{"counter":{"name":"x","bytes":2}}]}`, + } { + if _, err := ParseCounters([]byte(data)); err == nil { + t.Fatal("invalid counters accepted", data) + } + } +} diff --git a/internal/netpref/udp_linux_test.go b/internal/netpref/udp_linux_test.go index 6c92125..a808302 100644 --- a/internal/netpref/udp_linux_test.go +++ b/internal/netpref/udp_linux_test.go @@ -15,7 +15,7 @@ func TestWildcardUDPReplySource(t *testing.T) { c.Upstream = up for _, bind := range []string{"0.0.0.0:0", "[::]:0"} { t.Run(bind, func(t *testing.T) { - s, err := ListenDNS(bind, NewEngine(c), func(net.IP) string { return testMAC }) + s, err := listenFixtureDNS(bind, NewEngine(c), func(net.IP) string { return testMAC }) if err != nil { t.Fatal(err) } diff --git a/internal/netpref/ui_roundtrip_test.go b/internal/netpref/ui_roundtrip_test.go new file mode 100644 index 0000000..9ea4475 --- /dev/null +++ b/internal/netpref/ui_roundtrip_test.go @@ -0,0 +1,47 @@ +package netpref + +import ( + "os" + "testing" +) + +// The input is emitted by the real front-end model during its contract test, +// then validated by the CLI. CI runs this explicitly after generating it. +func TestGeneratedUILibraryPreference(t *testing.T) { + path := os.Getenv("NETPREFERENCE_UI_CONFIG") + if path == "" { + t.Skip("run after Node contract with NETPREFERENCE_UI_CONFIG=dist/ux-generated.uci") + } + raw, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + c, err := ParseUCI(string(raw)) + if err != nil { + t.Fatal(err) + } + d := &c.Devices[0] + if d.Mode != "ipv4" || d.WaitMS != 120 || d.DelayMS != 80 { + t.Fatal("device defaults mutated", d) + } + for _, tc := range []struct { + name, mode string + a, b int + probe bool + }{ + {"openai.com", "ipv6", 120, 80, true}, {"api.openai.com", "ipv6", 120, 80, true}, + {"deep.api.openai.com", "ipv6", 120, 80, true}, {"notopenai.com", "ipv4", 120, 80, true}, + {"youtube.com", "ipv4", 0, 160, true}, {"www.youtube.com", "ipv4", 0, 160, true}, + {"games.test", "custom", 40, 90, false}, {"a.games.test", "custom", 40, 90, false}, + {"example.com", "dual", 120, 80, true}, {"sub.example.com", "dual", 120, 80, true}, + {"unmatched.test", "ipv4", 120, 80, true}, + } { + p := ResolvePreference(&c, d, tc.name) + if p.Mode != tc.mode || p.WaitMS != tc.a || p.DelayMS != tc.b || p.Probe != tc.probe { + t.Errorf("%s: %+v", tc.name, p) + } + } + if r := MatchRule(&c, d, Question{Name: "bad.test", Type: TypeA}); r == nil || r.Action != "nxdomain" { + t.Fatal("legacy DNS action lost", r) + } +} diff --git a/openwrt/luci-app-netpreference/Makefile b/openwrt/luci-app-netpreference/Makefile index ea0e4ae..e10ad4d 100644 --- a/openwrt/luci-app-netpreference/Makefile +++ b/openwrt/luci-app-netpreference/Makefile @@ -1,8 +1,8 @@ include $(TOPDIR)/rules.mk PKG_NAME:=luci-app-netpreference -PKG_VERSION:=0.1.0 -PKG_RELEASE:=6 +PKG_VERSION:=0.2.0 +PKG_RELEASE:=2 PKG_LICENSE:=MIT PKG_MAINTAINER:=LE-saber PKG_BUILD_DEPENDS:=golang/host @@ -43,6 +43,7 @@ define Package/luci-app-netpreference/install chmod 0755 $(1)/etc/init.d/netpreference $(1)/usr/libexec/rpcd/netpreference $(INSTALL_DIR) $(1)/usr/share/netpreference $(INSTALL_DATA) $(NETPREFERENCE_SRC)/LICENSE $(1)/usr/share/netpreference/LICENSE + $(INSTALL_DATA) $(NETPREFERENCE_SRC)/docs/LICENSE-Go $(1)/usr/share/netpreference/LICENSE-Go endef define Package/luci-app-netpreference/postinst diff --git a/scripts/build_legacy.sh b/scripts/build_legacy.sh new file mode 100644 index 0000000..9c34588 --- /dev/null +++ b/scripts/build_legacy.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Build the real released r6 source for upgrade-format testing, never relabel new code. +set -euo pipefail +ROOT=$(cd "$(dirname "$0")/.." && pwd) +BASE=38a69cbb529eb8fc1b820fa00d7cc439306112f4 +OUT=${1:-"$ROOT/dist-legacy"} +WORK=$(mktemp -d /tmp/netpreference-legacy-XXXXXX) +trap 'rm -rf "$WORK"' EXIT +cd "$ROOT" +git cat-file -e "$BASE:go.mod" +git archive "$BASE" | tar -xf - -C "$WORK" +grep -q '^PKG_VERSION:=0.1.0$' "$WORK/openwrt/luci-app-netpreference/Makefile" +grep -q '^PKG_RELEASE:=6$' "$WORK/openwrt/luci-app-netpreference/Makefile" +python3 "$WORK/scripts/build_ipk.py" --out "$OUT" +test -s "$OUT/luci-app-netpreference_0.1.0-r6_x86_64.ipk" diff --git a/scripts/check.sh b/scripts/check.sh index bf95771..26173a3 100755 --- a/scripts/check.sh +++ b/scripts/check.sh @@ -8,9 +8,13 @@ go test -race -coverprofile=dist/coverage.out -v ./... | tee dist/logs/go-tests. go vet ./... 2>&1 | tee dist/logs/go-vet.txt go test ./internal/netpref -run '^$' -fuzz '^FuzzDNSWire$' -fuzztime=3s -parallel=1 | tee dist/logs/fuzz-dns.txt go test ./internal/netpref -run '^$' -fuzz '^FuzzUCITokens$' -fuzztime=3s -parallel=1 | tee dist/logs/fuzz-uci.txt +go test ./internal/netpref -run '^$' -fuzz '^FuzzDomainSetMatchesLinearReference$' -fuzztime=30s -parallel=2 | tee dist/logs/fuzz-domains.txt python3 scripts/build_ipk.py | tee dist/logs/build.txt python3 tests/test_package.py 2>&1 | tee dist/logs/package.txt +python3 tests/test_workflows.py 2>&1 | tee dist/logs/workflows.txt +node tests/library_model.js | tee dist/logs/library-model.txt node tests/luci_contract.js | tee dist/logs/luci-contract.txt +NETPREFERENCE_UI_CONFIG="$(pwd)/dist/ux-generated.uci" go test ./internal/netpref -run TestGeneratedUILibraryPreference -count=1 -v | tee dist/logs/ui-backend-roundtrip.txt python3 -m py_compile tests/*.py scripts/*.py for script in files/etc/init.d/netpreference files/usr/libexec/rpcd/netpreference packaging/*; do sh -n "$script"; done printf '%s\n' 'PASS: local test suite. Kernel and rootfs tests are separate.' diff --git a/scripts/ci_failure.py b/scripts/ci_failure.py index afe4387..d929bb9 100755 --- a/scripts/ci_failure.py +++ b/scripts/ci_failure.py @@ -1,28 +1,37 @@ #!/usr/bin/env python3 -"""Persist a single failed CI phase. No credentials or environment dumps.""" +"""Record one failed phase on a development push, never main or a PR branch. + +The CI recorder downloads only artifacts from the same run. Call separately for +individual failures; each creates its own reviewable commit. No environment or +credential dumps are included. +""" import os from pathlib import Path +import re import subprocess import sys + phase=sys.argv[1] -run=os.environ.get('GITHUB_RUN_ID','local') -attempt=os.environ.get('GITHUB_RUN_ATTEMPT','1') -path=Path('docs/failures')/f'ci-{run}-{attempt}-{phase}.md' +if not re.fullmatch(r'[a-z0-9_-]{1,40}',phase):raise SystemExit('invalid phase') +branch=os.environ.get('GITHUB_REF_NAME','') +if os.environ.get('GITHUB_EVENT_NAME')!='push' or branch in ('','main'): + raise SystemExit('failure commits are allowed only for non-main push events') +subprocess.run(['git','check-ref-format','--branch',branch],check=True,stdout=subprocess.DEVNULL) +run=os.environ.get('GITHUB_RUN_ID','local');attempt=os.environ.get('GITHUB_RUN_ATTEMPT','1') +path=Path('docs/failures/0.2.0-r2')/f'ci-{run}-{attempt}-{phase}.md' path.parent.mkdir(parents=True,exist_ok=True) -log=Path('dist/logs')/(phase+'.txt') -text=log.read_text(errors='replace')[-16000:] if log.exists() else 'No phase log was produced; inspect the workflow job steps.' +log=Path(sys.argv[2]) if len(sys.argv)>2 else Path('dist/logs')/(phase+'.txt') +text=log.read_text(errors='replace')[-16000:] if log.exists() else 'No phase log produced; inspect the job steps and outcomes artifact.' url='https://github.com/'+os.environ.get('GITHUB_REPOSITORY','LE-saber/NetPreference')+'/actions/runs/'+run -path.write_text(f'# CI failure: {phase}\n\nRun: {url}\n\nThis phase failed and is not verified. See the log below and subsequent recovery commits. No production router was modified.\n\n```text\n{text}\n```\n') -print(path) +sha=os.environ.get('GITHUB_SHA','unknown') +path.write_text(f'# CI failure: {phase}\n\nRun: {url}\n\nTested source: `{sha}`. Branch: `{branch}`.\n\nThis phase failed, and is NOT verified. See subsequent repair and successful run evidence. No production router was modified.\n\n```text\n{text}\n```\n') subprocess.run(['git','config','user.name','github-actions[bot]'],check=True) subprocess.run(['git','config','user.email','41898282+github-actions[bot]@users.noreply.github.com'],check=True) subprocess.run(['git','add',str(path)],check=True) subprocess.run(['git','commit','-m',f'docs: record {phase} failure for run {run}'],check=True) for retry in range(3): - subprocess.run(['git','fetch','origin','feat/mvp'],check=True) - subprocess.run(['git','rebase','origin/feat/mvp'],check=True) - pushed=subprocess.run(['git','push','origin','HEAD:feat/mvp']) - if pushed.returncode == 0: - break -else: - raise SystemExit('failed to push CI failure record after 3 rebased attempts') + subprocess.run(['git','fetch','origin',branch],check=True) + subprocess.run(['git','rebase','FETCH_HEAD'],check=True) + if subprocess.run(['git','push','origin',f'HEAD:refs/heads/{branch}']).returncode==0:break +else:raise SystemExit('failure record push failed after 3 non-forced attempts') +print(path) diff --git a/scripts/inspect_ipk.py b/scripts/inspect_ipk.py new file mode 100644 index 0000000..a8bdca5 --- /dev/null +++ b/scripts/inspect_ipk.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python3 +"""Validate a direct- or official-SDK-built package before artifact publication.""" +import argparse +import hashlib +import io +import json +from pathlib import Path +import subprocess +import tarfile +import tempfile + +import build_ipk + + +def members(blob): + with tarfile.open(fileobj=io.BytesIO(blob), mode='r:*') as tf: + result={} + for m in tf: + name=m.name.removeprefix('./') + p=Path(name) + if p.is_absolute() or '..' in p.parts:raise ValueError(f'unsafe archive path: {name}') + if m.isfile():result[name]=(tf.extractfile(m).read(),m.mode) + return result + + +def inspect(path): + outer=members(path.read_bytes()) + assert outer['debian-binary'][0].strip()==b'2.0' + control=members(outer['control.tar.gz'][0]);data=members(outer['data.tar.gz'][0]) + fields=dict(line.split(': ',1) for line in control['control'][0].decode().splitlines() if ': ' in line and not line.startswith(' ')) + assert fields['Package']=='luci-app-netpreference',fields + assert fields['Version']==build_ipk.VERSION,fields + assert fields['Architecture']=='x86_64',fields + assert b'/etc/config/netpreference' in control['conffiles'][0] + binary=data['usr/sbin/netpreference'][0];build_ipk.verify_elf(binary) + for suffix in ('overview.js','advanced.js'): + assert data['www/luci-static/resources/view/netpreference/'+suffix][0] + assert [name for name in data if name.startswith('etc/config/')]==['etc/config/netpreference'] + assert 'nlbwmon' not in fields.get('Depends','') + assert data['usr/share/netpreference/LICENSE-Go'][0] + with tempfile.TemporaryDirectory(prefix='netpreference-package-') as tmp: + exe=Path(tmp)/'netpreference';exe.write_bytes(binary);exe.chmod(0o755) + assert subprocess.check_output([str(exe),'version'],text=True).strip()==build_ipk.VERSION.split('-r')[0] + result={'package':path.name,'version':fields['Version'],'architecture':fields['Architecture'], + 'sha256':hashlib.sha256(path.read_bytes()).hexdigest(),'binary':'static linux/amd64', + 'source_sha':subprocess.check_output(['git','rev-parse','HEAD'],text=True).strip()} + print(json.dumps(result,indent=2)) + return result + +if __name__=='__main__': + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('package',type=Path) + args=parser.parse_args();inspect(args.package) diff --git a/tests/fixtures/legacy-r6.uci b/tests/fixtures/legacy-r6.uci new file mode 100644 index 0000000..7ff93b0 --- /dev/null +++ b/tests/fixtures/legacy-r6.uci @@ -0,0 +1,42 @@ +# Representative user-modified 0.1.0-r6 configuration. No new schema fields. +package netpreference +config global 'main' + option enabled '1' + option monitor '1' + list interface 'br-lan' + option upstream '127.0.0.1:53' + option timeout_ms '2000' +config device 'workstation' + option enabled '1' + option name 'Existing workstation' + option mac '02:00:00:00:00:01' + option mode 'custom' + option prefer 'ipv4' + option wait_ms '0' + option delay_ms '0' + option probe '0' + option upstream 'tcp://127.0.0.1:5333' +config device 'phone' + option enabled '0' + option mac '02:00:00:00:00:02' + option mode 'ipv6' + option wait_ms '250' + option delay_ms '150' +config rule 'legacy_static' + option enabled '1' + option device '02:00:00:00:00:01' + option domain '*.example.com' + option action 'rewrite' + list ipv4 '192.0.2.10' + list ipv6 '2001:db8::10' + option ttl '60' +config rule 'legacy_block' + option device '*' + option domain 'blocked.test' + option action 'nxdomain' +config rule 'legacy_upstream' + option device '*' + option domain 'resolver.test' + option qtype 'AAAA' + option action 'forward' + option upstream '127.0.0.1:6053' diff --git a/tests/fixtures/profiles.uci b/tests/fixtures/profiles.uci new file mode 100644 index 0000000..3a72713 --- /dev/null +++ b/tests/fixtures/profiles.uci @@ -0,0 +1,53 @@ +package netpreference +config global 'main' + option enabled '1' + list interface 'br-lan' + option upstream '127.0.0.1:53' +config device 'workstation' + option mac '02:00:00:00:00:01' + option mode 'ipv4' + option wait_ms '75' + option delay_ms '40' + option profile 'work' +config profile 'work' + option name 'Work mode' + option description 'Selected domains prefer IPv6; everything else keeps the device default.' +config profile 'travel' + option name 'Travel mode' +config domain_set 'media' + option name 'Media domains' + list domain '*.MEDIA.TEST.' + list domain 'video.test' +config policy 'media_v6' + option profile 'work' + option domain_set 'media' + option mode 'ipv6' + option wait_ms '250' + option delay_ms '150' +config policy 'zero_probe' + option profile 'work' + option domain 'zero.test' + option mode 'custom' + option prefer 'ipv4' + option wait_ms '0' + option delay_ms '0' + option probe '0' +config policy 'inherit_all' + option profile 'work' + option domain 'inherit.test' + option wait_ms '' + option delay_ms '' + option probe '' +config policy 'travel_dual' + option profile 'travel' + option domain '*' + option mode 'dual' +config rule 'legacy_block' + option device '*' + option domain 'blocked.test' + option action 'nxdomain' +config rule 'work_no6' + option profile 'work' + option domain 'restricted.test' + option qtype 'AAAA' + option action 'nodata' diff --git a/tests/library_model.js b/tests/library_model.js new file mode 100644 index 0000000..c989492 --- /dev/null +++ b/tests/library_model.js @@ -0,0 +1,18 @@ +'use strict'; +const assert=require('assert'),fs=require('fs'),path=require('path'); +const source=fs.readFileSync(path.join(__dirname,'../files/www/luci-static/resources/netpreference/library.js'),'utf8'); +const lib=new Function('baseclass',source)({extend:x=>x}); +for(const value of ['openai.com','OPENAI.COM.','*.openai.com','https://openai.com/chat','openai.com/path','.openai.com','openai\u3002com']){ + assert.equal(lib.domain(value),'*.openai.com',value); + assert.equal(lib.domain(lib.domain(value)),lib.domain(value)); +} +assert.equal(lib.domain('https://\u4f8b\u5b50.\u6d4b\u8bd5/path'),'*.xn--fsqu00a.xn--0zwm56d'); +assert.deepEqual(lib.domains('a.test\uff0cb.test\na.test; c.test #not-a-comment-inline'.split(' #')[0]),['*.a.test','*.b.test','*.c.test']); +for(const value of ['', '*.','a..b','a.*.b','http://a:bad','http://user:pass@a','javascript://evil','foo bar','a\\b'])assert.throws(()=>lib.domain(value),undefined,value); +assert.throws(()=>lib.domains('')); +assert.throws(()=>lib.domains(Array.from({length:257},(_,i)=>`d${i}.test`).join('\n'))); +// Real LuCI sections() may retain an option pending deletion, while get() +// returns the effective record. Serialization must use the latter. +const uci={sections(){return [{'.name':'p','.type':'policy',domain:'stale.test',domain_set:'set'}];},get(){return {'.name':'p','.type':'policy',domain_set:'set',name:"O'Reilly"};}}; +const text=lib.serialize(uci);assert(!text.includes('stale.test'));assert(text.includes("O'\\''Reilly")); +console.log('PASS: forgiving apex/subdomain, URL, IDN, normalization, bounds and effective UCI serialization.'); diff --git a/tests/luci_browser.py b/tests/luci_browser.py new file mode 100644 index 0000000..7fa9e77 --- /dev/null +++ b/tests/luci_browser.py @@ -0,0 +1,130 @@ +#!/usr/bin/env python3 +"""Chromium interactions on the real custom editor and real Go preflight. + +LuCI form/RPC/uci hosting is a documented API fixture, not a running router. +The separate rootfs test exercises the target's actual uci.js and /sbin/uci. +""" +import json +import os +from pathlib import Path +import shutil +import subprocess +from playwright.sync_api import sync_playwright + +ROOT = Path(__file__).resolve().parents[1] +BASE = ROOT / 'files/www/luci-static/resources' +OUT = ROOT / 'dist/browser' +OUT.mkdir(parents=True, exist_ok=True) + + +def check_config(text): + result = subprocess.run([str(ROOT / 'dist/netpreference'), 'rpc', 'call', 'check_config'], + input=json.dumps({'config': text}), text=True, capture_output=True, check=False) + return json.loads(result.stdout) + + +with sync_playwright() as pw: + browser = pw.chromium.launch(headless=True, executable_path=os.environ.get('CHROMIUM_BINARY') or shutil.which('chromium'), + args=['--no-sandbox']) + page = browser.new_page(viewport={'width': 1180, 'height': 900}, device_scale_factor=1) + errors = [] + page.on('pageerror', lambda error: errors.append(str(error))) + page.expose_function('npValidate', check_config) + page.set_content('
') + page.add_script_tag(content=(ROOT / 'tests/luci_harness.js').read_text()) + page.evaluate('''() => { + window.E=function(tag,attrs,children){ + const el=document.createElement(tag);attrs=attrs||{}; + Object.keys(attrs).forEach(k=>{const value=attrs[k];if(value==null)return; + if(typeof value==='function')el.addEventListener(k,value);else el.setAttribute(k,String(value)); + }); + (Array.isArray(children)?children:[children]).forEach(c=>{if(c!=null)el.append(c);});return el; + }; + window.h=NPTest.create(E,window.npValidate); + delete h.sections.pc.profile;delete h.sections.work;delete h.sections.media;delete h.sections.bias; + }''') + page.evaluate('(s)=>{window.lib=h.module(s)}', (BASE / 'netpreference/library.js').read_text()) + page.evaluate('(s)=>{window.app=h.loadView(s,lib)}', (BASE / 'view/netpreference/advanced.js').read_text()) + page.evaluate('async()=>document.querySelector("#root").append(await app.render())') + # Unicode escapes keep scripts portable on minimal host encodings. + page.get_by_role('button', name='\u57df\u540d\u96c6 (0)', exact=True).click() + page.locator('[data-action="add-set"]').click() + page.get_by_label('\u57df\u540d\u96c6\u540d\u79f0').fill('AI\u670d\u52a1') + page.get_by_label('\u57df\u540d\u5217\u8868').fill('openai.com\nanthropic.com\nhttps://claude.ai/new') + page.screenshot(path=str(OUT / 'domain-sets.png'), full_page=True) + page.get_by_role('button', name='\u6a21\u5f0f\u96c6 (0)', exact=True).click() + page.locator('[data-action="add-profile"]').click() + page.get_by_label('\u6a21\u5f0f\u96c6\u540d\u79f0').fill('\u65e5\u5e38\u6a21\u5f0f') + profile = page.locator('[data-profile]') + profile.locator('[data-action="add-rule"]').click() + set_id = page.evaluate('app.model.sets[0].id') + profile.locator('.np-rule').nth(0).get_by_label('\u8f93\u5165\u57df\u540d\u6216\u9009\u62e9\u57df\u540d\u96c6').select_option(set_id) + profile.locator('[data-action="add-rule"]').click() + r = profile.locator('.np-rule').nth(1) + r.get_by_label('\u76f4\u63a5\u57df\u540d').fill('youtube.com') + r.get_by_label('\u504f\u597d\u6a21\u5f0f').select_option('ipv4') + profile.locator('[data-action="add-rule"]').click() + r = profile.locator('.np-rule').nth(2) + r.get_by_label('\u76f4\u63a5\u57df\u540d').fill('games.test') + r.get_by_label('\u504f\u597d\u6a21\u5f0f').select_option('custom') + r.get_by_label('A', exact=True).fill('0') + r.get_by_label('B', exact=True).fill('150') + r.get_by_label('\u4f18\u5148\u534f\u8bae\u65cf').select_option('ipv6') + profile.locator('[data-action="add-rule"]').click() + r = profile.locator('.np-rule').nth(3) + r.get_by_label('\u76f4\u63a5\u57df\u540d').fill('example.com') + r.get_by_label('\u504f\u597d\u6a21\u5f0f').select_option('dual') + page.evaluate('async()=>{h.calls.length=0;await app.handleSaveApply()}') + assert page.evaluate('h.notices.filter(x=>x[0]==="error").length') == 0 + assert page.evaluate('h.calls.map(c=>c[1])') == ['save', 'check_config', 'save', 'save', 'commit', 'apply'] + assert page.evaluate('app.model.profiles[0].rows.length') == 4 + assert page.evaluate('app.model.profiles[0].rows[2].wait_ms') == '0' + assert page.evaluate('app.model.sets[0].original') == ['*.openai.com', '*.anthropic.com', '*.claude.ai'] + text = page.locator('body').inner_text() + for internal in ('DomainSet ID', 'stable ID', 'Policy', 'Profile', set_id): + assert internal not in text, internal + page.screenshot(path=str(OUT / 'mode-sets-desktop.png'), full_page=True) + page.set_viewport_size({'width': 390, 'height': 844}) + assert page.evaluate('document.documentElement.scrollWidth <= innerWidth+1'), 'mobile horizontal overflow' + page.screenshot(path=str(OUT / 'mode-sets-mobile.png'), full_page=True) + # Invalid custom timings are rejected before uci save/commit/apply. + r = profile.locator('.np-rule').nth(2) + r.get_by_label('A', exact=True).fill('750') + r.get_by_label('B', exact=True).fill('500') + page.evaluate('async()=>{h.calls.length=0;await app.handleSaveApply()}') + assert page.evaluate('h.calls.map(c=>c[1])') == ['save', 'check_config'] + page.evaluate('async()=>await app.handleReset()') + assert page.evaluate('app.model.profiles[0].rows[2].wait_ms') == '0' + # When run after the kernel lab, render its actual CLI/RPC output without + # replacing any numeric values. This closes the nft -> runtime -> RPC -> + # browser chain; locally this block is explicitly skipped if no kernel lab. + traffic_file = ROOT / 'dist/kernel-traffic.json' + kernel_rendered = traffic_file.exists() + if kernel_rendered: + snapshot = json.loads(traffic_file.read_text()) + assert snapshot['enabled'] and snapshot['totals_available'] + row = next(r for r in snapshot['rows'] if r['host']['mac'] == '02:00:00:00:00:01') + for family in ('ipv4', 'ipv6'): + assert row[family + '_rate']['valid'] + assert row[family + '_rate']['upload_Bps'] > 0 + assert row[family + '_rate']['download_Bps'] > 0 + page.set_viewport_size({'width': 1280, 'height': 900}) + page.evaluate('(t)=>{h.responses.traffic=t;}', snapshot) + page.evaluate('(s)=>{window.overview=h.loadView(s,lib);overview.statusBox=E("div");overview.trafficBox=E("div");document.querySelector("#root").replaceChildren(overview.statusBox,overview.trafficBox);}', + (BASE / 'view/netpreference/overview.js').read_text()) + page.evaluate('async()=>await overview.refresh()') + cells = page.locator('table tr').nth(1).locator('td') + assert cells.count() == 6 + for index in (1, 2, 3, 4): + text = cells.nth(index).inner_text() + assert '0 B/s' not in text and '\u7b49\u5f85' not in text and '\u2014' not in text, text + assert cells.nth(5).inner_text() == f"{100 * row['ipv6_ratio']:.1f}%" + page.screenshot(path=str(OUT / 'kernel-traffic-browser.png'), full_page=True) + assert not errors, errors + (OUT / 'result.json').write_text(json.dumps({'result': 'pass', 'browser': browser.version, + 'scope': 'real custom DOM + backend parser, LuCI hosting API fixture', + 'kernel_rpc_rendered': kernel_rendered, + 'checks': ['domain sets', 'four modes', 'no manual IDs', 'zero A/B', 'save/apply ordering', + 'backend rejection', 'reset', 'desktop/mobile overflow']}, indent=2)) + browser.close() +print('PASS: Chromium domain-set and four-row mode-set interactions, backend validation, save/reset and mobile layout.') diff --git a/tests/luci_contract.js b/tests/luci_contract.js index c82f95f..5bf7cd7 100644 --- a/tests/luci_contract.js +++ b/tests/luci_contract.js @@ -1,63 +1,92 @@ 'use strict'; -// Exercise the actual LuCI module with small API doubles, not a visual browser. -const assert = require('assert'); -const fs = require('fs'); -const path = require('path'); -const calls = []; -function E(tag, attrs, children) { - const node = { tag, attrs: attrs || {}, children: children || [], appendChild(child) { - if (!Array.isArray(this.children)) this.children = [this.children]; this.children.push(child); - }}; - return node; +const assert=require('assert'),fs=require('fs'),path=require('path'),cp=require('child_process'); +const {create}=require('./luci_harness'); +const ROOT=path.join(__dirname,'..'), BASE=path.join(ROOT,'files/www/luci-static/resources'); +function E(tag,attrs,children){return {tag,attrs:attrs||{},children:children||[],appendChild(c){if(!Array.isArray(this.children))this.children=[this.children];this.children.push(c);}};} +function validate(text){ + const res=cp.spawnSync(path.join(ROOT,'dist/netpreference'),['rpc','call','check_config'],{input:JSON.stringify({config:text}),encoding:'utf8'}); + if(res.error)throw res.error; + return JSON.parse(res.stdout); } -const responses = { - status: { version: '0.1.0', active: true, selected_devices: 1, queries: 4 }, - devices: { devices: [{mac:'02:00:00:00:00:01',name:'laptop',ipv4:['192.0.2.2'],ipv6:['fd42::2']}] }, - traffic: { enabled: true, totals_available: true, rows: [{host:{mac:'02:00:00:00:00:01',name:'laptop',ipv4:[],ipv6:[]}, - totals:{ipv4:{upload_bytes:100,download_bytes:200},ipv6:{upload_bytes:300,download_bytes:400}}, - ipv4_rate:{valid:true,upload_Bps:50,download_Bps:70},ipv6_rate:{valid:false},ipv6_ratio:0.7}] }, - apply: {ok:true}, restore: {ok:true}, commit:0 -}; -const rpc = { declare(spec) { return async (...args) => { calls.push([spec.object,spec.method,...args]); return responses[spec.method]; }; } }; -const values = {}; -class Option { - constructor(name) { this.name=name; this.choices=[]; } - value(...args){this.choices.push(args);} - depends(){} - getUIElement(sid){return {setValue:v=>{values[`${sid}/${this.name}`]=v;}};} -} -class Section { - constructor(map){this.map=map;} - option(_type,name){const o=new Option(name);this.map.options.push(o);return o;} -} -class FormMap { - constructor(){this.options=[];} - section(){return new Section(this);} - lookupOption(name){return this.options.filter(o=>o.name===name);} - async render(){return E('form');} - async save(){calls.push(['form','save']);} -} -const form={Map:FormMap,NamedSection:Section,GridSection:Section,Value:Option,Flag:Option,DynamicList:Option,ListValue:Option}; -const uci={async load(){return {};},unload(){},get(){return undefined;},sections(_p,_s,cb){cb({mac:'02:00:00:00:00:01',name:'laptop'});}}; -const notices=[]; -const ui={createHandlerFn(self,fn){return fn.bind(self);},addNotification(_a,msg,type){if(type==='error')throw new Error(JSON.stringify(msg));notices.push([type,msg]);}}; -const poll={add(fn){this.fn=fn;}}; -const dom={content(node,children){node.children=children;}}; -const source=fs.readFileSync(path.join(__dirname,'../files/www/luci-static/resources/view/netpreference/overview.js'),'utf8'); -const moduleView=new Function('view','form','rpc','uci','ui','poll','dom','E','_',source)({extend:x=>x},form,rpc,uci,ui,poll,dom,E,x=>x); +const h=create(E,validate),lib=h.module(fs.readFileSync(path.join(BASE,'netpreference/library.js'),'utf8')); +function view(name){return h.loadView(fs.readFileSync(path.join(BASE,'view/netpreference',name+'.js'),'utf8'),lib);} +function methods(){return h.calls.map(c=>c[1]);} (async()=>{ - const data=await moduleView.load();await moduleView.render(data);await moduleView.refresh(); - assert(JSON.stringify(moduleView.trafficBox).includes('70.0%')); - const preset=moduleView.map.lookupOption('_preset')[0];preset.onchange(null,'device1','strong'); - assert.equal(values['device1/wait_ms'],'250');assert.equal(values['device1/delay_ms'],'150'); - calls.length=0;await moduleView.handleSaveApply(); - assert.deepEqual(calls.slice(0,3),[['form','save'],['uci','commit','netpreference'],['netpreference','apply']]); - assert(!calls.some(x=>x[0]==='uci'&&x[1]==='apply'),'must not commit unrelated pending UCI packages'); - assert(notices.some(n=>n[0]==='info'&&JSON.stringify(n[1]).includes('NetPreference 配置已保存并应用'))); - assert.equal(moduleView.handleSave,null); - const actions=moduleView.map.lookupOption('action')[0].choices.map(v=>v[0]); - assert(actions.includes('rewrite')&&actions.includes('nxdomain')&&actions.includes('ipv4_only')); - responses.traffic={enabled:false};await moduleView.refresh(); - assert(JSON.stringify(moduleView.trafficBox).includes('NetPreference')&&JSON.stringify(moduleView.trafficBox).includes('不会采样或累计流量')); - console.log('PASS: LuCI render/status/traffic/preset and own-package-only Save & Apply contract (API doubles, not browser validation).'); + const basic=view('overview');await basic.render(await basic.load());await basic.refresh(); + assert(JSON.stringify(basic.trafficBox).includes('70.0%')); + assert(!basic.map.sections.some(s=>s.sectiontype==='rule')); + assert.deepEqual(h.option(basic,'device','profile').choices.find(c=>c[0]==='work'),['work','Work']); + assert(h.option(basic,'device','mode').choices.some(c=>c[0]==='block')); + assert(h.option(basic,'device','prefer').retain); + h.option(basic,'device','_preset').onchange(null,'pc','strong'); + assert.equal(h.values['pc/wait_ms'],'250');assert.equal(h.values['pc/delay_ms'],'150'); + h.calls.length=0;await basic.handleSaveApply(); + assert.deepEqual(methods().slice(0,5),['save','check_config','save','commit','apply']); + const status=JSON.stringify(basic.statusBox); + h.responses.traffic=new Error('counter RPC unavailable');await basic.refresh(); + assert.equal(JSON.stringify(basic.statusBox),status,'traffic RPC must not falsify DNS service status'); + assert(JSON.stringify(basic.trafficBox).includes('counter RPC unavailable')); + h.responses.traffic={enabled:true,state:'unavailable',totals_available:false,error:'missing counters',rows:[]};await basic.refresh(); + assert(JSON.stringify(basic.trafficBox).includes('missing counters')); + h.responses.traffic={enabled:false};await basic.refresh(); + assert(JSON.stringify(basic.trafficBox).includes('NetPreference')); + + const advanced=view('advanced');await advanced.load();await advanced.render(); + assert.deepEqual(advanced.map.sections.map(s=>s.sectiontype),['rule'],'only optional DNS actions use a backend grid'); + assert(!JSON.stringify(advanced.editor).includes('stable ID')); + const actions=h.option(advanced,'rule','action').choices.map(v=>v[0]); + for(const action of ['rewrite','nxdomain','nodata','refused','sinkhole','forward','ipv4_only','ipv6_only'])assert(actions.includes(action)); + for(const k of ['ipv4','ipv6','upstream'])assert(h.option(advanced,'rule',k).retain); + let model=advanced.model; + const originalRule=JSON.stringify(h.sections.block); + // Round-trip old r1 records without silently broadening exact patterns. + h.calls.length=0;await advanced.handleSave(); + assert.deepEqual(methods(),['save','check_config','save','save','commit']); + assert.deepEqual(h.sections.media.domain,['*.media.test','exact.test']); + assert.equal(h.sections.work.description,'Retain this note'); + assert.equal(h.sections.bias.wait_ms,'0');assert.equal(h.sections.bias.probe,'0'); + assert.equal(JSON.stringify(h.sections.block),originalRule); + model=advanced.model; + const set=lib.newSet(h.uci,model);set.name='AI\u670d\u52a1';set.text=' OpenAI.com \nhttps://anthropic.com/docs\nclaude.ai\uff0copenai.com'; + const profile=lib.newProfile(h.uci,model);profile.name='\u65e5\u5e38\u6a21\u5f0f'; + let row=lib.newRow(h.uci,model,profile);row.kind='set';row.domain_set=set.id;row.mode='ipv6'; + row=lib.newRow(h.uci,model,profile);row.input='youtube.com';row.mode='ipv4';row.wait_ms='0';row.delay_ms='160'; + row=lib.newRow(h.uci,model,profile);row.input='games.test';row.mode='custom';row.prefer='ipv6';row.wait_ms='40';row.delay_ms='90';row.probe='0'; + row=lib.newRow(h.uci,model,profile);row.input='example.com';row.mode='dual'; + h.uci.set('netpreference','pc','profile',profile.id); + h.calls.length=0;await advanced.handleSaveApply(); + assert.deepEqual(methods(),['save','check_config','save','save','commit','apply']); + assert.deepEqual(h.sections[set.id].domain,['*.openai.com','*.anthropic.com','*.claude.ai']); + const config=lib.serialize(h.uci); + fs.mkdirSync(path.join(ROOT,'dist'),{recursive:true});fs.writeFileSync(path.join(ROOT,'dist/ux-generated.uci'),config); + assert(!config.includes("option 'wait_ms' ''"),'unset inheritance is not a literal empty option'); + assert.equal(h.sections.pc.mode,'ipv4','profile must not overwrite device global mode'); + assert.equal(h.sections.pc.wait_ms,'120'); + // Rename both libraries, change an existing direct selector to a set, then + // round-trip: no name is used as an identifier and no stale selector remains. + model=advanced.model;model.sets.find(s=>s.id===set.id).name='Renamed AI'; + let p=model.profiles.find(p=>p.id===profile.id);p.name='Renamed daily'; + p.rows[1].kind='set';p.rows[1].domain_set=set.id; + h.calls.length=0;await advanced.handleSave(); + assert(methods().includes('commit'));assert.equal(h.sections.pc.profile,profile.id); + assert.equal(h.sections[p.rows[1].id].domain,undefined); + assert.equal(h.sections[p.rows[1].id].domain_set,set.id); + // Backend, not JavaScript heuristics, is authoritative before persistence. + model=advanced.model;p=model.profiles.find(p=>p.id===profile.id); + p.rows[0].wait_ms='750';p.rows[0].delay_ms='500'; + h.calls.length=0;await advanced.handleSaveApply(); + assert(methods().includes('check_config'));assert(!methods().includes('commit'));assert(!methods().includes('apply'));assert(!methods().includes('save',1)); + p.rows[0].wait_ms='';p.rows[0].delay_ms=''; + const doomed=lib.newProfile(h.uci,model);doomed.name='Temporary';const invalid=lib.newRow(h.uci,model,doomed);invalid.input='a.test';invalid.wait_ms='9999'; + await advanced.handleSave(); + model.profiles=model.profiles.filter(p=>p!==doomed); + h.calls.length=0;await advanced.handleSave(); + assert(methods().includes('commit'),'removing a rejected new profile must remove its staged sections too'); + assert(!h.sections[doomed.id]);assert(!h.sections[invalid.id]); + // Referenced library deletion is blocked before any persistent write. + model=advanced.model;model.profiles=model.profiles.filter(p=>p.id!==profile.id); + h.calls.length=0;await advanced.handleSave();assert(!methods().includes('commit')); + assert.equal(JSON.stringify(h.sections.block),originalRule); + assert(!h.calls.some(x=>x[0]==='uci'&&x[1]==='apply')); + console.log('PASS: actual views + pure model + backend preflight; generated stable IDs, named sets, unnamed rules, inheritance, old actions, scoped persistence, full traffic UI contract. API doubles, not target-router acceptance.'); })().catch(e=>{console.error(e);process.exit(1);}); diff --git a/tests/luci_harness.js b/tests/luci_harness.js new file mode 100644 index 0000000..47d4e6b --- /dev/null +++ b/tests/luci_harness.js @@ -0,0 +1,77 @@ +'use strict'; +// Documented LuCI API doubles. Shared by Node contract tests and Chromium +// interaction tests. Not a substitute for the target router's LuCI acceptance. +(function(global){ + function create(E, validate){ + const calls=[], notices=[], values={}; + let sections={ + main:{'.name':'main','.type':'global',enabled:'1',monitor:'1',interface:['br-lan']}, + pc:{'.name':'pc','.type':'device',mac:'02:00:00:00:00:01',name:'Laptop',profile:'work',mode:'ipv4',wait_ms:'120',delay_ms:'80'}, + work:{'.name':'work','.type':'profile',name:'Work',description:'Retain this note'}, + media:{'.name':'media','.type':'domain_set',name:'Media',domain:['*.media.test','exact.test']}, + bias:{'.name':'bias','.type':'policy',profile:'work',domain_set:'media',mode:'ipv6',wait_ms:'0',delay_ms:'0',probe:'0'}, + block:{'.name':'block','.type':'rule',domain:'bad.test',device:'*',action:'nxdomain',custom_note:'retained'} + }; + let saved=JSON.parse(JSON.stringify(sections)); + const responses={ + status:{version:'0.2.0',active:true,desired:true,monitoring:true,selected_devices:1,queries:4}, + devices:{devices:[{mac:'02:00:00:00:00:01',name:'Laptop',ipv4:['192.0.2.2'],ipv6:['fd42::2']}]}, + traffic:{enabled:true,state:'ready',totals_available:true,rows:[{host:{mac:'02:00:00:00:00:01',name:'Laptop',ipv4:[],ipv6:[]},totals:{ipv4:{upload_bytes:100,download_bytes:200},ipv6:{upload_bytes:300,download_bytes:400}},ipv4_rate:{valid:true,upload_Bps:50,download_Bps:70},ipv6_rate:{valid:false},ipv6_ratio:0.7}]}, + apply:{ok:true},restore:{ok:true},validate:{valid:true},check_config:{ok:true,valid:true},commit:0 + }; + const rpc={declare(spec){return async(...args)=>{ + calls.push([spec.object,spec.method,...args]); + if(spec.method==='check_config'&&validate)return validate(args[0]); + if(responses[spec.method] instanceof Error)throw responses[spec.method]; + if(spec.method==='commit'&&responses.commit===0)saved=JSON.parse(JSON.stringify(sections)); + return responses[spec.method]; + };}}; + const uci={ + async load(){return {};},unload(){sections=JSON.parse(JSON.stringify(saved));}, + get(p,s,k){return k==null?sections[s]:(sections[s]||{})[k];}, + sections(p,type,cb){const rows=Object.values(sections).filter(s=>!type||s['.type']===type);if(cb)rows.forEach(cb);return rows;}, + add(p,type,name){if(!name)throw new Error('Library must create stable named sections');sections[name]={'.name':name,'.type':type};return name;}, + set(p,s,k,v){if(v==null||v==='')delete sections[s][k];else sections[s][k]=v;}, + remove(p,s){delete sections[s];}, + move(p,s,target,after){ + const row=sections[s];if(!row||target!=null&&!sections[target])return false; + const entries=Object.entries(sections).filter(function(e){return e[0]!==s;}); + let at=entries.length; + if(target!=null){at=entries.findIndex(function(e){return e[0]===target;});if(at<0)return false;if(after)at++;} + entries.splice(at,0,[s,row]);sections=Object.fromEntries(entries);return true; + }, + async save(){calls.push(['uci','save']);} + }; + class Option{ + constructor(section,name){this.section=section;this.map=section.map;this.name=name;this.option=name;this.choices=[];this.keylist=[];this.vallist=[];} + value(k,v){this.choices.push([k,v]);this.keylist.push(k);this.vallist.push(v||k);} + depends(){} load(sid){return uci.get('netpreference',sid,this.name);} + getUIElement(sid){return {setValue:v=>{values[`${sid}/${this.name}`]=v;}};} + } + class Section{ + constructor(map,type){this.map=map;this.sectiontype=type;this.options=[];} + option(Type,name){const o=new Type(this,name);this.options.push(o);this.map.options.push(o);return o;} + } + class FormMap{ + constructor(){this.options=[];this.sections=[];} + section(_Type,type){const s=new Section(this,type);this.sections.push(s);return s;} + lookupOption(name,sid){return this.options.filter(o=>o.name===name&&(!sections[sid]||o.section.sectiontype===sections[sid]['.type']));} + async render(){for(const o of this.options)for(const s of Object.values(sections).filter(s=>s['.type']===o.section.sectiontype))await o.load(s['.name']);return E('div',{'class':'test-luci-form'},'LuCI form API fixture');} + async save(cb){calls.push(['form','save']);if(cb)await cb();await uci.save();} + async reset(){return this.render();} + } + const form={Map:FormMap,NamedSection:Section,GridSection:Section,Value:Option,Flag:Option,DynamicList:Option,ListValue:Option}; + const ui={createHandlerFn(self,fn){return fn.bind(self);},addNotification(a,msg,type){notices.push([type,msg]);}}; + const poll={add(fn){this.fn=fn;}},dom={content(node,children){ + if(node.replaceChildren){node.replaceChildren();(Array.isArray(children)?children:[children]).forEach(c=>node.append(c));} + else node.children=children; + }}; + const h={calls,notices,values,responses,uci,form,ui,poll,dom,E,baseclass:{extend:x=>x},view:{extend:x=>x},get sections(){return sections;}}; + h.module=function(source){return new Function('baseclass',source)(h.baseclass);}; + h.loadView=function(source,library){return new Function('view','form','rpc','uci','ui','poll','dom','E','_','library',source)(h.view,form,rpc,uci,ui,poll,dom,E,x=>x,library);}; + h.option=function(v,type,name){return v.map.sections.find(s=>s.sectiontype===type).options.find(o=>o.name===name);}; + return h; + } + global.NPTest={create:create}; + if(typeof module!=='undefined')module.exports=global.NPTest; +})(typeof window!=='undefined'?window:globalThis); diff --git a/tests/luci_target_uci.js b/tests/luci_target_uci.js new file mode 100644 index 0000000..9c5b39d --- /dev/null +++ b/tests/luci_target_uci.js @@ -0,0 +1,61 @@ +'use strict'; +// Run against uci.js extracted from the exact official target rootfs. The ubus +// transport is a bounded in-memory fixture; persistence is also round-tripped +// through the target /sbin/uci and the installed SDK binary in a temp config dir. +const assert=require('assert'),fs=require('fs'),path=require('path'),cp=require('child_process'); +const root=path.resolve(process.argv[2]),project=path.resolve(__dirname,'..'); +const src=fs.readFileSync(path.join(root,'www/luci-static/resources/uci.js'),'utf8'); +let db={main:{'.type':'global','.name':'main','.index':0,enabled:'1',interface:['br-lan']}, + pc:{'.type':'device','.name':'pc','.index':1,enabled:'1',mac:'02:00:00:00:00:01',mode:'ipv4',wait_ms:'120',delay_ms:'80'}}; +const clone=x=>JSON.parse(JSON.stringify(x)); +const rpc={declare(spec){return async(...args)=>{ + const [config,sid,opts]=args;assert.equal(config,'netpreference'); + switch(spec.method){ + case 'get':return clone(db); + case 'add':{const [,type,name,values]=args;assert(name);assert(!db[name]);db[name]={'.type':type,'.name':name,'.index':Object.keys(db).length,...clone(values)};return name;} + case 'set':Object.assign(db[sid],clone(opts));return 0; + case 'delete':if(!opts)delete db[sid];else opts.forEach(k=>delete db[sid][k]);return 0; + case 'order':args[1].forEach((id,i)=>db[id]['.index']=i);return 0; + default:throw new Error('unexpected target UCI method '+spec.method); + } +};}}; +const baseclass={extend:x=>x}; +const document={dispatchEvent(){}},CustomEvent=function(type){this.type=type;}; +// Used by older supported LuCI implementations, not by generated stable IDs. +if(!String.prototype.format)String.prototype.format=function(...args){let i=0;return this.replace(/%06x|%s|%d/g,m=>m==='%06x'?Math.floor(args[i++]).toString(16).padStart(6,'0'):String(args[i++]));}; +const L={bind:(fn,self,...args)=>fn.bind(self,...args),toArray:x=>Array.isArray(x)?x:[x]}; +const uci=new Function('baseclass','rpc','document','CustomEvent','L',src)(baseclass,rpc,document,CustomEvent,L);uci.__init__(); +const lib=new Function('baseclass',fs.readFileSync(path.join(project,'files/www/luci-static/resources/netpreference/library.js'),'utf8'))(baseclass); +(async()=>{ + await uci.load('netpreference'); + let m=lib.load(uci),s=lib.newSet(uci,m);s.name='AI services';s.text='openai.com\nclaude.ai'; + let p=lib.newProfile(uci,m);p.name='Daily'; + let r=lib.newRow(uci,m,p);r.input='youtube.com';r.mode='ipv4';r.wait_ms='0';r.delay_ms='0';r.probe='0'; + const id=r.id; + let other=lib.newRow(uci,m,p);other.kind='set';other.domain_set=s.id; + lib.stage(uci,m);uci.set('netpreference','pc','profile',p.id); + let pre=lib.serialize(uci);assert(pre.includes('*.youtube.com')); + await uci.save();lib.order(uci,m);await uci.save(); + assert(db[s.id]&&db[p.id]&&db[id],'named references changed on save'); + assert.equal(db[id].wait_ms,'0');assert.equal(db[id].probe,'0'); + // Old domain deletion must disappear from both preflight text and native UCI. + m=lib.load(uci);p=m.profiles[0];s=m.sets[0];p.rows[0].kind='set';p.rows[0].domain_set=s.id; + p.rows.reverse();lib.stage(uci,m);pre=lib.serialize(uci); + assert(!pre.includes('youtube.com'),'deleted selector leaked into validation'); + await uci.save();lib.order(uci,m);await uci.save();assert.equal(db[id].domain,undefined);assert.equal(db[id].domain_set,s.id); + let rows=uci.sections('netpreference','policy');assert.equal(rows[0]['.name'],other.id); + // Remove one rule and rename the set without renaming its stable reference. + m=lib.load(uci);m.profiles[0].rows.pop();m.sets[0].name='Renamed';lib.stage(uci,m);await uci.save();lib.order(uci,m);await uci.save(); + assert(!db[id]);assert.equal(db[other.id].domain_set,s.id); + const text=lib.serialize(uci); + fs.mkdirSync(path.join(root,'tmp/np-ui-config'),{recursive:true}); + cp.execFileSync('chroot',[root,'/sbin/uci','-c','/tmp/np-ui-config','import','netpreference'],{input:text}); + cp.execFileSync('chroot',[root,'/sbin/uci','-c','/tmp/np-ui-config','commit','netpreference']); + const exported=cp.execFileSync('chroot',[root,'/sbin/uci','-c','/tmp/np-ui-config','export','netpreference'],{encoding:'utf8'}); + const validation=JSON.parse(cp.execFileSync('chroot',[root,'/usr/sbin/netpreference','rpc','call','check_config'],{input:JSON.stringify({config:exported}),encoding:'utf8'})); + assert(validation.valid);assert(exported.includes("'*.openai.com'")); + fs.mkdirSync(path.join(project,'dist-sdk/target-luci'),{recursive:true}); + fs.writeFileSync(path.join(project,'dist-sdk/target-luci/uci.js'),src); + fs.writeFileSync(path.join(project,'dist-sdk/target-luci/roundtrip.uci'),exported); + console.log('PASS: official target uci.js create/rename/selector-delete/reorder/remove/save, native target uci import/export and installed SDK parser. Ubus transport fixture, no live router web session.'); +})().catch(err=>{console.error(err);process.exit(1);}); diff --git a/tests/netns.py b/tests/netns.py index f459c16..6a99872 100644 --- a/tests/netns.py +++ b/tests/netns.py @@ -73,11 +73,35 @@ def main(): config device 'selected' option enabled '1' option name 'selected' + option profile 'work' option mac '02:00:00:00:00:01' option mode 'ipv6' option wait_ms '120' option delay_ms '100' option probe '1' +config profile 'work' + option name 'Work' +config profile 'travel' + option name 'Travel' +config domain_set 'v4_domains' + option name 'V4 domains' + list domain '*.v4.test' +config policy 'v4_override' + option profile 'work' + option domain_set 'v4_domains' + option mode 'ipv4' + option wait_ms '90' + option delay_ms '180' +config policy 'short_override' + option profile 'work' + option domain 'fast.test' + option mode 'ipv6' + option wait_ms '90' + option delay_ms '45' +config policy 'travel_dual' + option profile 'travel' + option domain '*' + option mode 'dual' config rule 'static' option device '*' option domain 'rewrite.test' @@ -139,7 +163,7 @@ def expect(n,host,typ,domain,address=None,rcode=0,proto='udp',port=0): } """ ns(router,'nft','-f','-',input=sentinel);before=ns(router,'nft','-j','list','table','inet','fw4') - start(router,sys.executable,FIXTURE,'serve');start(wan,sys.executable,FIXTURE,'echo') + dns_fixture=start(router,sys.executable,FIXTURE,'serve');start(wan,sys.executable,FIXTURE,'echo');start(router,sys.executable,FIXTURE,'echo') daemon=start(router,BINARY,'serve');guard=start(router,BINARY,'guard') wait_for(lambda:ctl('status')) expect(first,'192.0.2.1',1,'rewrite.test','198.51.100.7') @@ -194,6 +218,29 @@ def ll_discovered(): expect(first,'192.0.2.1',1,'x.blocked.test',rcode=3) expect(second,'192.0.2.1',1,'x.blocked.test','198.51.100.7') r=expect(first,'192.0.2.1',1,'preference.test','198.51.100.7');assert r['elapsed']>=0.07,r + # Domain sets and domain-specific A/B apply on both DNS transports and IP families. + for host in ('192.0.2.1','fd42:1::1'): + for proto in ('udp','tcp'): + r=expect(first,host,28,'deep.v4.test','2001:db8::7',proto=proto) + assert 0.15 <= r['elapsed'] < 1.5,r + r=expect(first,host,1,'fast.test','198.51.100.7',proto=proto) + assert 0.03 <= r['elapsed'] < 1.5,r + # Reject bad references without losing the active policy or touching shared NAT66. + p=base/'config';saved=p.read_text() + p.write_text(saved.replace("option profile 'work'","option profile 'missing'",1)) + failed=subprocess.run(['ip','netns','exec',router,str(BINARY),'reload'],env=env,text=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) + assert failed.returncode != 0,failed.stdout + rejected=json.loads(failed.stdout);assert not rejected.get('ok',True),rejected + assert ctl('status')['active'] + r=expect(first,'192.0.2.1',28,'deep.v4.test','2001:db8::7');assert r['elapsed']>=0.15,r + p.write_text(saved.replace("option profile 'work'","option profile 'travel'",1)) + assert ctl('reload')['ok'] + delays=ctl('status')['delayed'] + expect(first,'192.0.2.1',28,'deep.v4.test','2001:db8::7') + assert ctl('status')['delayed']==delays,'old profile remained after switch' + expect(first,'192.0.2.1',1,'x.blocked.test',rcode=3) + p.write_text(saved);assert ctl('reload')['ok'] + assert ns(router,'nft','-j','list','table','inet','fw4')==before expect(first,'192.0.2.1',1,'fallback.test','198.51.100.7') expect(first,'192.0.2.1',1,'rewrite.test','203.0.113.77',port=42053) # A successful restore also cleans the already cached UDP DNAT tuple. @@ -208,17 +255,80 @@ def ll_discovered(): counters={r['counter']['name']:r['counter']['bytes'] for r in table['nftables'] if 'counter' in r} for family in (4,6): for direction in ('up','down'):assert counters[f'm020000000001_{family}_{direction}']>0,counters - wait_for(lambda:ctl('traffic').get('totals_available')) + def observed(): + snapshot=json.loads(ns(router,BINARY,'rpc','call','traffic',input='{}',env=env)) + row=next((r for r in snapshot.get('rows',[]) if r['host']['mac']=='02:00:00:00:00:01'),None) + if row and all(row[f'ipv{f}_rate']['valid'] and row[f'ipv{f}_rate']['upload_Bps']>0 and row[f'ipv{f}_rate']['download_Bps']>0 and + row['totals'][f'ipv{f}']['upload_bytes']>=20000 and row['totals'][f'ipv{f}']['download_bytes']>=20000 for f in (4,6)): + return snapshot + snapshot=wait_for(observed,15) + rpc=snapshot + print('TRAFFIC_FULL_CHAIN',json.dumps(rpc,sort_keys=True),flush=True) + (ROOT/'dist/kernel-traffic.json').write_text(json.dumps(rpc,indent=2)) + def rowof(snap):return next(r for r in snap['rows'] if r['host']['mac']=='02:00:00:00:00:01') + def counts(): + data=json.loads(ns(router,'nft','-j','list','table','inet','netpreference')) + return {r['counter']['name']:r['counter']['bytes'] for r in data['nftables'] if 'counter' in r} + def nondecreasing(old,new): + for family in ('ipv4','ipv6'): + for direction in ('upload_bytes','download_bytes'):assert new['totals'][family][direction]>=old['totals'][family][direction],(old,new) + assert 0=value,(name,value,after_counts) + nondecreasing(before_row,rowof(ctl('traffic'))) + p.write_text(active_config);assert ctl('reload')['ok'] + # Traffic terminating in a local proxy takes INPUT/OUTPUT, not FORWARD. + # No HomeProxy binary is installed in this lab: exercise its packet path. + before_counts=counts() + ns(first,sys.executable,FIXTURE,'traffic','192.0.2.1');ns(first,sys.executable,FIXTURE,'traffic','fd42:1::1') + after_counts=counts() + for family in (4,6): + for direction in ('up','down'): + name=f'm020000000001_{family}_{direction}' + assert after_counts[name]-before_counts[name]>=20000,(name,before_counts,after_counts) + # New inventory membership really rebuilds the table; keep past totals + # while explicitly invalidating the rate generation. + before_row=rowof(ctl('traffic')) + p.write_text(active_config+"\nconfig device 'spare'\n option enabled '0'\n option mac '02:00:00:00:00:03'\n") + assert ctl('reload')['ok'];nondecreasing(before_row,rowof(ctl('traffic'))) + p.write_text(active_config);assert ctl('reload')['ok'] + # Original DNS chain outage pauses DNS interception, not read-only + # traffic observation. Echo traffic must continue accumulating. + dns_fixture.terminate();dns_fixture.wait(timeout=5) + wait_for(lambda:not ctl('status')['active'],15) + before_row=rowof(ctl('traffic')) + ns(first,sys.executable,FIXTURE,'traffic','192.0.2.1');ns(first,sys.executable,FIXTURE,'traffic','fd42:1::1') + wait_for(lambda:all(rowof(ctl('traffic'))['totals'][f'ipv{f}']['download_bytes']>before_row['totals'][f'ipv{f}']['download_bytes'] for f in (4,6)),15) + dns_fixture=start(router,sys.executable,FIXTURE,'serve') + wait_for(lambda:ctl('status')['active'],15) + print('PASS: nft -> sampler -> runtime -> CLI/RPC four-direction rates/totals/ratio; profile reload, host churn, local-proxy path and DNS fail-open sampling',flush=True) assert ns(router,'nft','-j','list','table','inet','fw4')==before # SIGKILL cannot run defer/stop handlers: separate watchdog must recover. expect(first,'192.0.2.1',1,'rewrite.test','203.0.113.77',port=42054) + def stale_dns_mapping(): + return ns(router,'conntrack','-L','-f','ipv4','-p','udp', + '-s','192.0.2.2','--sport','42054','--dport','53', + '--reply-src','192.0.2.1','--reply-port-src','1053').strip() + assert stale_dns_mapping(),'the SIGKILL fixture must have a cached DNAT tuple' + killed_at=time.monotonic() daemon.kill();daemon.wait(timeout=5) - def removed():return 'netpreference' not in ns(router,'nft','list','tables') - wait_for(removed,15) + # Removing the nft table and clearing old conntrack are separate kernel + # operations. Observe both, with the original deadline, before making + # one strict DNS query on the SAME old port. Never retry that query to + # hide a failure, and never treat table removal alone as completion. + def recovered(): + if 'netpreference' in ns(router,'nft','list','tables'):return False + return not stale_dns_mapping() + wait_for(recovered,15) + print('RECOVERY nft and cached DNAT cleared in',time.monotonic()-killed_at,'seconds',flush=True) expect(first,'192.0.2.1',1,'rewrite.test','198.51.100.7',port=42054) expect(first,'fd42:1::1',28,'rewrite.test','2001:db8::7') assert ns(router,'nft','-j','list','table','inet','fw4')==before - print('PASS: real IPv4/IPv6 UDP/TCP per-device redirect, timing, rules, custom fallback, own-table restore, identical-tuple conntrack recovery, SIGKILL watchdog, forwarded counters and NAT66 preservation.',flush=True) + print('PASS: real IPv4/IPv6 UDP/TCP per-device redirect, domain profiles/A-B/switch/invalid-reference rollback, timing, rules, custom fallback, own-table restore, identical-tuple conntrack recovery, SIGKILL watchdog, forwarded counters and NAT66 preservation.',flush=True) print('LIMIT: UCI/nlbw are fixtures; host kernel is not the target ImmortalWrt kernel; LuCI/procd target acceptance is separate.',flush=True) finally: for proc in reversed(processes): diff --git a/tests/rootfs_install.sh b/tests/rootfs_install.sh index 6904325..3cebdcc 100755 --- a/tests/rootfs_install.sh +++ b/tests/rootfs_install.sh @@ -16,7 +16,13 @@ mkdir root tar -xzf "$IMAGE" -C root mkdir -p root/tmp root/dev root/var/lock [ -e root/dev/null ] || mknod root/dev/null c 1 3 -PACKAGE=$(find "$ROOT/dist" -maxdepth 1 -name '*.ipk' -print -quit) +VERSION=$(sed -n 's/^PKG_VERSION:=//p' "$ROOT/openwrt/luci-app-netpreference/Makefile") +REV=$(sed -n 's/^PKG_RELEASE:=//p' "$ROOT/openwrt/luci-app-netpreference/Makefile") +PACKAGE=${NETPREFERENCE_IPK:-"$ROOT/dist/luci-app-netpreference_${VERSION}-r${REV}_x86_64.ipk"} +LEGACY=${NETPREFERENCE_LEGACY_IPK:-"$ROOT/dist-legacy/luci-app-netpreference_0.1.0-r6_x86_64.ipk"} +test -s "$PACKAGE" +test -s "$LEGACY" +cp "$LEGACY" root/tmp/legacy.ipk cp "$PACKAGE" root/tmp/netpreference.ipk # The minimal target rootfs omits a few runtime tools that are present on the # real target router. opkg filters a local package candidate before force-depends @@ -38,12 +44,28 @@ EOF fi done chroot root /bin/opkg print-architecture +# New installation is idle and removable. IPKG_INSTROOT=/ chroot root /bin/opkg install /tmp/netpreference.ipk chroot root /usr/sbin/netpreference version IPKG_INSTROOT=/ chroot root /bin/opkg status luci-app-netpreference grep -q "option enabled '0'" root/etc/config/netpreference test -x root/usr/libexec/rpcd/netpreference test -s root/usr/share/rpcd/acl.d/luci-app-netpreference.json +node "$ROOT/tests/luci_target_uci.js" "$WORK/root" IPKG_INSTROOT=/ chroot root /bin/opkg remove luci-app-netpreference test ! -e root/usr/sbin/netpreference -printf '%s\n' 'PASS: ImmortalWrt 24.10.4 rootfs opkg install/version/remove. Offline scripts skipped by design; no target-kernel or LuCI browser claim.' +# Install the true r6 binary, persist a real legacy config, then perform an ordinary upgrade. +IPKG_INSTROOT=/ chroot root /bin/opkg install /tmp/legacy.ipk +test "$(chroot root /usr/sbin/netpreference version)" = 0.1.0 +cp "$ROOT/tests/fixtures/legacy-r6.uci" root/etc/config/netpreference +before=$(sha256sum root/etc/config/netpreference | cut -d ' ' -f 1) +IPKG_INSTROOT=/ chroot root /bin/opkg install /tmp/netpreference.ipk +test "$(chroot root /usr/sbin/netpreference version)" = "$VERSION" +test "$(sha256sum root/etc/config/netpreference | cut -d ' ' -f 1)" = "$before" +IPKG_INSTROOT=/ chroot root /bin/opkg status luci-app-netpreference | grep -F "Version: ${VERSION}-r${REV}" +test -s root/www/luci-static/resources/view/netpreference/advanced.js +IPKG_INSTROOT=/ chroot root /bin/opkg remove luci-app-netpreference +test ! -e root/usr/sbin/netpreference +# opkg must retain the user-modified conffile rather than erase it on remove. +test "$(sha256sum root/etc/config/netpreference | cut -d ' ' -f 1)" = "$before" +printf '%s\n' 'PASS: ImmortalWrt 24.10.4 opkg new install, remove, actual r6 -> current upgrade, byte-identical legacy config, and modified-conffile retention. Offline package hooks skipped; runtime lifecycle is exercised in the isolated kernel lab.' diff --git a/tests/test_package.py b/tests/test_package.py index 2376f7a..0257b65 100755 --- a/tests/test_package.py +++ b/tests/test_package.py @@ -28,7 +28,7 @@ def unpack(data): class PackageTests(unittest.TestCase): @classmethod def setUpClass(cls): - cls.path=next((ROOT/'dist').glob('*.ipk')) + cls.path=ROOT/'dist'/f'luci-app-netpreference_{builder.VERSION}_x86_64.ipk' cls.outer=unpack(cls.path.read_bytes()) cls.control=unpack(cls.outer['control.tar.gz'][0]) cls.files=unpack(cls.outer['data.tar.gz'][0]) @@ -54,7 +54,7 @@ def test_static_binary_and_permissions(self): self.assertEqual(mode,0o755) for name in ['etc/init.d/netpreference','usr/libexec/rpcd/netpreference']: self.assertEqual(self.files[name][1],0o755) - self.assertEqual(subprocess.check_output([ROOT/'dist/netpreference','version'],text=True).strip(),'0.1.0') + self.assertEqual(subprocess.check_output([ROOT/'dist/netpreference','version'],text=True).strip(),builder.VERSION.split('-r')[0]) def test_no_shared_config_files(self): configs=[p for p in self.files if p.startswith('etc/config/')] self.assertEqual(configs,['etc/config/netpreference']) @@ -68,11 +68,22 @@ def test_luci_acl_and_syntax(self): acl=json.loads(self.files['usr/share/rpcd/acl.d/luci-app-netpreference.json'][0]) text=json.dumps(acl);self.assertNotIn('file',text);self.assertNotIn('"*"',text) self.assertIn('netpreference',text) - subprocess.run(['node','--check',ROOT/'files/www/luci-static/resources/view/netpreference/overview.js'],check=True) + for view in ('overview', 'advanced'): + subprocess.run(['node','--check',ROOT/f'files/www/luci-static/resources/view/netpreference/{view}.js'],check=True) + menu=json.loads(self.files['usr/share/luci/menu.d/luci-app-netpreference.json'][0]) + self.assertEqual(menu['admin/services/netpreference']['action']['type'],'firstchild') + self.assertIn('admin/services/netpreference/advanced',menu) + self.assertIn('www/luci-static/resources/netpreference/library.js',self.files) methods=json.loads(subprocess.check_output([ROOT/'dist/netpreference','rpc','list'])) - self.assertEqual(set(methods),{'apply','restore','validate','status','devices','traffic'}) + self.assertEqual(set(methods),{'apply','restore','validate','status','devices','traffic','check_config'}) bad=subprocess.run([ROOT/'dist/netpreference','rpc','call','apply'],input=b'{"command":"rm"}',stdout=subprocess.PIPE) self.assertNotEqual(bad.returncode,0) + for fixture in ('legacy-r6.uci', 'profiles.uci'): + payload=json.dumps({'config':(ROOT/'tests/fixtures'/fixture).read_text()}).encode() + result=json.loads(subprocess.check_output([ROOT/'dist/netpreference','rpc','call','check_config'],input=payload)) + self.assertTrue(result['valid']) + invalid=subprocess.run([ROOT/'dist/netpreference','rpc','call','check_config'],input=b'{"config":"config profile bad"}',stdout=subprocess.PIPE) + self.assertNotEqual(invalid.returncode,0) def test_openwrt_prerm_does_not_preempt_default_service_stop(self): mk=(ROOT/'openwrt/luci-app-netpreference/Makefile').read_text() start=mk.index('define Package/luci-app-netpreference/prerm') diff --git a/tests/test_workflows.py b/tests/test_workflows.py new file mode 100644 index 0000000..3deca38 --- /dev/null +++ b/tests/test_workflows.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python3 +"""Static regression guards for CI routing/security, complemented by actual Actions runs.""" +from pathlib import Path +import re +import unittest +ROOT=Path(__file__).resolve().parents[1] + +class WorkflowTests(unittest.TestCase): + def test_feature_pr_main_and_manual_verification(self): + text=(ROOT/'.github/workflows/ci.yml').read_text() + self.assertIn("branches: ['**']",text) + self.assertIn(' pull_request:',text) + self.assertIn(' workflow_dispatch:',text) + self.assertNotIn('feat/mvp',text) + self.assertNotIn('continue-on-error',text) + self.assertNotIn('.bootstrap',text) + self.assertIn('bash scripts/check.sh',text) + self.assertIn('sudo python3 tests/netns.py',text) + def test_release_requires_successful_main_push_and_both_jobs(self): + text=(ROOT/'.github/workflows/ci.yml').read_text() + release=text.split('\n release:\n',1)[1] + self.assertIn('needs: [verify, sdk]',release) + self.assertIn("if: github.event_name == 'push' && github.ref == 'refs/heads/main'",release) + self.assertNotIn('if: always()',release) + self.assertEqual(text.count('gh release create'),1) + self.assertIn('sha256sum -c SHA256SUMS',release) + def test_reusable_sdk_cannot_publish(self): + text=(ROOT/'.github/workflows/sdk-build.yml').read_text() + self.assertIn(' workflow_call:',text) + self.assertIn('contents: read',text) + self.assertNotIn('contents: write',text) + self.assertNotIn('gh release',text) + self.assertIn('python3 scripts/inspect_ipk.py',text) + self.assertIn('bash tests/rootfs_install.sh',text) + self.assertIn('sha256sum -c -',text) + def test_failure_recording_is_scoped(self): + text=(ROOT/'.github/workflows/ci.yml').read_text() + part=text.split('\n record-failures:\n',1)[1].split('\n release:\n')[0] + self.assertIn("github.event_name == 'push'",part) + self.assertIn("github.ref != 'refs/heads/main'",part) + script=(ROOT/'scripts/ci_failure.py').read_text() + self.assertNotIn('feat/mvp',script) + self.assertNotIn('--force',script) + self.assertIn("branch in ('','main')",script) + def test_third_party_actions_pinned(self): + for filename in ('ci.yml','sdk-build.yml'): + for action in re.findall(r'uses: (\S+)',(ROOT/'.github/workflows'/filename).read_text()): + if action.startswith('./'):continue + self.assertRegex(action,r'@[a-f0-9]{40}$') + +if __name__=='__main__':unittest.main(verbosity=2)