From a9195f596eb0d36776767b691bbdd8f5962fa394 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 00:29:51 +0000 Subject: [PATCH 1/8] chore: move audit-syslog-bridge, tunnel and capture-sidecar to submodules; remove svcutil audit-syslog-bridge, tunnel and capture-sidecar now live in their own GameplanePanel repositories (full history) and are checked out here as submodules at the same paths, like mcp-server. svcutil had no importers and is removed. .gitmodules is the one list of split components (component = true). hack/submodules.sh reads it for CI init steps, Makefile image rules and deploy/kind/e2e.sh, and checks the static workflow path filters name every component. ci_scope.py derives its component ids from it, and the freshness check covers every gitlink with its .gitmodules url and branch. .github/workflows/go-component.yaml is the shared CI the component repos call (lint with this repo's .golangci.yml and .hadolint.yaml, race tests on amd64 and arm64 with the coverage gate, govulncheck, image build). The hadolint download moves to .github/actions/install-hadolint so both use one pin. test/e2e/suite-components.json drops the svcutil unexercised entry (signed off by the maintainer). Co-Authored-By: Claude Opus 5.5 Signed-off-by: Claude --- .devcontainer/api/ready.txt | 1 - .devcontainer/api/setup.env | 2 +- .devcontainer/control-plane/ready.txt | 1 - .devcontainer/control-plane/setup.env | 4 +- .devcontainer/dashboard-api/ready.txt | 1 - .devcontainer/dashboard-api/setup.env | 4 +- .devcontainer/full/ready.txt | 7 +- .devcontainer/full/setup.env | 4 +- .devcontainer/go-services/ready.txt | 6 +- .devcontainer/go-services/setup.env | 4 +- .devcontainer/profiles.toml | 11 +- .github/actions/build-e2e-images/action.yml | 4 +- .github/actions/install-hadolint/action.yml | 19 + .github/dependabot.yml | 117 +- .github/workflows/ci.yaml | 63 +- .github/workflows/devcontainers.yaml | 6 + .github/workflows/go-component.yaml | 160 ++ .github/workflows/publish-edge.yaml | 17 +- .github/workflows/release.yaml | 5 +- .gitmodules | 16 + Makefile | 8 +- audit-syslog-bridge | 1 + audit-syslog-bridge/.gitignore | 1 - audit-syslog-bridge/.testcoverage.yml | 16 - audit-syslog-bridge/Dockerfile | 27 - audit-syslog-bridge/README.md | 85 - audit-syslog-bridge/bridge_test.go | 985 ------------ audit-syslog-bridge/go.mod | 3 - audit-syslog-bridge/main.go | 460 ------ audit-syslog-bridge/peek_linux.go | 67 - audit-syslog-bridge/peek_other.go | 10 - audit-syslog-bridge/specs.md | 76 - audit-syslog-bridge/system-deps.toml | 15 - capture-sidecar | 1 + capture-sidecar/.testcoverage.yml | 17 - capture-sidecar/Dockerfile | 41 - capture-sidecar/cmd/main.go | 188 --- capture-sidecar/cmd/main_test.go | 42 - capture-sidecar/go.mod | 10 - capture-sidecar/go.sum | 12 - capture-sidecar/internal/auth/tls.go | 137 -- .../internal/auth/tls_rotation_test.go | 409 ----- capture-sidecar/internal/auth/tls_test.go | 290 ---- capture-sidecar/internal/capture/afpacket.go | 289 ---- .../internal/capture/afpacket_filter_test.go | 176 -- .../internal/capture/afpacket_test.go | 179 --- capture-sidecar/internal/capture/filter.go | 147 -- .../internal/capture/filter_test.go | 149 -- capture-sidecar/internal/capture/writer.go | 351 ---- .../internal/capture/writer_test.go | 675 -------- .../internal/httpserver/artifacts.go | 57 - .../internal/httpserver/artifacts_test.go | 31 - .../internal/httpserver/handlers.go | 975 ----------- .../internal/httpserver/handlers_test.go | 1426 ----------------- .../internal/httpserver/identity.go | 285 ---- .../internal/httpserver/identity_test.go | 273 ---- .../internal/nodecapture/worker.go | 277 ---- .../internal/nodecapture/worker_test.go | 97 -- capture-sidecar/specs.md | 345 ---- capture-sidecar/system-deps.toml | 15 - deploy/kind/e2e.sh | 12 +- go.work | 4 - go.work.sum | 1 + hack/check-doc-versions.sh | 8 +- hack/check-links.sh | 14 +- hack/check-submodule-freshness.sh | 59 +- hack/ci_scope.py | 27 +- hack/submodules.sh | 106 ++ svcutil/.testcoverage.yml | 14 - svcutil/env.go | 52 - svcutil/env_test.go | 208 --- svcutil/go.mod | 3 - svcutil/server.go | 37 - svcutil/server_test.go | 193 --- svcutil/specs.md | 105 -- svcutil/system-deps.toml | 15 - test/e2e/suite-components.json | 1 - tunnel | 1 + tunnel/.gitignore | 1 - tunnel/.testcoverage.yml | 15 - tunnel/Dockerfile.frp | 52 - tunnel/Dockerfile.playit | 59 - tunnel/Dockerfile.tailscale | 33 - tunnel/bench/frp_udp.py | 135 -- .../bench/results/frp-loopback-series-1.jsonl | 17 - .../bench/results/frp-loopback-series-2.jsonl | 17 - tunnel/cmd/relay-load/main.go | 80 - tunnel/cmd/relay-load/main_test.go | 46 - tunnel/forward_metrics.go | 77 - tunnel/frpc/go.mod | 55 - tunnel/frpc/go.sum | 179 --- tunnel/go.mod | 51 - tunnel/go.sum | 239 --- tunnel/internal/relayload/load.go | 187 --- tunnel/main.go | 619 ------- tunnel/main_test.go | 1106 ------------- tunnel/playit_reporter.go | 525 ------ tunnel/playit_reporter_test.go | 652 -------- tunnel/relay_health.go | 295 ---- tunnel/relay_health_test.go | 223 --- tunnel/relay_metrics.go | 49 - tunnel/relay_metrics_test.go | 53 - tunnel/specs.md | 332 ---- tunnel/system-deps.toml | 15 - tunnel/tailscale.go | 237 --- tunnel/tailscale_forward.go | 288 ---- tunnel/tailscale_forward_test.go | 277 ---- tunnel/tailscale_retry_test.go | 150 -- tunnel/tailscale_test.go | 384 ----- 109 files changed, 453 insertions(+), 15955 deletions(-) create mode 100644 .github/actions/install-hadolint/action.yml create mode 100644 .github/workflows/go-component.yaml create mode 160000 audit-syslog-bridge delete mode 100644 audit-syslog-bridge/.gitignore delete mode 100644 audit-syslog-bridge/.testcoverage.yml delete mode 100644 audit-syslog-bridge/Dockerfile delete mode 100644 audit-syslog-bridge/README.md delete mode 100644 audit-syslog-bridge/bridge_test.go delete mode 100644 audit-syslog-bridge/go.mod delete mode 100644 audit-syslog-bridge/main.go delete mode 100644 audit-syslog-bridge/peek_linux.go delete mode 100644 audit-syslog-bridge/peek_other.go delete mode 100644 audit-syslog-bridge/specs.md delete mode 100644 audit-syslog-bridge/system-deps.toml create mode 160000 capture-sidecar delete mode 100644 capture-sidecar/.testcoverage.yml delete mode 100644 capture-sidecar/Dockerfile delete mode 100644 capture-sidecar/cmd/main.go delete mode 100644 capture-sidecar/cmd/main_test.go delete mode 100644 capture-sidecar/go.mod delete mode 100644 capture-sidecar/go.sum delete mode 100644 capture-sidecar/internal/auth/tls.go delete mode 100644 capture-sidecar/internal/auth/tls_rotation_test.go delete mode 100644 capture-sidecar/internal/auth/tls_test.go delete mode 100644 capture-sidecar/internal/capture/afpacket.go delete mode 100644 capture-sidecar/internal/capture/afpacket_filter_test.go delete mode 100644 capture-sidecar/internal/capture/afpacket_test.go delete mode 100644 capture-sidecar/internal/capture/filter.go delete mode 100644 capture-sidecar/internal/capture/filter_test.go delete mode 100644 capture-sidecar/internal/capture/writer.go delete mode 100644 capture-sidecar/internal/capture/writer_test.go delete mode 100644 capture-sidecar/internal/httpserver/artifacts.go delete mode 100644 capture-sidecar/internal/httpserver/artifacts_test.go delete mode 100644 capture-sidecar/internal/httpserver/handlers.go delete mode 100644 capture-sidecar/internal/httpserver/handlers_test.go delete mode 100644 capture-sidecar/internal/httpserver/identity.go delete mode 100644 capture-sidecar/internal/httpserver/identity_test.go delete mode 100644 capture-sidecar/internal/nodecapture/worker.go delete mode 100644 capture-sidecar/internal/nodecapture/worker_test.go delete mode 100644 capture-sidecar/specs.md delete mode 100644 capture-sidecar/system-deps.toml create mode 100755 hack/submodules.sh delete mode 100644 svcutil/.testcoverage.yml delete mode 100644 svcutil/env.go delete mode 100644 svcutil/env_test.go delete mode 100644 svcutil/go.mod delete mode 100644 svcutil/server.go delete mode 100644 svcutil/server_test.go delete mode 100644 svcutil/specs.md delete mode 100644 svcutil/system-deps.toml create mode 160000 tunnel delete mode 100644 tunnel/.gitignore delete mode 100644 tunnel/.testcoverage.yml delete mode 100644 tunnel/Dockerfile.frp delete mode 100644 tunnel/Dockerfile.playit delete mode 100644 tunnel/Dockerfile.tailscale delete mode 100644 tunnel/bench/frp_udp.py delete mode 100644 tunnel/bench/results/frp-loopback-series-1.jsonl delete mode 100644 tunnel/bench/results/frp-loopback-series-2.jsonl delete mode 100644 tunnel/cmd/relay-load/main.go delete mode 100644 tunnel/cmd/relay-load/main_test.go delete mode 100644 tunnel/forward_metrics.go delete mode 100644 tunnel/frpc/go.mod delete mode 100644 tunnel/frpc/go.sum delete mode 100644 tunnel/go.mod delete mode 100644 tunnel/go.sum delete mode 100644 tunnel/internal/relayload/load.go delete mode 100644 tunnel/main.go delete mode 100644 tunnel/main_test.go delete mode 100644 tunnel/playit_reporter.go delete mode 100644 tunnel/playit_reporter_test.go delete mode 100644 tunnel/relay_health.go delete mode 100644 tunnel/relay_health_test.go delete mode 100644 tunnel/relay_metrics.go delete mode 100644 tunnel/relay_metrics_test.go delete mode 100644 tunnel/specs.md delete mode 100644 tunnel/system-deps.toml delete mode 100644 tunnel/tailscale.go delete mode 100644 tunnel/tailscale_forward.go delete mode 100644 tunnel/tailscale_forward_test.go delete mode 100644 tunnel/tailscale_retry_test.go delete mode 100644 tunnel/tailscale_test.go diff --git a/.devcontainer/api/ready.txt b/.devcontainer/api/ready.txt index b47bf4697..408c1c446 100644 --- a/.devcontainer/api/ready.txt +++ b/.devcontainer/api/ready.txt @@ -6,7 +6,6 @@ Works here: cd gp-module && go build ./... cd i18n && go build ./... cd netguard && go build ./... - cd svcutil && go build ./... cd telemetryschema && go build ./... make build-go diff --git a/.devcontainer/api/setup.env b/.devcontainer/api/setup.env index 1bfeb7f7a..428907ea3 100644 --- a/.devcontainer/api/setup.env +++ b/.devcontainer/api/setup.env @@ -1,6 +1,6 @@ ENVTEST_K8S_VERSION="1.36.2" GOLANGCI_LINT_VERSION="v2.14.0" -GO_MODULES="api gameaction gp-module i18n netguard svcutil telemetryschema" +GO_MODULES="api gameaction gp-module i18n netguard telemetryschema" MODULES_DIR="modules" OPTIONAL_STEPS="ai_clis" PROFILE="api" diff --git a/.devcontainer/control-plane/ready.txt b/.devcontainer/control-plane/ready.txt index de193ecef..7b41c5a29 100644 --- a/.devcontainer/control-plane/ready.txt +++ b/.devcontainer/control-plane/ready.txt @@ -6,7 +6,6 @@ Works here: cd gp-module && go build ./... cd i18n && go build ./... cd netguard && go build ./... - cd svcutil && go build ./... cd telemetryschema && go build ./... cd operator && go build ./... cd agent && go build ./... diff --git a/.devcontainer/control-plane/setup.env b/.devcontainer/control-plane/setup.env index 8133edd9c..9ff83945c 100644 --- a/.devcontainer/control-plane/setup.env +++ b/.devcontainer/control-plane/setup.env @@ -1,6 +1,6 @@ ENVTEST_K8S_VERSION="1.36.2" GOLANGCI_LINT_VERSION="v2.14.0" -GO_MODULES="agent api gameaction gameproto gp-module i18n netguard operator svcutil telemetryschema test/e2e" +GO_MODULES="agent api gameaction gameproto gp-module i18n netguard operator telemetryschema test/e2e" KIND_VERSION="v0.32.0" MODULES_DIR="modules" OPTIONAL_STEPS="ai_clis" @@ -10,5 +10,5 @@ READY=".devcontainer/control-plane/ready.txt" SETUP_ENVTEST_VERSION="release-0.24" SPECIFY_VERSION="v1.0.3" STEPS="submodules python3 pyyaml kind oras golangci_lint envtest go_mod_download uv specify ai_clis" -SUBMODULES="modules mcp-server" +SUBMODULES="modules audit-syslog-bridge capture-sidecar mcp-server tunnel" WEBSITE_DIR="website" diff --git a/.devcontainer/dashboard-api/ready.txt b/.devcontainer/dashboard-api/ready.txt index edde26e8e..5f56813e3 100644 --- a/.devcontainer/dashboard-api/ready.txt +++ b/.devcontainer/dashboard-api/ready.txt @@ -7,7 +7,6 @@ Works here: cd gp-module && go build ./... cd i18n && go build ./... cd netguard && go build ./... - cd svcutil && go build ./... cd telemetryschema && go build ./... cd operator && go build ./... cd agent && go build ./... diff --git a/.devcontainer/dashboard-api/setup.env b/.devcontainer/dashboard-api/setup.env index b099fff17..7a3f7e2b9 100644 --- a/.devcontainer/dashboard-api/setup.env +++ b/.devcontainer/dashboard-api/setup.env @@ -1,6 +1,6 @@ ENVTEST_K8S_VERSION="1.36.2" GOLANGCI_LINT_VERSION="v2.14.0" -GO_MODULES="agent api gameaction gp-module i18n netguard operator svcutil telemetryschema" +GO_MODULES="agent api gameaction gp-module i18n netguard operator telemetryschema" KIND_VERSION="v0.32.0" MODULES_DIR="modules" OPTIONAL_STEPS="ai_clis" @@ -10,5 +10,5 @@ READY=".devcontainer/dashboard-api/ready.txt" SETUP_ENVTEST_VERSION="release-0.24" SPECIFY_VERSION="v1.0.3" STEPS="submodules python3 pyyaml kind oras golangci_lint envtest go_mod_download npm_ci_web uv specify ai_clis" -SUBMODULES="modules mcp-server" +SUBMODULES="modules audit-syslog-bridge capture-sidecar mcp-server tunnel" WEBSITE_DIR="website" diff --git a/.devcontainer/full/ready.txt b/.devcontainer/full/ready.txt index 43e571b51..7f384c483 100644 --- a/.devcontainer/full/ready.txt +++ b/.devcontainer/full/ready.txt @@ -7,17 +7,16 @@ Works here: cd gp-module && go build ./... cd i18n && go build ./... cd netguard && go build ./... - cd svcutil && go build ./... cd telemetryschema && go build ./... cd operator && go build ./... cd agent && go build ./... - cd audit-syslog-bridge && go build ./... - cd capture-sidecar && go build ./... cd gameproto && go build ./... cd sentinel && go build ./... cd telemetry-receiver && go build ./... - cd tunnel && go build ./... + cd audit-syslog-bridge && GOWORK=off go build ./... + cd capture-sidecar && GOWORK=off go build ./... cd mcp-server && GOWORK=off go build ./... + cd tunnel && GOWORK=off go build ./... cd website && npm ci && npm run check make module-validate MODULE=minecraft-java cd test/e2e && go vet -tags e2e ./... diff --git a/.devcontainer/full/setup.env b/.devcontainer/full/setup.env index 4930dae80..4273d3398 100644 --- a/.devcontainer/full/setup.env +++ b/.devcontainer/full/setup.env @@ -1,6 +1,6 @@ ENVTEST_K8S_VERSION="1.36.2" GOLANGCI_LINT_VERSION="v2.14.0" -GO_MODULES="agent api audit-syslog-bridge capture-sidecar gameaction gameproto gp-module i18n netguard operator sentinel svcutil telemetryschema telemetry-receiver test/e2e tunnel" +GO_MODULES="agent api gameaction gameproto gp-module i18n netguard operator sentinel telemetryschema telemetry-receiver test/e2e" KIND_VERSION="v0.32.0" MODULES_DIR="modules" OPTIONAL_STEPS="ai_clis" @@ -10,5 +10,5 @@ READY=".devcontainer/full/ready.txt" SETUP_ENVTEST_VERSION="release-0.24" SPECIFY_VERSION="v1.0.3" STEPS="submodules python3 pyyaml kind oras golangci_lint envtest go_mod_download npm_ci_web npm_ci_website uv specify ai_clis" -SUBMODULES="mcp-server website modules" +SUBMODULES="audit-syslog-bridge capture-sidecar mcp-server tunnel website modules" WEBSITE_DIR="website" diff --git a/.devcontainer/go-services/ready.txt b/.devcontainer/go-services/ready.txt index 1c4227b10..f2b11fdc4 100644 --- a/.devcontainer/go-services/ready.txt +++ b/.devcontainer/go-services/ready.txt @@ -1,16 +1,16 @@ [devcontainer] ready: Gameplane · Go services Works here: - cd audit-syslog-bridge && go build ./... - cd capture-sidecar && go build ./... cd gameproto && go build ./... cd gp-module && go build ./... cd i18n && go build ./... cd sentinel && go build ./... cd telemetryschema && go build ./... cd telemetry-receiver && go build ./... - cd tunnel && go build ./... + cd audit-syslog-bridge && GOWORK=off go build ./... + cd capture-sidecar && GOWORK=off go build ./... cd mcp-server && GOWORK=off go build ./... + cd tunnel && GOWORK=off go build ./... make build-go Ports: none diff --git a/.devcontainer/go-services/setup.env b/.devcontainer/go-services/setup.env index 6d2220a8e..a71e2f065 100644 --- a/.devcontainer/go-services/setup.env +++ b/.devcontainer/go-services/setup.env @@ -1,10 +1,10 @@ GOLANGCI_LINT_VERSION="v2.14.0" -GO_MODULES="audit-syslog-bridge capture-sidecar gameproto gp-module i18n sentinel telemetryschema telemetry-receiver tunnel" +GO_MODULES="gameproto gp-module i18n sentinel telemetryschema telemetry-receiver" MODULES_DIR="modules" OPTIONAL_STEPS="ai_clis" PROFILE="go-services" READY=".devcontainer/go-services/ready.txt" SPECIFY_VERSION="v1.0.3" STEPS="submodules python3 golangci_lint go_mod_download uv specify ai_clis" -SUBMODULES="mcp-server" +SUBMODULES="audit-syslog-bridge capture-sidecar mcp-server tunnel" WEBSITE_DIR="website" diff --git a/.devcontainer/profiles.toml b/.devcontainer/profiles.toml index 93b7f1a69..a24943fff 100644 --- a/.devcontainer/profiles.toml +++ b/.devcontainer/profiles.toml @@ -86,7 +86,7 @@ checks = [ [profile.api] size = "component" title = "API" -dirs = ["api", "svcutil"] +dirs = ["api"] extensions = ["golang.go"] checks = ["{go_build}"] @@ -120,11 +120,14 @@ dirs = [ "telemetry-receiver", "tunnel", ] -submodules = ["mcp-server"] +submodules = ["audit-syslog-bridge", "capture-sidecar", "mcp-server", "tunnel"] extensions = ["golang.go"] checks = [ "{go_build}", + "cd audit-syslog-bridge && GOWORK=off go build ./...", + "cd capture-sidecar && GOWORK=off go build ./...", "cd mcp-server && GOWORK=off go build ./...", + "cd tunnel && GOWORK=off go build ./...", ] [profile.website] @@ -158,7 +161,7 @@ size = "part" title = "Dashboard and API" includes = ["web", "api", "operator", "agent"] dirs = ["deploy/kind", "charts/gameplane"] -submodules = ["modules", "mcp-server"] +submodules = ["modules", "audit-syslog-bridge", "capture-sidecar", "mcp-server", "tunnel"] extras = [ { name = "docker", kind = "service", version = "docker", reason = "In-container Docker daemon for the kind dev cluster (OD-2; deploy/kind/up.sh:195-199)." }, ] @@ -176,7 +179,7 @@ size = "part" title = "Control plane" includes = ["operator", "api", "agent"] dirs = ["charts/gameplane", "deploy/kind", "test/e2e"] -submodules = ["modules", "mcp-server"] +submodules = ["modules", "audit-syslog-bridge", "capture-sidecar", "mcp-server", "tunnel"] extras = [ { name = "docker", kind = "service", version = "docker", reason = "In-container Docker daemon for the kind cluster and E2E images (OD-2; test/e2e/gatewayparity_e2e_test.go:156)." }, ] diff --git a/.github/actions/build-e2e-images/action.yml b/.github/actions/build-e2e-images/action.yml index 4bec9edf6..e2f889283 100644 --- a/.github/actions/build-e2e-images/action.yml +++ b/.github/actions/build-e2e-images/action.yml @@ -15,9 +15,9 @@ inputs: runs: using: composite steps: - - name: init mcp-server submodule + - name: init component submodules shell: bash - run: git submodule update --init mcp-server + run: ./hack/submodules.sh init - uses: docker/setup-buildx-action@d7f5e7f509e45cec5c76c4d5afdd7de93d0b3df5 # v4.1.0 - name: bake e2e images (operator/api/agent/sentinel/capture-sidecar/telemetry-receiver/fakeoidc/mcp-server/audit-syslog-bridge/tunnel-frp) uses: docker/bake-action@d3418bd7d0e9324001bca92fa8ba175ea7e6dc9b # v7.3.0 diff --git a/.github/actions/install-hadolint/action.yml b/.github/actions/install-hadolint/action.yml new file mode 100644 index 000000000..459ecb6a7 --- /dev/null +++ b/.github/actions/install-hadolint/action.yml @@ -0,0 +1,19 @@ +name: install hadolint +description: >- + Download the pinned hadolint release, verify its checksum and put it on PATH. + Used by ci.yaml workflow-lint and by go-component.yaml for the split components. + +runs: + using: composite + steps: + - name: hadolint (download and verify) + shell: bash + run: | + set -euo pipefail + mkdir -p "$RUNNER_TEMP/hadolint" + cd "$RUNNER_TEMP/hadolint" + curl -fsSL -o hadolint \ + https://github.com/hadolint/hadolint/releases/download/v2.14.0/hadolint-linux-x86_64 + echo "6bf226944684f56c84dd014e8b979d27425c0148f61b3bd99bcc6f39e9dc5a47 hadolint" | sha256sum -c - + chmod +x hadolint + echo "$RUNNER_TEMP/hadolint" >> "$GITHUB_PATH" diff --git a/.github/dependabot.yml b/.github/dependabot.yml index b6604c56e..5537b68bc 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -3,7 +3,7 @@ version: 2 updates: - # Go modules — 14 entries (one per module in go.work) + # Go modules — 12 entries (one per module in go.work) - package-ecosystem: "gomod" directory: "/agent" schedule: @@ -32,34 +32,6 @@ updates: api-minor-patch: update-types: ["minor", "patch"] - - package-ecosystem: "gomod" - directory: "/audit-syslog-bridge" - schedule: - interval: "weekly" - day: "monday" - time: "03:00" - commit-message: - prefix: "chore(deps)" - include: "scope" - open-pull-requests-limit: 5 - groups: - audit-syslog-bridge-minor-patch: - update-types: ["minor", "patch"] - - - package-ecosystem: "gomod" - directory: "/capture-sidecar" - schedule: - interval: "weekly" - day: "monday" - time: "03:00" - commit-message: - prefix: "chore(deps)" - include: "scope" - open-pull-requests-limit: 5 - groups: - capture-sidecar-minor-patch: - update-types: ["minor", "patch"] - - package-ecosystem: "gomod" directory: "/gameaction" schedule: @@ -144,20 +116,6 @@ updates: sentinel-minor-patch: update-types: ["minor", "patch"] - - package-ecosystem: "gomod" - directory: "/svcutil" - schedule: - interval: "weekly" - day: "monday" - time: "03:00" - commit-message: - prefix: "chore(deps)" - include: "scope" - open-pull-requests-limit: 5 - groups: - svcutil-minor-patch: - update-types: ["minor", "patch"] - - package-ecosystem: "gomod" directory: "/telemetryschema" schedule: @@ -214,35 +172,6 @@ updates: test-e2e-minor-patch: update-types: ["minor", "patch"] - - package-ecosystem: "gomod" - directory: "/tunnel" - schedule: - interval: "weekly" - day: "monday" - time: "03:00" - commit-message: - prefix: "chore(deps)" - include: "scope" - open-pull-requests-limit: 5 - groups: - tunnel-minor-patch: - update-types: ["minor", "patch"] - - # frpc build module (tunnel/Dockerfile.frp builds frpc from these pins) - - package-ecosystem: "gomod" - directory: "/tunnel/frpc" - schedule: - interval: "weekly" - day: "monday" - time: "03:00" - commit-message: - prefix: "chore(deps)" - include: "scope" - open-pull-requests-limit: 5 - groups: - tunnel-frpc-minor-patch: - update-types: ["minor", "patch"] - # npm — 1 entry (React dashboard) - package-ecosystem: "npm" directory: "/web" @@ -258,7 +187,7 @@ updates: npm-minor-patch: update-types: ["minor", "patch"] - # Docker — 13 entries (base images and service containers) + # Docker — 9 entries (base images and service containers) - package-ecosystem: "docker" directory: "/agent" schedule: @@ -287,34 +216,6 @@ updates: api-docker-minor-patch: update-types: ["minor", "patch"] - - package-ecosystem: "docker" - directory: "/audit-syslog-bridge" - schedule: - interval: "weekly" - day: "monday" - time: "03:00" - commit-message: - prefix: "chore(deps)" - include: "scope" - open-pull-requests-limit: 5 - groups: - audit-syslog-bridge-docker-minor-patch: - update-types: ["minor", "patch"] - - - package-ecosystem: "docker" - directory: "/capture-sidecar" - schedule: - interval: "weekly" - day: "monday" - time: "03:00" - commit-message: - prefix: "chore(deps)" - include: "scope" - open-pull-requests-limit: 5 - groups: - capture-sidecar-docker-minor-patch: - update-types: ["minor", "patch"] - - package-ecosystem: "docker" directory: "/containers/common/steamcmd" schedule: @@ -399,20 +300,6 @@ updates: test-e2e-docker-minor-patch: update-types: ["minor", "patch"] - - package-ecosystem: "docker" - directory: "/tunnel" - schedule: - interval: "weekly" - day: "monday" - time: "03:00" - commit-message: - prefix: "chore(deps)" - include: "scope" - open-pull-requests-limit: 5 - groups: - tunnel-docker-minor-patch: - update-types: ["minor", "patch"] - - package-ecosystem: "docker" directory: "/web" schedule: diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 49fc85104..136a19b5a 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -26,7 +26,6 @@ on: - "**/specs.md" - "README.md" - "docs/**" - - "audit-syslog-bridge/README.md" - "telemetry-receiver/README.md" - "CHANGELOG.md" - "AGENTS.md" @@ -188,15 +187,13 @@ jobs: - 'operator/**' - 'api/**' - 'agent/**' - - 'audit-syslog-bridge/**' - 'telemetry-receiver/**' - 'telemetryschema/**' - 'i18n/**' - 'sentinel/**' - - 'capture-sidecar/**' - - 'svcutil/**' - - 'tunnel/**' - 'gp-module/**' + # The capture-sidecar submodule (its pointer) gates capture-sidecar-setcap-proof. + - 'capture-sidecar' - 'test/e2e/**' - 'go.work' - 'go.work.sum' @@ -235,10 +232,12 @@ jobs: - 'test/e2e/**' - 'deploy/kind/**' - 'containers/docker-bake.hcl' - # mcp-server is a submodule: a pointer bump changes the image the - # optional-components e2e loads. 'mcp-server/**' covers any future in-tree files. + # Component submodules (hack/submodules.sh, enforced by its + # `check` in submodule-freshness): a pointer bump changes an image the e2e loads. - 'mcp-server' - - 'mcp-server/**' + - 'audit-syslog-bridge' + - 'tunnel' + - 'capture-sidecar' - 'hack/trivy-scan-images.sh' - 'hack/check-image-scan_test.sh' # Narrower than e2etree on purpose: this backs a job that only @@ -258,7 +257,7 @@ jobs: # specs/done_007-capture-overhead-guard/OPEN-DECISIONS.md). Master pushes # run it through the e2e gate instead. capture_overhead: - - 'capture-sidecar/**' + - 'capture-sidecar' - 'operator/internal/controller/networkcapture*' - 'api/internal/handlers/capture*' - 'test/e2e/internal/minecraft-java/**' @@ -269,6 +268,11 @@ jobs: - 'modules' - 'website' - 'mcp-server' + - 'audit-syslog-bridge' + - 'tunnel' + - 'capture-sidecar' + - '.gitmodules' + - 'hack/submodules.sh' - 'hack/check-submodule-freshness.sh' - 'hack/check-submodule-freshness_test.sh' # Gate scope for codegen drift (spec 013 T007). @@ -313,6 +317,9 @@ jobs: - 'hack/testdata/check-publish-edge-paths/**' - '**/Dockerfile*' - 'mcp-server' + - 'audit-syslog-bridge' + - 'tunnel' + - 'capture-sidecar' - '.hadolint.yaml' - 'hack/check-hadolint_test.sh' - 'hack/testdata/hadolint/**' @@ -344,7 +351,6 @@ jobs: - 'docs/roadmap.md' - 'docs/security.md' - 'docs/tunnels.md' - - 'audit-syslog-bridge/README.md' - 'telemetry-receiver/README.md' - 'docs/comparison-sources.md' - 'FEATURES.md' @@ -523,6 +529,8 @@ jobs: contents: read steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: init component submodules + run: ./hack/submodules.sh init - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 - name: install libcap2-bin (getcap) run: | @@ -712,8 +720,8 @@ jobs: - name: prove the gate fails on a stale types edit run: ./hack/check-codegen-drift_test.sh - # Spec 013 G6 (OD-1): the modules/, website/ and mcp-server/ gitlinks must point at - # commits already on each submodule's main branch, so a pointer bump never + # Spec 013 G6 (OD-1): every submodule gitlink (modules/, website/ and the + # component submodules in .gitmodules) must point at commits already on its main branch, so a pointer bump never # lands before its submodule PR merges. submodule-freshness: name: submodule freshness @@ -733,6 +741,8 @@ jobs: run: ./hack/check-submodule-freshness_test.sh - name: submodule pointers are on upstream main run: ./hack/check-submodule-freshness.sh + - name: component submodules are in the workflow path filters + run: ./hack/submodules.sh check # Spec 028: a PR that adds a move brief under specs/028-split-big-packages/briefs/ must # keep every test name and change test files only in the OD-6/OD-9 mechanical ways. @@ -811,7 +821,7 @@ jobs: strategy: fail-fast: false matrix: - module: [netguard, gameaction, gameproto, telemetryschema, i18n, operator, agent, api, sentinel, audit-syslog-bridge, telemetry-receiver, capture-sidecar, svcutil, tunnel, gp-module, test/e2e] + module: [netguard, gameaction, gameproto, telemetryschema, i18n, operator, agent, api, sentinel, telemetry-receiver, gp-module, test/e2e] exclude: ${{ fromJSON(needs.changes.outputs.lint-exclude) }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -897,7 +907,7 @@ jobs: strategy: fail-fast: false matrix: - module: [netguard, gameaction, gameproto, telemetryschema, i18n, operator, api, agent, audit-syslog-bridge, telemetry-receiver, sentinel, capture-sidecar, svcutil, tunnel, gp-module] + module: [netguard, gameaction, gameproto, telemetryschema, i18n, operator, api, agent, telemetry-receiver, sentinel, gp-module] exclude: ${{ fromJSON(needs.changes.outputs.go-exclude) }} arch: [amd64, arm64] steps: @@ -945,13 +955,6 @@ jobs: read -r -a packages <<<"$GO_PACKAGES" go test -covermode=atomic -coverpkg=./... \ -coverprofile=coverage/unit.out "${packages[@]}" - - name: profile local UDP forwarding against direct echo - if: matrix.module == 'tunnel' && matrix.arch == 'amd64' && env.GO_PACKAGES != '' - working-directory: tunnel - run: | - go test -count=1 -v -run '^TestRelayLoadForwardingProfile$' -cpuprofile="$RUNNER_TEMP/relay.cpu" -memprofile="$RUNNER_TEMP/relay.mem" -o "$RUNNER_TEMP/relay.test" . - go tool pprof -top -cum -nodecount=12 -focus='forwarder' "$RUNNER_TEMP/relay.test" "$RUNNER_TEMP/relay.cpu" - go tool pprof -top -alloc_space -nodecount=12 -focus='forwarder' "$RUNNER_TEMP/relay.test" "$RUNNER_TEMP/relay.mem" - name: sentinel mixed-load regression measurements if: matrix.module == 'sentinel' && env.GO_PACKAGES != '' working-directory: sentinel @@ -1670,9 +1673,9 @@ jobs: contents: read steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - name: init mcp-server submodule - # check-publish-edge-paths.sh and its test read mcp-server/Dockerfile. - run: git submodule update --init mcp-server + - name: init component submodules + # check-publish-edge-paths.sh and its test read the component Dockerfiles. + run: ./hack/submodules.sh init - name: actionlint (download and verify) run: | set -euo pipefail @@ -1691,16 +1694,8 @@ jobs: "$tmp/actionlint" # Spec 013 G3: hadolint over every tracked Dockerfile, at warning and # above (.hadolint.yaml). Same pinned-download pattern as actionlint. - - name: hadolint (download and verify) - run: | - set -euo pipefail - mkdir -p "$RUNNER_TEMP/hadolint" - cd "$RUNNER_TEMP/hadolint" - curl -fsSL -o hadolint \ - https://github.com/hadolint/hadolint/releases/download/v2.14.0/hadolint-linux-x86_64 - echo "6bf226944684f56c84dd014e8b979d27425c0148f61b3bd99bcc6f39e9dc5a47 hadolint" | sha256sum -c - - chmod +x hadolint - echo "$RUNNER_TEMP/hadolint" >> "$GITHUB_PATH" + - name: install hadolint + uses: ./.github/actions/install-hadolint - name: prove the Dockerfile lint gate can fail run: ./hack/check-hadolint_test.sh - name: hadolint diff --git a/.github/workflows/devcontainers.yaml b/.github/workflows/devcontainers.yaml index 7dddab27f..0c29eb1ea 100644 --- a/.github/workflows/devcontainers.yaml +++ b/.github/workflows/devcontainers.yaml @@ -22,6 +22,9 @@ on: - 'modules' - 'website' - 'mcp-server' + - 'audit-syslog-bridge' + - 'tunnel' + - 'capture-sidecar' - 'web/package*.json' - '.github/workflows/devcontainers.yaml' push: @@ -38,6 +41,9 @@ on: - 'modules' - 'website' - 'mcp-server' + - 'audit-syslog-bridge' + - 'tunnel' + - 'capture-sidecar' - 'web/package*.json' - '.github/workflows/devcontainers.yaml' diff --git a/.github/workflows/go-component.yaml b/.github/workflows/go-component.yaml new file mode 100644 index 000000000..5d164dfb6 --- /dev/null +++ b/.github/workflows/go-component.yaml @@ -0,0 +1,160 @@ +# Shared CI for the Go components split out of this repository (mcp, +# audit-syslog-bridge, tunnel, capture-sidecar; see hack/submodules.sh). Each +# component repo calls this workflow from a short ci.yaml, pinned by SHA: +# +# jobs: +# ci: +# uses: GameplanePanel/Gameplane/.github/workflows/go-component.yaml@ # master +# with: +# dockerfiles: Dockerfile +# +# Lint uses this repository's root .golangci.yml and .hadolint.yaml, fetched +# from master, so every component is linted by the same ruleset as Gameplane +# itself (the single-config rule R-010) and no component carries a copy. +name: go component + +on: + workflow_call: + inputs: + path: + description: >- + Folder name the component has inside Gameplane. The Dockerfiles copy + `/...` from the Gameplane repo root, so the image build checks + the component out under this name. Defaults to the repository name. + type: string + default: "" + dockerfiles: + description: Space-separated Dockerfiles (relative to the component root) to lint and build. + type: string + default: Dockerfile + amd64-extra: + description: Optional extra shell step run in the component root after the amd64 tests. + type: string + default: "" + +permissions: + contents: read + +env: + GO_VERSION: "1.27" + GOLANGCI_LINT_VERSION: v2.14.0 + GOVULNCHECK_VERSION: v1.9.0 + GO_TEST_COVERAGE_VERSION: v2.18.9 + +jobs: + lint: + name: lint + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: shared lint config from Gameplane + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: GameplanePanel/Gameplane + ref: master + path: .gameplane + persist-credentials: false + sparse-checkout: | + .golangci.yml + .hadolint.yaml + .github/actions/install-hadolint/ + sparse-checkout-cone-mode: false + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version: ${{ env.GO_VERSION }} + check-latest: true + - name: gofmt + run: | + unformatted=$(gofmt -l . | grep -v '^\.gameplane/' || true) + if [ -n "$unformatted" ]; then + echo "gofmt needed on:"; echo "$unformatted"; exit 1 + fi + - name: go vet + run: go vet ./... + - uses: golangci/golangci-lint-action@ba0d7d2ec06a0ea1cb5fa41b2e4a3ab91d21278a # v9.3.0 + with: + version: ${{ env.GOLANGCI_LINT_VERSION }} + args: --config=.gameplane/.golangci.yml + - name: install hadolint + uses: ./.gameplane/.github/actions/install-hadolint + - name: hadolint + env: + DOCKERFILES: ${{ inputs.dockerfiles }} + run: | + read -r -a files <<<"$DOCKERFILES" + hadolint --config .gameplane/.hadolint.yaml "${files[@]}" + + test: + name: test (${{ matrix.arch }}) + runs-on: ${{ matrix.arch == 'arm64' && 'ubuntu-24.04-arm' || 'ubuntu-latest' }} + timeout-minutes: 20 + strategy: + fail-fast: false + matrix: + arch: [amd64, arm64] + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version: ${{ env.GO_VERSION }} + check-latest: true + - name: unit test + coverage + run: | + mkdir -p coverage + go test -race -covermode=atomic -coverpkg=./... -coverprofile=coverage/unit.out ./... + - name: coverage threshold gate (.testcoverage.yml) + run: go run "github.com/vladopajic/go-test-coverage/v2@${GO_TEST_COVERAGE_VERSION}" --config=.testcoverage.yml + - name: extra amd64 step + if: matrix.arch == 'amd64' && inputs.amd64-extra != '' + env: + EXTRA: ${{ inputs.amd64-extra }} + run: bash -euo pipefail -c "$EXTRA" + + govulncheck: + name: govulncheck + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version: ${{ env.GO_VERSION }} + check-latest: true + - name: govulncheck + run: go run "golang.org/x/vuln/cmd/govulncheck@${GOVULNCHECK_VERSION}" ./... + + image: + name: image build + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + # The Dockerfiles take the Gameplane repo root as build context and copy + # /..., so check the component out under that folder name. + - name: folder name + id: dir + env: + INPUT_PATH: ${{ inputs.path }} + REPO_NAME: ${{ github.event.repository.name }} + run: echo "dir=${INPUT_PATH:-$REPO_NAME}" >> "$GITHUB_OUTPUT" + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + path: ${{ steps.dir.outputs.dir }} + persist-credentials: false + - name: docker build + env: + DIR: ${{ steps.dir.outputs.dir }} + DOCKERFILES: ${{ inputs.dockerfiles }} + run: | + read -r -a files <<<"$DOCKERFILES" + for f in "${files[@]}"; do + echo "::group::docker build $DIR/$f" + docker build -f "$DIR/$f" -t "component-ci:$(basename "$f" | tr '[:upper:].' '[:lower:]-')" . + echo "::endgroup::" + done diff --git a/.github/workflows/publish-edge.yaml b/.github/workflows/publish-edge.yaml index 086907215..43dc99c3d 100644 --- a/.github/workflows/publish-edge.yaml +++ b/.github/workflows/publish-edge.yaml @@ -30,14 +30,16 @@ on: - "gameproto/**" - "telemetryschema/**" - "i18n/**" - - "svcutil/**" - "gp-module/**" + - "audit-syslog-bridge" - "audit-syslog-bridge/**" - "telemetry-receiver/**" - "sentinel/**" + - "capture-sidecar" - "capture-sidecar/**" - - "mcp-server/**" - "mcp-server" + - "mcp-server/**" + - "tunnel" - "tunnel/**" - "go.work" - "go.work.sum" @@ -73,9 +75,9 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 - - name: init mcp-server submodule - # select_images reads mcp-server/Dockerfile's COPY inputs. - run: git submodule update --init mcp-server + - name: init component submodules + # select_images reads the component Dockerfiles' COPY inputs. + run: ./hack/submodules.sh init - name: include changes since the last successful publish id: scope env: @@ -103,9 +105,8 @@ jobs: matrix: ${{ fromJSON(needs.changes.outputs.matrix) }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - name: init mcp-server submodule - if: matrix.component == 'mcp-server' - run: git submodule update --init mcp-server + - name: init component submodules + run: ./hack/submodules.sh init # Signing is mandatory for the official edge channel: fail before anything # is pushed if the key is absent, rather than shipping unsigned images. # The key has been provisioned since module signing went live, so this diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index 3005ac034..bad3fcc8a 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -43,9 +43,8 @@ jobs: dockerfile: tunnel/Dockerfile.playit steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - name: init mcp-server submodule - if: matrix.component == 'mcp-server' - run: git submodule update --init mcp-server + - name: init component submodules + run: ./hack/submodules.sh init # Signing is mandatory for an official release: fail before anything is # pushed rather than publish unsigned images. Mirrors publish-edge.yaml. - name: require signing key diff --git a/.gitmodules b/.gitmodules index 5c40d9b00..4defe8033 100644 --- a/.gitmodules +++ b/.gitmodules @@ -10,3 +10,19 @@ path = mcp-server url = https://github.com/GameplanePanel/mcp.git branch = main + component = true +[submodule "audit-syslog-bridge"] + path = audit-syslog-bridge + url = https://github.com/GameplanePanel/audit-syslog-bridge.git + branch = main + component = true +[submodule "tunnel"] + path = tunnel + url = https://github.com/GameplanePanel/tunnel.git + branch = main + component = true +[submodule "capture-sidecar"] + path = capture-sidecar + url = https://github.com/GameplanePanel/capture-sidecar.git + branch = main + component = true diff --git a/Makefile b/Makefile index 4f01c7b2f..52f190a75 100644 --- a/Makefile +++ b/Makefile @@ -40,7 +40,7 @@ KUBECONFIG_ENV := KUBE_CONTEXT := kind-$(KIND_CLUSTER) endif -GO_MODULES := netguard gameaction gameproto telemetryschema i18n gp-module operator api agent audit-syslog-bridge telemetry-receiver sentinel capture-sidecar svcutil tunnel +GO_MODULES := netguard gameaction gameproto telemetryschema i18n gp-module operator api agent telemetry-receiver sentinel GO_INTEGRATION_MODULES := operator api # test/e2e is a separate module (its own go.mod, excluded from the coverage @@ -344,24 +344,28 @@ images: $(addprefix image-,$(IMAGES)) image-audit-syslog image-tunnel-frp image- # Pattern rule for standard-shaped images image-%: ## Build container image @hack/need.sh docker - @if [ "$*" = mcp-server ] && [ ! -f mcp-server/Dockerfile ]; then git submodule update --init mcp-server; fi + @hack/submodules.sh ensure $* docker build -t $(REGISTRY)/$*:$(TAG) -f $*/Dockerfile . # Non-standard images (target name ≠ dir, or special Dockerfile paths) image-audit-syslog: ## Build audit-syslog-bridge image @hack/need.sh docker + @hack/submodules.sh ensure audit-syslog-bridge docker build -t $(REGISTRY)/audit-syslog-bridge:$(TAG) -f audit-syslog-bridge/Dockerfile . image-tunnel-frp: ## Build tunnel-frp image @hack/need.sh docker + @hack/submodules.sh ensure tunnel docker build -t $(REGISTRY)/tunnel-frp:$(TAG) -f tunnel/Dockerfile.frp . image-tunnel-tailscale: ## Build tunnel-tailscale image @hack/need.sh docker + @hack/submodules.sh ensure tunnel docker build -t $(REGISTRY)/tunnel-tailscale:$(TAG) -f tunnel/Dockerfile.tailscale . image-tunnel-playit: ## Build tunnel-playit image @hack/need.sh docker + @hack/submodules.sh ensure tunnel docker build -t $(REGISTRY)/tunnel-playit:$(TAG) -f tunnel/Dockerfile.playit . # -------- codegen -------- diff --git a/audit-syslog-bridge b/audit-syslog-bridge new file mode 160000 index 000000000..7a5d30d1e --- /dev/null +++ b/audit-syslog-bridge @@ -0,0 +1 @@ +Subproject commit 7a5d30d1efc2631c9e7bc077f9e389c03513e9a9 diff --git a/audit-syslog-bridge/.gitignore b/audit-syslog-bridge/.gitignore deleted file mode 100644 index 38a027e71..000000000 --- a/audit-syslog-bridge/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/audit-syslog-bridge diff --git a/audit-syslog-bridge/.testcoverage.yml b/audit-syslog-bridge/.testcoverage.yml deleted file mode 100644 index 15afb95c1..000000000 --- a/audit-syslog-bridge/.testcoverage.yml +++ /dev/null @@ -1,16 +0,0 @@ -# Coverage threshold gate for the audit-syslog-bridge module. -# Enforced by `make cover-go-check` via go-test-coverage/v2. -# -# The bridge is a small, pure-stdlib HTTP-JSON → RFC 5424 syslog relay. The -# tests cover the syslog framing, config validation, the HTTP handler (TCP/UDP -# forward, auth, method/body errors, forward failure), and the reconnecting -# forwarder. The uncovered remainder is main()/run() process wiring -# (ListenAndServe + signal handling), which isn't unit-testable. Gate below -# measured; ratchet up as coverage grows. -profile: coverage/unit.out -github-action-output: false - -threshold: - file: 0 - package: 0 - total: 70 diff --git a/audit-syslog-bridge/Dockerfile b/audit-syslog-bridge/Dockerfile deleted file mode 100644 index 08a22cb3a..000000000 --- a/audit-syslog-bridge/Dockerfile +++ /dev/null @@ -1,27 +0,0 @@ -FROM --platform=$BUILDPLATFORM golang:1.27-alpine AS build -WORKDIR /src - -COPY audit-syslog-bridge/go.mod audit-syslog-bridge/go.sum* ./audit-syslog-bridge/ -WORKDIR /src/audit-syslog-bridge -RUN go mod download - -WORKDIR /src -COPY audit-syslog-bridge/ ./audit-syslog-bridge/ -WORKDIR /src/audit-syslog-bridge - -ARG VERSION=dev -# Cross-compile on the build host ($BUILDPLATFORM above) rather than under -# QEMU emulation: multi-arch release builds of the arm64 image were slow -# enough to hit the release job timeout. -ARG TARGETARCH -RUN CGO_ENABLED=0 GOOS=linux GOARCH=${TARGETARCH} go build \ - -trimpath \ - -ldflags="-s -w -X main.Version=${VERSION}" \ - -o /out/audit-syslog-bridge . - -FROM gcr.io/distroless/static:nonroot -WORKDIR / -COPY --from=build /out/audit-syslog-bridge /audit-syslog-bridge -USER 65532:65532 -EXPOSE 8514 -ENTRYPOINT ["/audit-syslog-bridge"] diff --git a/audit-syslog-bridge/README.md b/audit-syslog-bridge/README.md deleted file mode 100644 index 9752887d7..000000000 --- a/audit-syslog-bridge/README.md +++ /dev/null @@ -1,85 +0,0 @@ -# audit-syslog-bridge - -The **audit-syslog-bridge** [optional] is a tiny, generic **HTTP-JSON → syslog** relay. It accepts an HTTP `POST` whose -body is a single JSON document and re-emits that document as an -[RFC 5424](https://www.rfc-editor.org/rfc/rfc5424) syslog message to a -configured collector (TCP, TCP over TLS, or UDP). - -It exists so Gameplane's [audit webhook sink](../docs/install.md#audit-log) can -reach a syslog/SIEM endpoint, but it is deliberately **schema-agnostic**: it -forwards the received body verbatim as the syslog `MSG`, so it works for any -JSON-webhook source, not just audit events. Nothing in it is Gameplane-specific. - -## Behavior - -- `POST /` with a JSON body → forwarded as one syslog record. Returns `204`. - - TCP uses RFC 6587 octet-counting framing (` `); UDP sends the bare - message as one datagram. - - The receive time becomes the syslog `TIMESTAMP`; the body becomes `MSG` - (collapsed to a single line). -- `GET /healthz` → `200 ok` (for Kubernetes probes). -- Other methods → `405`; empty body → `400`; a configured-but-mismatched auth - header → `401`; a failed forward to the collector → `502`. - -The forwarder reuses a lazily-dialed connection, bounds each write with a -deadline (so a hung collector can't wedge the relay), and reconnects once on a -write error. Before it reuses a TCP connection it checks that the collector -hasn't closed it, and opens a fresh one if it has. This check is best-effort: it -waits only a few milliseconds for the collector's close, so a close that -arrives later can still lose one record while the bridge returns `204` (written -to connection). Syslog has no application-level acknowledgement, so this window -can be narrowed but not closed. - -Each inbound request must arrive in full (headers and body) within 15 s, and -idle keep-alive connections close after 120 s. - -## Transport: prefer TCP - -`SYSLOG_NETWORK=tcp` (the default) is recommended for an audit/compliance trail: - -- **UDP has no delivery confirmation.** A connected-UDP write succeeds locally - even when the collector is down, so the bridge returns `204` and the API - counts the event `sent` while nothing actually arrives. TCP surfaces a dead - collector as a `502` (→ API `failed`), which is the signal you want. -- **UDP caps message size.** A record whose JSON body approaches the 64 KiB - intake limit can exceed the single-datagram ceiling and be dropped; TCP - streams it fine. -- **TCP (and TLS) can still lose one record after a collector-side close.** - A 204 means the record was written to the collector connection (best effort; - the connection may close concurrently and the record be lost). If the - collector closes a reused connection and its FIN/RST reaches the bridge only - after the short liveness probe, the close goes unnoticed: one record is - written into the dead connection and the bridge returns `204`. The following - write detects the close, reconnects, and retries. If the retry succeeds, the - bridge returns `204` and the record is delivered; if the retry fails, the - bridge returns `502` and that record is not delivered. Syslog framing has no - acknowledgement, so this window cannot be closed without a different transport - (for example one with per-record acks). - -`AUTH_HEADER` gates who may inject records — set it (the chart wires it from the -same Secret as the API's webhook token). Without it the relay accepts any POST. - -## Configuration (environment variables) - -| Var | Default | Meaning | -|---|---|---| -| `LISTEN_ADDR` | `:8514` | HTTP listen address | -| `SYSLOG_ADDR` | — (**required**) | collector `host:port` | -| `SYSLOG_NETWORK` | `tcp` | `tcp` or `udp` | -| `SYSLOG_TLS` | `false` | wrap a `tcp` connection in (verified) TLS | -| `APP_NAME` | `gameplane-audit` | RFC 5424 `APP-NAME` | -| `FACILITY` | `local0` | `kern`/`user`/`daemon`/`auth`/…/`local0`–`local7` | -| `SEVERITY` | `info` | `emerg`/`alert`/`crit`/`err`/`warning`/`notice`/`info`/`debug` | -| `SYSLOG_HOSTNAME` | OS hostname | RFC 5424 `HOSTNAME` field | -| `AUTH_HEADER` | — | if set, inbound requests must carry this exact `Authorization` header | - -## Run via the Helm chart - -The chart deploys this automatically when you set -`api.audit.webhook.syslogBridge.enabled=true` and a collector address — see the -[install docs](../docs/install.md#audit-log). Standalone: - -```sh -docker run -e SYSLOG_ADDR=syslog.example:514 \ - ghcr.io/gameplanepanel/gameplane/audit-syslog-bridge:edge -``` diff --git a/audit-syslog-bridge/bridge_test.go b/audit-syslog-bridge/bridge_test.go deleted file mode 100644 index ae9c2c5a3..000000000 --- a/audit-syslog-bridge/bridge_test.go +++ /dev/null @@ -1,985 +0,0 @@ -package main - -import ( - "context" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "crypto/tls" - "crypto/x509" - "crypto/x509/pkix" - "encoding/pem" - "errors" - "io" - "math/big" - "net" - "net/http" - "net/http/httptest" - "os" - "strconv" - "strings" - "sync" - "testing" - "time" -) - -// generateTestTLSCert returns a self-signed ECDSA certificate and key valid -// for 127.0.0.1, usable as both the test collector's server certificate and -// (via its DER bytes) the client's trusted root. -func generateTestTLSCert(t *testing.T) tls.Certificate { - t.Helper() - priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - if err != nil { - t.Fatalf("generate key: %v", err) - } - tmpl := &x509.Certificate{ - SerialNumber: big.NewInt(1), - Subject: pkix.Name{CommonName: "127.0.0.1"}, - NotBefore: time.Now().Add(-time.Hour), - NotAfter: time.Now().Add(time.Hour), - KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, - ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, - IPAddresses: []net.IP{net.ParseIP("127.0.0.1")}, - IsCA: true, - } - der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &priv.PublicKey, priv) - if err != nil { - t.Fatalf("create certificate: %v", err) - } - keyDER, err := x509.MarshalECPrivateKey(priv) - if err != nil { - t.Fatalf("marshal key: %v", err) - } - certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}) - keyPEM := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER}) - cert, err := tls.X509KeyPair(certPEM, keyPEM) - if err != nil { - t.Fatalf("build key pair: %v", err) - } - return cert -} - -// waitForwarderSeesClose polls the forwarder's alive() status for up to 2 seconds, -// returning true if it detects a closed connection within that time. -// This replaces fixed sleeps when waiting for a collector close to reach the socket. -func waitForwarderSeesClose(t *testing.T, f *forwarder) bool { - t.Helper() - deadline := time.Now().Add(2 * time.Second) - for { - f.mu.Lock() - ok := f.alive() - f.mu.Unlock() - if !ok { - return true // Close detected - } - if time.Now().After(deadline) { - return false // Timeout - } - time.Sleep(time.Millisecond) // Small poll interval - } -} - -func TestBuildSyslog(t *testing.T) { - ts := time.Date(2026, 6, 30, 12, 0, 0, 0, time.UTC) - got := buildSyslog(16*8+6, ts, "host1", "gameplane-audit", `{"actor":"alice"}`) - want := `<134>1 2026-06-30T12:00:00.000Z host1 gameplane-audit - - - {"actor":"alice"}` - if got != want { - t.Errorf("buildSyslog =\n %q\nwant\n %q", got, want) - } -} - -func TestBuildSyslog_DefaultsAndSingleLine(t *testing.T) { - ts := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) - got := buildSyslog(13, ts, "", "", "line1\nline2\rline3") - // Empty host/app become "-"; embedded newlines/CRs collapse to spaces. - want := `<13>1 2026-01-02T03:04:05.000Z - - - - - line1 line2 line3` - if got != want { - t.Errorf("buildSyslog =\n %q\nwant\n %q", got, want) - } -} - -func TestFrameFor(t *testing.T) { - msg := "<134>1 ... hello" - if got := string(frameFor("tcp", msg)); got != strconv.Itoa(len(msg))+" "+msg { - t.Errorf("tcp frame = %q", got) - } - if got := string(frameFor("udp", msg)); got != msg { - t.Errorf("udp frame = %q", got) - } -} - -func TestNewServer_Validation(t *testing.T) { - base := func() config { - return config{ - syslogAddr: "127.0.0.1:514", network: "tcp", - appName: "x", facility: "local0", severity: "info", - dialTimeout: time.Second, - } - } - t.Run("ok computes pri", func(t *testing.T) { - s, err := newServer(base()) - if err != nil { - t.Fatalf("newServer: %v", err) - } - if s.pri != 16*8+6 { // local0(16), info(6) - t.Errorf("pri = %d, want %d", s.pri, 16*8+6) - } - }) - t.Run("missing addr", func(t *testing.T) { - c := base() - c.syslogAddr = "" - if _, err := newServer(c); err == nil { - t.Error("want error for missing syslog addr") - } - }) - t.Run("bad network", func(t *testing.T) { - c := base() - c.network = "sctp" - if _, err := newServer(c); err == nil { - t.Error("want error for bad network") - } - }) - t.Run("tls requires tcp", func(t *testing.T) { - c := base() - c.network = "udp" - c.useTLS = true - if _, err := newServer(c); err == nil { - t.Error("want error for tls over udp") - } - }) - t.Run("bad facility", func(t *testing.T) { - c := base() - c.facility = "nope" - if _, err := newServer(c); err == nil { - t.Error("want error for bad facility") - } - }) - t.Run("bad severity", func(t *testing.T) { - c := base() - c.severity = "nope" - if _, err := newServer(c); err == nil { - t.Error("want error for bad severity") - } - }) - t.Run("app name with space rejected", func(t *testing.T) { - c := base() - c.appName = "gameplane audit" - if _, err := newServer(c); err == nil { - t.Error("want error for APP_NAME containing a space") - } - }) - t.Run("app name too long rejected", func(t *testing.T) { - c := base() - c.appName = strings.Repeat("a", 49) - if _, err := newServer(c); err == nil { - t.Error("want error for APP_NAME over 48 bytes") - } - }) - t.Run("app name at max length ok", func(t *testing.T) { - c := base() - c.appName = strings.Repeat("a", 48) - if _, err := newServer(c); err != nil { - t.Errorf("newServer: %v", err) - } - }) - t.Run("empty hostname ok", func(t *testing.T) { - c := base() - c.hostname = "" - if _, err := newServer(c); err != nil { - t.Errorf("newServer: %v", err) - } - }) - t.Run("empty app name ok (renders as -)", func(t *testing.T) { - c := base() - c.appName = "" - if _, err := newServer(c); err != nil { - t.Errorf("newServer: %v", err) - } - }) - t.Run("hostname with space rejected", func(t *testing.T) { - c := base() - c.hostname = "my host" - if _, err := newServer(c); err == nil { - t.Error("want error for SYSLOG_HOSTNAME containing a space") - } - }) - t.Run("hostname too long rejected", func(t *testing.T) { - c := base() - c.hostname = strings.Repeat("h", 256) - if _, err := newServer(c); err == nil { - t.Error("want error for SYSLOG_HOSTNAME over 255 bytes") - } - }) - t.Run("hostname with non-printable rejected", func(t *testing.T) { - c := base() - c.hostname = "host\x01name" - if _, err := newServer(c); err == nil { - t.Error("want error for SYSLOG_HOSTNAME containing a non-printable byte") - } - }) -} - -// tcpSyslogSink starts a one-shot TCP listener that returns the first frame it -// reads. Returns its address and a channel delivering the received bytes. -func tcpSyslogSink(t *testing.T) (string, <-chan string) { - t.Helper() - lc := &net.ListenConfig{} - ln, err := lc.Listen(context.Background(), "tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("listen: %v", err) - } - got := make(chan string, 1) - go func() { - defer ln.Close() - conn, err := ln.Accept() - if err != nil { - return - } - defer conn.Close() - buf := make([]byte, 4096) - n, _ := conn.Read(buf) - got <- string(buf[:n]) - }() - return ln.Addr().String(), got -} - -func TestHandle_ForwardsToTCPSyslog(t *testing.T) { - addr, got := tcpSyslogSink(t) - s, err := newServer(config{ - syslogAddr: addr, network: "tcp", appName: "gameplane-audit", - facility: "local0", severity: "info", hostname: "h", dialTimeout: 2 * time.Second, - }) - if err != nil { - t.Fatalf("newServer: %v", err) - } - - srv := httptest.NewServer(s.routes()) - defer srv.Close() - - body := strings.NewReader(`{"actor":"admin","path":"/api/v1/servers"}`) - req, err := http.NewRequestWithContext(context.Background(), http.MethodPost, srv.URL+"/", body) - if err != nil { - t.Fatalf("new request: %v", err) - } - req.Header.Set("Content-Type", "application/json") - resp, err := http.DefaultClient.Do(req) - if err != nil { - t.Fatalf("post: %v", err) - } - defer resp.Body.Close() - if resp.StatusCode != http.StatusNoContent { - t.Fatalf("status = %d, want 204", resp.StatusCode) - } - - select { - case frame := <-got: - // Octet-counting prefix, RFC 5424 header, and the JSON payload. - if !strings.Contains(frame, "<134>1 ") { - t.Errorf("missing PRI/version header: %q", frame) - } - if !strings.Contains(frame, "gameplane-audit") { - t.Errorf("missing app-name: %q", frame) - } - if !strings.Contains(frame, `{"actor":"admin","path":"/api/v1/servers"}`) { - t.Errorf("missing JSON payload: %q", frame) - } - prefix := frame[:strings.IndexByte(frame, ' ')] - if _, err := strconv.Atoi(prefix); err != nil { - t.Errorf("octet-count prefix not numeric: %q", prefix) - } - case <-time.After(2 * time.Second): - t.Fatal("syslog sink received nothing") - } -} - -func TestHandle_ForwardsToUDPSyslog(t *testing.T) { - lc := &net.ListenConfig{} - pc, err := lc.ListenPacket(context.Background(), "udp", "127.0.0.1:0") - if err != nil { - t.Fatalf("listen udp: %v", err) - } - defer pc.Close() - got := make(chan string, 1) - go func() { - buf := make([]byte, 4096) - n, _, err := pc.ReadFrom(buf) - if err == nil { - got <- string(buf[:n]) - } - }() - - s, err := newServer(config{ - syslogAddr: pc.LocalAddr().String(), network: "udp", appName: "gp", - facility: "local0", severity: "info", hostname: "h", dialTimeout: 2 * time.Second, - }) - if err != nil { - t.Fatalf("newServer: %v", err) - } - rr := httptest.NewRecorder() - req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/", strings.NewReader(`{"k":"v"}`)) - s.handle(rr, req) - if rr.Code != http.StatusNoContent { - t.Fatalf("status = %d, want 204", rr.Code) - } - select { - case msg := <-got: - // UDP carries the bare message (no octet-count prefix). - if !strings.HasPrefix(msg, "<134>1 ") || !strings.Contains(msg, `{"k":"v"}`) { - t.Errorf("udp message = %q", msg) - } - case <-time.After(2 * time.Second): - t.Fatal("udp sink received nothing") - } -} - -func TestHandle_AuthRequired(t *testing.T) { - s := &server{authHeader: "Bearer secret", network: "tcp", fwd: newForwarder("tcp", "127.0.0.1:1", false, time.Second)} - - t.Run("missing token", func(t *testing.T) { - rr := httptest.NewRecorder() - req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/", strings.NewReader(`{}`)) - s.handle(rr, req) - if rr.Code != http.StatusUnauthorized { - t.Errorf("status = %d, want 401", rr.Code) - } - }) - t.Run("wrong token", func(t *testing.T) { - rr := httptest.NewRecorder() - req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/", strings.NewReader(`{}`)) - req.Header.Set("Authorization", "Bearer nope") - s.handle(rr, req) - if rr.Code != http.StatusUnauthorized { - t.Errorf("status = %d, want 401", rr.Code) - } - }) -} - -func TestHandle_MethodAndBody(t *testing.T) { - s := &server{network: "tcp", fwd: newForwarder("tcp", "127.0.0.1:1", false, time.Second)} - - t.Run("GET rejected", func(t *testing.T) { - rr := httptest.NewRecorder() - s.handle(rr, httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/", nil)) - if rr.Code != http.StatusMethodNotAllowed { - t.Errorf("status = %d, want 405", rr.Code) - } - }) - t.Run("empty body", func(t *testing.T) { - rr := httptest.NewRecorder() - s.handle(rr, httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/", strings.NewReader(" "))) - if rr.Code != http.StatusBadRequest { - t.Errorf("status = %d, want 400", rr.Code) - } - }) -} - -func TestHandle_ForwardFailureIs502(t *testing.T) { - // Point at a closed port so the dial fails. - s := &server{network: "tcp", appName: "x", hostname: "h", - fwd: newForwarder("tcp", "127.0.0.1:1", false, 200*time.Millisecond)} - rr := httptest.NewRecorder() - s.handle(rr, httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/", strings.NewReader(`{"k":"v"}`))) - if rr.Code != http.StatusBadGateway { - t.Errorf("status = %d, want 502", rr.Code) - } -} - -func TestForwarder_ReusesConnection(t *testing.T) { - lc := &net.ListenConfig{} - ln, err := lc.Listen(context.Background(), "tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("listen: %v", err) - } - defer ln.Close() - - // Accept exactly one connection and accumulate everything read on it. Both - // sends must arrive on this same connection — if the forwarder opened a - // second one for "two", it would sit unaccepted and the test would time out, - // so this proves connection reuse. Accumulating (rather than counting reads) - // is robust to TCP coalescing "one"+"two" into a single Read. - got := make(chan string, 1) - go func() { - conn, err := ln.Accept() - if err != nil { - return - } - defer conn.Close() - var acc []byte - tmp := make([]byte, 256) - for { - n, err := conn.Read(tmp) - acc = append(acc, tmp[:n]...) - if strings.Contains(string(acc), "one") && strings.Contains(string(acc), "two") { - got <- string(acc) - return - } - if err != nil { - return - } - } - }() - - f := newForwarder("tcp", ln.Addr().String(), false, time.Second) - if err := f.send(context.Background(), []byte("one")); err != nil { - t.Fatalf("send one: %v", err) - } - if err := f.send(context.Background(), []byte("two")); err != nil { - t.Fatalf("send two: %v", err) - } - select { - case s := <-got: - if !strings.Contains(s, "one") || !strings.Contains(s, "two") { - t.Errorf("received %q, want both frames", s) - } - case <-time.After(2 * time.Second): - t.Fatal("did not receive both frames on a reused connection") - } -} - -// TestForwarder_ReconnectsAfterWriteFailure exercises the redial-and-retry -// branch in forwarder.send: a write that fails on the held connection must -// close it, dial a fresh one, and retry the same frame. -func TestForwarder_ReconnectsAfterWriteFailure(t *testing.T) { - lc := &net.ListenConfig{} - ln, err := lc.Listen(context.Background(), "tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("listen: %v", err) - } - defer ln.Close() - - type accepted struct { - n int - data string - } - acceptCh := make(chan accepted, 2) - go func() { - for i := 0; i < 2; i++ { - conn, err := ln.Accept() - if err != nil { - return - } - // Bound the read so a missing frame can't park this goroutine. - _ = conn.SetReadDeadline(time.Now().Add(5 * time.Second)) - buf := make([]byte, 256) - n, _ := conn.Read(buf) - acceptCh <- accepted{n: i + 1, data: string(buf[:n])} - // Leave the connection open; the client side (not this accepted - // conn) is what gets force-closed to simulate the dead link. - defer conn.Close() - } - }() - - f := newForwarder("tcp", ln.Addr().String(), false, time.Second) - if err := f.send(context.Background(), []byte("one")); err != nil { - t.Fatalf("send one: %v", err) - } - select { - case got := <-acceptCh: - if got.n != 1 || got.data != "one" { - t.Fatalf("first accept = %+v, want frame \"one\"", got) - } - case <-time.After(2 * time.Second): - t.Fatal("first connection never received \"one\"") - } - - // Force the held connection dead from the client side, so the next send - // must observe a write failure and go through dial+retry. - f.mu.Lock() - _ = f.conn.Close() - f.mu.Unlock() - - if err := f.send(context.Background(), []byte("two")); err != nil { - t.Fatalf("send two (post-reconnect): %v", err) - } - select { - case got := <-acceptCh: - if got.n != 2 || got.data != "two" { - t.Fatalf("second accept = %+v, want a fresh connection carrying \"two\"", got) - } - case <-time.After(2 * time.Second): - t.Fatal("forwarder did not reconnect and deliver \"two\" on a new connection") - } -} - -// TestForwarder_WriteDeadlineExceeded exercises the deadline set in -// forwarder.write: a collector that accepts the connection but never drains -// it must make Write fail once dialTimeout elapses, instead of blocking -// forever. -// -// The forwarder dials lazily inside send, so the test must not wait for an -// Accept before calling send. A background loop accepts (and holds, unread) -// every connection until cleanup closes the listener and the held conns, and -// send runs in its own goroutine so every wait is bounded by a timer. -func TestForwarder_WriteDeadlineExceeded(t *testing.T) { - lc := &net.ListenConfig{} - ln, err := lc.Listen(context.Background(), "tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("listen: %v", err) - } - - var ( - heldMu sync.Mutex - held []net.Conn - ) - acceptDone := make(chan struct{}) - go func() { - defer close(acceptDone) - for { - conn, err := ln.Accept() - if err != nil { - return // listener closed by cleanup - } - // Deliberately never Read: the kernel buffers fill and the - // forwarder's Write blocks until its deadline fires. - heldMu.Lock() - held = append(held, conn) - heldMu.Unlock() - } - }() - t.Cleanup(func() { - _ = ln.Close() - select { - case <-acceptDone: - case <-time.After(5 * time.Second): - t.Error("accept loop did not exit after listener close") - } - heldMu.Lock() - for _, c := range held { - _ = c.Close() - } - heldMu.Unlock() - }) - - f := newForwarder("tcp", ln.Addr().String(), false, 200*time.Millisecond) - // Far larger than loopback send+receive socket buffers combined, so the - // write cannot complete while the peer never reads. - frame := make([]byte, 64<<20) - - errCh := make(chan error, 1) - start := time.Now() - go func() { errCh <- f.send(context.Background(), frame) }() - - select { - case err = <-errCh: - case <-time.After(10 * time.Second): - t.Fatal("send did not return; write deadline was not enforced") - } - elapsed := time.Since(start) - if err == nil { - t.Fatal("want a write-deadline error, got nil") - } - var nerr net.Error - if !errors.Is(err, os.ErrDeadlineExceeded) && (!errors.As(err, &nerr) || !nerr.Timeout()) { - t.Errorf("err = %v, want a deadline-exceeded / timeout error", err) - } - if elapsed > 5*time.Second { - t.Errorf("send took %s, want it bounded by the ~200ms write deadline (x2 for the retry)", elapsed) - } -} - -func TestHealthz(t *testing.T) { - s := &server{network: "tcp", fwd: newForwarder("tcp", "127.0.0.1:1", false, time.Second)} - rr := httptest.NewRecorder() - s.routes().ServeHTTP(rr, httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/healthz", nil)) - if rr.Code != http.StatusOK { - t.Fatalf("healthz status = %d", rr.Code) - } - b, _ := io.ReadAll(rr.Body) - if string(b) != "ok" { - t.Errorf("healthz body = %q", b) - } -} - -func TestEnvOr(t *testing.T) { - t.Setenv("BRIDGE_TEST_KEY", "set") - if got := envOr("BRIDGE_TEST_KEY", "fallback"); got != "set" { - t.Errorf("envOr set = %q", got) - } - if got := envOr("BRIDGE_TEST_UNSET_KEY", "fallback"); got != "fallback" { - t.Errorf("envOr unset = %q", got) - } -} - -func TestServe_ConfigError(t *testing.T) { - // Empty syslog addr fails validation before any listener is opened. - if err := serve(context.Background(), config{network: "tcp", facility: "local0", severity: "info"}); err == nil { - t.Fatal("want error for missing syslog addr") - } -} - -func TestServe_ShutsDownOnContextCancel(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - cfg := config{ - listen: "127.0.0.1:0", syslogAddr: "127.0.0.1:9", network: "tcp", - appName: "x", facility: "local0", severity: "info", dialTimeout: time.Second, - } - done := make(chan error, 1) - go func() { done <- serve(ctx, cfg) }() - - // Give ListenAndServe a moment to bind, then trigger graceful shutdown. - time.Sleep(100 * time.Millisecond) - cancel() - select { - case err := <-done: - if err != nil { - t.Fatalf("serve returned %v, want nil on clean shutdown", err) - } - case <-time.After(3 * time.Second): - t.Fatal("serve did not return after context cancel") - } -} - -func TestLoadConfig_Defaults(t *testing.T) { - for _, k := range []string{ - "LISTEN_ADDR", "SYSLOG_ADDR", "SYSLOG_NETWORK", "SYSLOG_TLS", - "APP_NAME", "FACILITY", "SEVERITY", "SYSLOG_HOSTNAME", "AUTH_HEADER", - } { - // t.Setenv registers restoration of the prior value; immediately - // unsetting then exercises the "env absent → fallback" path. - t.Setenv(k, "") - if err := os.Unsetenv(k); err != nil { - t.Fatalf("unset %s: %v", k, err) - } - } - cfg := loadConfig() - if cfg.listen != ":8514" || cfg.network != "tcp" || cfg.appName != "gameplane-audit" || - cfg.facility != "local0" || cfg.severity != "info" { - t.Errorf("unexpected defaults: %+v", cfg) - } -} - -func TestFallbackHostname(t *testing.T) { - cases := []struct { - name string - lookup func() (string, error) - want string - }{ - {"valid OS hostname kept", func() (string, error) { return "node-1", nil }, "node-1"}, - {"hostname with space dropped", func() (string, error) { return "my host", nil }, ""}, - {"non-ASCII hostname dropped", func() (string, error) { return "hôte", nil }, ""}, - {"too long hostname dropped", func() (string, error) { return strings.Repeat("h", 256), nil }, ""}, - {"lookup error dropped", func() (string, error) { return "", errors.New("no hostname") }, ""}, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - if got := fallbackHostname(tc.lookup); got != tc.want { - t.Errorf("fallbackHostname = %q, want %q", got, tc.want) - } - }) - } -} - -// A record sent after the collector has closed the reused connection is -// delivered on a fresh connection, not written to the closed one. -func TestForwarder_RecordAfterCollectorCloseReachesNewConnection(t *testing.T) { - lc := &net.ListenConfig{} - ln, err := lc.Listen(context.Background(), "tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("listen: %v", err) - } - defer ln.Close() - - firstClosed := make(chan struct{}) - second := make(chan string, 1) - go func() { - // Connection 1: read one frame, then close it, as a collector that - // reaps idle connections does. - c1, err := ln.Accept() - if err != nil { - return - } - buf := make([]byte, 256) - _, _ = c1.Read(buf) - _ = c1.Close() - close(firstClosed) - - // Connection 2: accumulate everything read until "two" arrives. - c2, err := ln.Accept() - if err != nil { - return - } - defer c2.Close() - var acc []byte - for { - n, err := c2.Read(buf) - acc = append(acc, buf[:n]...) - if strings.Contains(string(acc), "two") { - second <- string(acc) - return - } - if err != nil { - return - } - } - }() - - f := newForwarder("tcp", ln.Addr().String(), false, time.Second) - if err := f.send(context.Background(), []byte("one")); err != nil { - t.Fatalf("send one: %v", err) - } - select { - case <-firstClosed: - case <-time.After(2 * time.Second): - t.Fatal("collector did not receive the first frame") - } - // Wait for the collector's close to reach the forwarder's socket. - if !waitForwarderSeesClose(t, f) { - t.Fatal("collector close did not reach the forwarder within 2s") - } - - if err := f.send(context.Background(), []byte("two")); err != nil { - t.Fatalf("send two: %v", err) - } - select { - case got := <-second: - if !strings.Contains(got, "two") { - t.Errorf("new connection received %q, want the second frame", got) - } - case <-time.After(2 * time.Second): - t.Fatal("the record sent after the collector closed its connection did not reach a new connection") - } -} - -// The same reconnect-after-close path exercises the TLS dial branch, not just -// plain TCP: a record sent after the collector closes a reused TLS connection -// still reaches a fresh TLS connection rather than being silently lost. -func TestForwarder_TLSRecordAfterCollectorCloseReachesNewConnection(t *testing.T) { - cert := generateTestTLSCert(t) - pool := x509.NewCertPool() - leaf, err := x509.ParseCertificate(cert.Certificate[0]) - if err != nil { - t.Fatalf("parse leaf certificate: %v", err) - } - pool.AddCert(leaf) - - lc := &net.ListenConfig{} - rawLn, err := lc.Listen(context.Background(), "tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("listen: %v", err) - } - ln := tls.NewListener(rawLn, &tls.Config{Certificates: []tls.Certificate{cert}, MinVersion: tls.VersionTLS12}) - defer ln.Close() - - firstClosed := make(chan struct{}) - second := make(chan string, 1) - go func() { - // Connection 1: read one frame, then close it, as a collector that - // reaps idle connections does. - c1, err := ln.Accept() - if err != nil { - return - } - buf := make([]byte, 256) - _, _ = c1.Read(buf) - _ = c1.Close() - close(firstClosed) - - // Connection 2: accumulate everything read until "two" arrives. - c2, err := ln.Accept() - if err != nil { - return - } - defer c2.Close() - var acc []byte - for { - n, err := c2.Read(buf) - acc = append(acc, buf[:n]...) - if strings.Contains(string(acc), "two") { - second <- string(acc) - return - } - if err != nil { - return - } - } - }() - - f := newForwarder("tcp", rawLn.Addr().String(), true, time.Second) - f.tlsConfig = &tls.Config{RootCAs: pool, ServerName: "127.0.0.1", MinVersion: tls.VersionTLS12} - if err := f.send(context.Background(), []byte("one")); err != nil { - t.Fatalf("send one: %v", err) - } - select { - case <-firstClosed: - case <-time.After(2 * time.Second): - t.Fatal("collector did not receive the first frame") - } - // Wait for the collector's close to reach the forwarder's socket. - if !waitForwarderSeesClose(t, f) { - t.Fatal("collector close did not reach the forwarder within 2s") - } - - if err := f.send(context.Background(), []byte("two")); err != nil { - t.Fatalf("send two: %v", err) - } - select { - case got := <-second: - if !strings.Contains(got, "two") { - t.Errorf("new connection received %q, want the second frame", got) - } - case <-time.After(2 * time.Second): - t.Fatal("the record sent after the collector closed its TLS connection did not reach a new connection") - } -} - -// When the collector has closed the connection and is no longer reachable, the -// next POST is answered with 502 rather than reported as delivered. -func TestHandle_CollectorGoneAfterCloseIs502(t *testing.T) { - lc := &net.ListenConfig{} - ln, err := lc.Listen(context.Background(), "tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("listen: %v", err) - } - defer ln.Close() - - gone := make(chan struct{}) - go func() { - c, err := ln.Accept() - if err != nil { - return - } - buf := make([]byte, 4096) - _, _ = c.Read(buf) - // The collector goes away: its connection and its listener both close. - _ = c.Close() - _ = ln.Close() - close(gone) - }() - - s, err := newServer(config{ - syslogAddr: ln.Addr().String(), network: "tcp", appName: "gp", - facility: "local0", severity: "info", hostname: "h", dialTimeout: time.Second, - }) - if err != nil { - t.Fatalf("newServer: %v", err) - } - - post := func() int { - rr := httptest.NewRecorder() - s.handle(rr, httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/", strings.NewReader(`{"k":"v"}`))) - return rr.Code - } - - if code := post(); code != http.StatusNoContent { - t.Fatalf("first POST status = %d, want 204", code) - } - select { - case <-gone: - case <-time.After(2 * time.Second): - t.Fatal("collector did not receive the first record") - } - // Wait for the collector's close to reach the forwarder's socket. - if !waitForwarderSeesClose(t, s.fwd) { - t.Fatal("collector close did not reach the forwarder within 2s") - } - - if code := post(); code != http.StatusBadGateway { - t.Fatalf("POST after the collector went away: status = %d, want 502", code) - } -} - -// A request whose body does not arrive within the read bound is closed by the -// server instead of holding the connection open. -func TestIntake_BodyReadIsTimeBounded(t *testing.T) { - s := &server{network: "tcp", fwd: newForwarder("tcp", "127.0.0.1:1", false, time.Second)} - - lc := &net.ListenConfig{} - ln, err := lc.Listen(context.Background(), "tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("listen: %v", err) - } - srv := newHTTPServer(config{readTimeout: 300 * time.Millisecond}, s.routes()) - go func() { _ = srv.Serve(ln) }() - defer srv.Close() - - d := &net.Dialer{Timeout: time.Second} - conn, err := d.DialContext(context.Background(), "tcp", ln.Addr().String()) - if err != nil { - t.Fatalf("dial: %v", err) - } - defer conn.Close() - - start := time.Now() - // Complete headers announcing a body, then no body at all. - if _, err := io.WriteString(conn, - "POST / HTTP/1.1\r\nHost: bridge\r\nContent-Type: application/json\r\nContent-Length: 64\r\n\r\n"); err != nil { - t.Fatalf("write headers: %v", err) - } - _ = conn.SetReadDeadline(time.Now().Add(5 * time.Second)) - if _, err := io.ReadAll(conn); err != nil { - t.Fatalf("server did not close the connection within the read bound: %v", err) - } - if elapsed := time.Since(start); elapsed > time.Second { - t.Fatalf("connection closed after %v, want within 1s of the 300ms read timeout", elapsed) - } -} - -// TestForwarder_ManyHealthyReusedConnSends verifies that repeated sends over -// a single healthy reused connection complete quickly (verifying the fast path -// eliminates the 5ms penalty). With the old timed-read-only alive(), 1000 sends -// would need at least 5 seconds; with the fast path, it should complete in a -// fraction of a second. -func TestForwarder_ManyHealthyReusedConnSends(t *testing.T) { - lc := &net.ListenConfig{} - ln, err := lc.Listen(context.Background(), "tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("listen: %v", err) - } - defer ln.Close() - - // Collector that drains all sends without closing. - go func() { - for { - c, err := ln.Accept() - if err != nil { - return - } - go func(c net.Conn) { - defer c.Close() - buf := make([]byte, 4096) - for { - if _, err := c.Read(buf); err != nil { - return - } - } - }(c) - } - }() - - f := newForwarder("tcp", ln.Addr().String(), false, time.Second) - start := time.Now() - for i := 0; i < 1000; i++ { - if err := f.send(context.Background(), []byte("x")); err != nil { - t.Fatalf("send %d: %v", i, err) - } - } - elapsed := time.Since(start) - - // With the old code (5ms per send * 1000), this would be >= 5s. - // With the fast path, it should be well under 1s. - if elapsed > 2*time.Second { - t.Errorf("1000 sends took %v, expected < 2s (old code would need >= 5s)", elapsed) - } -} - -// The intake server bounds the header phase, the whole request and keep-alive -// idle time, and a zero read bound falls back to the default. -func TestNewHTTPServer_BoundsEveryPhase(t *testing.T) { - if got := loadConfig().readTimeout; got != defaultReadTimeout { - t.Errorf("default readTimeout = %v, want %v", got, defaultReadTimeout) - } - srv := newHTTPServer(config{listen: "127.0.0.1:0"}, http.NewServeMux()) - if srv.ReadTimeout != defaultReadTimeout { - t.Errorf("ReadTimeout = %v, want %v", srv.ReadTimeout, defaultReadTimeout) - } - if srv.ReadHeaderTimeout != headerReadTimeout { - t.Errorf("ReadHeaderTimeout = %v, want %v", srv.ReadHeaderTimeout, headerReadTimeout) - } - if srv.IdleTimeout != idleTimeout { - t.Errorf("IdleTimeout = %v, want %v", srv.IdleTimeout, idleTimeout) - } - short := newHTTPServer(config{readTimeout: time.Second}, http.NewServeMux()) - if short.ReadHeaderTimeout != time.Second || short.ReadTimeout != time.Second { - t.Errorf("short bound: header=%v read=%v, want 1s for both", short.ReadHeaderTimeout, short.ReadTimeout) - } -} diff --git a/audit-syslog-bridge/go.mod b/audit-syslog-bridge/go.mod deleted file mode 100644 index e9020ea30..000000000 --- a/audit-syslog-bridge/go.mod +++ /dev/null @@ -1,3 +0,0 @@ -module github.com/GameplanePanel/gameplane/audit-syslog-bridge - -go 1.27.0 diff --git a/audit-syslog-bridge/main.go b/audit-syslog-bridge/main.go deleted file mode 100644 index 08e0681eb..000000000 --- a/audit-syslog-bridge/main.go +++ /dev/null @@ -1,460 +0,0 @@ -// Command audit-syslog-bridge is a tiny, generic HTTP-JSON → syslog relay. It -// accepts an HTTP POST whose body is a single JSON document and re-emits that -// document as an RFC 5424 syslog message to a configured collector (TCP, TCP -// over TLS, or UDP). -// -// It exists so Gameplane's audit webhook sink (which POSTs each audit event as -// JSON) can reach a syslog/SIEM endpoint, but it is deliberately -// schema-agnostic: it forwards the received body verbatim as the syslog MSG, so -// it works for any JSON webhook source, not just audit events. -package main - -import ( - "context" - "crypto/subtle" - "crypto/tls" - "errors" - "fmt" - "io" - "log/slog" - "net" - "net/http" - "os" - "os/signal" - "strconv" - "strings" - "sync" - "syscall" - "time" -) - -// RFC 5424 facility and severity name → numeric maps. PRI = facility*8 + severity. -var facilities = map[string]int{ - "kern": 0, "user": 1, "mail": 2, "daemon": 3, "auth": 4, "syslog": 5, - "lpr": 6, "news": 7, "uucp": 8, "cron": 9, "authpriv": 10, "ftp": 11, - "local0": 16, "local1": 17, "local2": 18, "local3": 19, - "local4": 20, "local5": 21, "local6": 22, "local7": 23, -} - -var severities = map[string]int{ - "emerg": 0, "alert": 1, "crit": 2, "err": 3, - "warning": 4, "notice": 5, "info": 6, "debug": 7, -} - -// Version is set at build time via -ldflags "-X main.Version=...". -var Version = "dev" - -// maxBody bounds the inbound POST body. Audit events are small; this just stops -// a misdirected client from streaming something huge at us. -const maxBody = 64 << 10 - -// RFC 5424 §6.2.3/§6.2.4 field-length limits for APP-NAME and HOSTNAME. -const ( - maxAppNameLen = 48 - maxHostnameLen = 255 -) - -// validateRFC5424Field rejects a value that can't legally sit in an RFC 5424 -// APP-NAME or HOSTNAME field: both are 1*maxLen PRINTUSASCII (%d33-126), a range -// that excludes space. A value containing a space or other non-printable -// character shifts every field after it once a collector splits the header on -// whitespace; an empty value is left alone here since it resolves to "-". -func validateRFC5424Field(name, value string, maxLen int) error { - if value == "" { - return nil - } - if len(value) > maxLen { - return fmt.Errorf("%s %q is %d bytes, want at most %d", name, value, len(value), maxLen) - } - for _, r := range value { - if r < 33 || r > 126 { - return fmt.Errorf("%s %q contains %q, want only RFC 5424 PRINTUSASCII (33-126)", name, value, r) - } - } - return nil -} - -// Intake time bounds. defaultReadTimeout caps how long one request (headers and -// body) may take to arrive; headerReadTimeout caps the header phase on its own; -// idleTimeout closes keep-alive connections that sit unused between requests. -// idleTimeout is longer than Go's default client idle timeout (90s), so a Go -// sender such as the API retires an idle connection before the bridge does. -const ( - defaultReadTimeout = 15 * time.Second - headerReadTimeout = 10 * time.Second - idleTimeout = 120 * time.Second -) - -// peekState values returned by peek(). -type peekState int - -const ( - peekUnknown peekState = iota - peekEmpty - peekClosed - peekPending -) - -// livenessProbe is how long send waits for a pending close from the collector -// before it reuses a stream connection. Collectors never write to a syslog -// stream, so a read that times out means the connection is still open. -const livenessProbe = 5 * time.Millisecond - -type config struct { - listen string - syslogAddr string - network string // tcp | udp - useTLS bool - appName string - facility string - severity string - hostname string - authHeader string - dialTimeout time.Duration - readTimeout time.Duration -} - -func loadConfig() config { - return config{ - listen: envOr("LISTEN_ADDR", ":8514"), - syslogAddr: envOr("SYSLOG_ADDR", ""), - network: envOr("SYSLOG_NETWORK", "tcp"), - useTLS: envOr("SYSLOG_TLS", "") == "true", - appName: envOr("APP_NAME", "gameplane-audit"), - facility: envOr("FACILITY", "local0"), - severity: envOr("SEVERITY", "info"), - hostname: envOr("SYSLOG_HOSTNAME", ""), - authHeader: envOr("AUTH_HEADER", ""), - dialTimeout: 5 * time.Second, - readTimeout: defaultReadTimeout, - } -} - -func envOr(key, fallback string) string { - if v, ok := os.LookupEnv(key); ok { - return v - } - return fallback -} - -// fallbackHostname returns the OS hostname for the RFC 5424 HOSTNAME field -// when SYSLOG_HOSTNAME is unset. A lookup error or a hostname that fails -// validateRFC5424Field yields "" instead, which the formatter renders as the -// nil value "-", so an unusual OS hostname can't shift the header fields. -func fallbackHostname(lookup func() (string, error)) string { - h, err := lookup() - if err != nil || validateRFC5424Field("hostname", h, maxHostnameLen) != nil { - return "" - } - return h -} - -// server holds the resolved relay configuration and the syslog forwarder. -type server struct { - pri int - appName string - hostname string - network string - authHeader string - fwd *forwarder -} - -func newServer(cfg config) (*server, error) { - if cfg.syslogAddr == "" { - return nil, errors.New("SYSLOG_ADDR (-syslog-addr) is required") - } - if cfg.network != "tcp" && cfg.network != "udp" { - return nil, fmt.Errorf("SYSLOG_NETWORK must be tcp or udp, got %q", cfg.network) - } - if cfg.useTLS && cfg.network != "tcp" { - return nil, errors.New("SYSLOG_TLS requires SYSLOG_NETWORK=tcp") - } - fac, ok := facilities[cfg.facility] - if !ok { - return nil, fmt.Errorf("unknown FACILITY %q", cfg.facility) - } - sev, ok := severities[cfg.severity] - if !ok { - return nil, fmt.Errorf("unknown SEVERITY %q", cfg.severity) - } - if err := validateRFC5424Field("APP_NAME", cfg.appName, maxAppNameLen); err != nil { - return nil, err - } - if err := validateRFC5424Field("SYSLOG_HOSTNAME", cfg.hostname, maxHostnameLen); err != nil { - return nil, err - } - host := cfg.hostname - if host == "" { - host = fallbackHostname(os.Hostname) - } - return &server{ - pri: fac*8 + sev, - appName: cfg.appName, - hostname: host, - network: cfg.network, - authHeader: cfg.authHeader, - fwd: newForwarder(cfg.network, cfg.syslogAddr, cfg.useTLS, cfg.dialTimeout), - }, nil -} - -func (s *server) routes() *http.ServeMux { - mux := http.NewServeMux() - mux.HandleFunc("/healthz", func(w http.ResponseWriter, _ *http.Request) { - _, _ = w.Write([]byte("ok")) - }) - mux.HandleFunc("/", s.handle) - return mux -} - -func (s *server) handle(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodPost { - http.Error(w, "method not allowed", http.StatusMethodNotAllowed) - return - } - if s.authHeader != "" && - subtle.ConstantTimeCompare([]byte(r.Header.Get("Authorization")), []byte(s.authHeader)) != 1 { - http.Error(w, "unauthorized", http.StatusUnauthorized) - return - } - body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxBody)) - if err != nil { - // Log the cause: without this an operator seeing the API's audit-webhook - // counter tick "failed" has nothing on the bridge side to explain the gap. - slog.Warn("read request body", "err", err) - http.Error(w, "read body", http.StatusBadRequest) - return - } - msg := strings.TrimSpace(string(body)) - if msg == "" { - http.Error(w, "empty body", http.StatusBadRequest) - return - } - line := buildSyslog(s.pri, time.Now(), s.hostname, s.appName, msg) - if err := s.fwd.send(r.Context(), frameFor(s.network, line)); err != nil { - slog.Error("forward to syslog failed", "err", err) - http.Error(w, "syslog forward failed", http.StatusBadGateway) - return - } - w.WriteHeader(http.StatusNoContent) -} - -// buildSyslog renders one RFC 5424 message: -// -// 1 TIMESTAMP HOSTNAME APP-NAME PROCID MSGID STRUCTURED-DATA MSG -// -// PROCID, MSGID and STRUCTURED-DATA are nil ("-"); MSG carries the JSON body -// collapsed to a single line so it stays one syslog record. -func buildSyslog(pri int, ts time.Time, host, app, msg string) string { - if host == "" { - host = "-" - } - if app == "" { - app = "-" - } - msg = strings.NewReplacer("\n", " ", "\r", " ").Replace(msg) - return fmt.Sprintf("<%d>1 %s %s %s - - - %s", - pri, ts.UTC().Format("2006-01-02T15:04:05.000Z07:00"), host, app, msg) -} - -// frameFor wraps a syslog message for the wire. TCP uses RFC 6587 -// octet-counting (" ") so a stream collector can split records -// unambiguously; UDP sends the bare message as one datagram. -func frameFor(network, msg string) []byte { - if network == "tcp" { - return []byte(strconv.Itoa(len(msg)) + " " + msg) - } - return []byte(msg) -} - -// forwarder ships framed syslog messages over a lazily-dialed, reused -// connection. Writes are serialized; a failed write triggers one reconnect and -// retry before surfacing the error. -type forwarder struct { - network string - addr string - useTLS bool - dialTimeout time.Duration - - // tlsConfig overrides the default client TLS config when set. Production - // code leaves it nil; tests use it to trust a self-signed test collector - // certificate instead of the system root pool. - tlsConfig *tls.Config - - mu sync.Mutex - conn net.Conn -} - -func newForwarder(network, addr string, useTLS bool, dialTimeout time.Duration) *forwarder { - return &forwarder{network: network, addr: addr, useTLS: useTLS, dialTimeout: dialTimeout} -} - -func (f *forwarder) dial(ctx context.Context) error { - var ( - c net.Conn - err error - ) - if f.useTLS && f.network == "tcp" { - cfg := f.tlsConfig - if cfg == nil { - cfg = &tls.Config{MinVersion: tls.VersionTLS12} - } - d := &tls.Dialer{NetDialer: &net.Dialer{Timeout: f.dialTimeout}, Config: cfg} - c, err = d.DialContext(ctx, "tcp", f.addr) - } else { - d := &net.Dialer{Timeout: f.dialTimeout} - c, err = d.DialContext(ctx, f.network, f.addr) - } - if err != nil { - return fmt.Errorf("dial %s/%s: %w", f.network, f.addr, err) - } - f.conn = c - return nil -} - -func (f *forwarder) send(ctx context.Context, frame []byte) error { - f.mu.Lock() - defer f.mu.Unlock() - if f.conn != nil && !f.alive() { - slog.Info("syslog collector closed the connection; reconnecting", - "network", f.network, "addr", f.addr) - _ = f.conn.Close() - f.conn = nil - } - if f.conn == nil { - if err := f.dial(ctx); err != nil { - return err - } - } - if err := f.write(frame); err != nil { - // The collector may have dropped a long-idle connection; reconnect once. - _ = f.conn.Close() - f.conn = nil - if err := f.dial(ctx); err != nil { - return err - } - if err := f.write(frame); err != nil { - _ = f.conn.Close() - f.conn = nil - return fmt.Errorf("write syslog %s/%s: %w", f.network, f.addr, err) - } - } - return nil -} - -// alive reports whether a reused stream connection is still open. When a -// collector closes an idle connection, its FIN (or RST) is already queued on -// the socket, and a write would still succeed locally while the frame is lost. -// A short read surfaces that close first, so send moves the frame to a fresh -// connection. Datagram connections have no such state and are always reused. -// -// The probe is best-effort, not a delivery guarantee: a close that has not -// reached the socket within livenessProbe goes unseen, and the next frame can -// be lost while send reports success (204). Syslog framing has no ack, so this -// window cannot be closed without a different transport protocol. -// -// On Linux, alive first attempts a zero-wait peek to avoid the 5ms blocking -// read on every healthy reused connection; only if the peek is inconclusive -// does it fall back to the timed read. -// -// Pending data (peekPending) is deliberately not treated as proof the -// connection is open: on TLS a collector close first queues a close_notify -// alert record ahead of the FIN, so the raw socket looks readable. Falling -// through to the timed read on f.conn lets crypto/tls consume the alert and -// return io.EOF, which reports the connection as closed. -func (f *forwarder) alive() bool { - if f.network != "tcp" { - return true - } - - // Fast path on Linux: non-blocking peek avoids the 5ms blocking read. - switch peek(f.conn) { - case peekEmpty: - return true - case peekClosed: - return false - } - - // Inconclusive or non-Linux: fall back to timed read. - var one [1]byte - _ = f.conn.SetReadDeadline(time.Now().Add(livenessProbe)) - _, err := f.conn.Read(one[:]) - _ = f.conn.SetReadDeadline(time.Time{}) - if err == nil { - // The collector sent something unexpected; the connection is open. - return true - } - var ne net.Error - return errors.As(err, &ne) && ne.Timeout() -} - -// write bounds a single frame write with a deadline. Without it, a collector -// that accepts the TCP connection but stops draining it would block Write -// forever while holding f.mu, wedging every subsequent audit POST behind the -// mutex until the pod is restarted. -func (f *forwarder) write(frame []byte) error { - _ = f.conn.SetWriteDeadline(time.Now().Add(f.dialTimeout)) - _, err := f.conn.Write(frame) - return err -} - -// run wires OS signal handling to serve. main's thin wrapper; the testable -// lifecycle lives in serve. -func run(cfg config) error { - ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) - defer stop() - return serve(ctx, cfg) -} - -// serve builds the relay and runs the HTTP server until ctx is cancelled (then -// it drains with a 5s deadline) or ListenAndServe fails. -func serve(ctx context.Context, cfg config) error { - s, err := newServer(cfg) - if err != nil { - return err - } - srv := newHTTPServer(cfg, s.routes()) - slog.Info("audit-syslog-bridge listening", - "version", Version, "listen", cfg.listen, "syslog", cfg.syslogAddr, - "network", cfg.network, "tls", cfg.useTLS, "app", cfg.appName) - - errCh := make(chan error, 1) - go func() { - if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { - errCh <- err - } - close(errCh) - }() - - select { - case err := <-errCh: - return err - case <-ctx.Done(): - shutCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) - defer cancel() - return srv.Shutdown(shutCtx) - } -} - -// newHTTPServer builds the intake server with every phase of a request bounded -// in time: headers, the whole request (headers plus body), and keep-alive idle. -// A zero cfg.readTimeout falls back to defaultReadTimeout. -func newHTTPServer(cfg config, h http.Handler) *http.Server { - readTimeout := cfg.readTimeout - if readTimeout <= 0 { - readTimeout = defaultReadTimeout - } - return &http.Server{ - Addr: cfg.listen, - Handler: h, - ReadHeaderTimeout: min(headerReadTimeout, readTimeout), - ReadTimeout: readTimeout, - IdleTimeout: idleTimeout, - } -} - -func main() { - if err := run(loadConfig()); err != nil { - slog.Error("audit-syslog-bridge exited", "err", err) - os.Exit(1) - } -} diff --git a/audit-syslog-bridge/peek_linux.go b/audit-syslog-bridge/peek_linux.go deleted file mode 100644 index 0b8605202..000000000 --- a/audit-syslog-bridge/peek_linux.go +++ /dev/null @@ -1,67 +0,0 @@ -//go:build linux - -package main - -import ( - "crypto/tls" - "net" - "syscall" -) - -// peek performs a non-blocking socket peek to determine connection state. -// On Linux, uses MSG_PEEK|MSG_DONTWAIT to check for pending data or a close -// without blocking. -func peek(c net.Conn) peekState { - // Unwrap *tls.Conn to get the underlying net.Conn. - tc, ok := c.(*tls.Conn) - if ok { - c = tc.NetConn() - } - - // Get syscall.Conn to perform raw syscall reads. - sc, ok := c.(syscall.Conn) - if !ok { - return peekUnknown - } - - rc, err := sc.SyscallConn() - if err != nil { - return peekUnknown - } - - var ( - buf [1]byte - n int - err2 error - ) - rerr := rc.Read(func(fd uintptr) bool { - n, _, err2 = syscall.Recvfrom(int(fd), buf[:1], syscall.MSG_PEEK|syscall.MSG_DONTWAIT) - return true - }) - - if rerr != nil { - return peekUnknown - } - - if err2 != nil { - switch err2 { - case syscall.EAGAIN: - // No data pending; connection is open. (EWOULDBLOCK is an alias for EAGAIN on Linux) - return peekEmpty - case syscall.EINTR: - // Interrupted system call; inconclusive. - return peekUnknown - default: - // Any other error (ECONNRESET, EPIPE, etc.) indicates closure. - return peekClosed - } - } - - // n == 0 means a FIN was received (connection closed). - if n == 0 { - return peekClosed - } - - // n > 0 means data is pending. - return peekPending -} diff --git a/audit-syslog-bridge/peek_other.go b/audit-syslog-bridge/peek_other.go deleted file mode 100644 index 89943f0c9..000000000 --- a/audit-syslog-bridge/peek_other.go +++ /dev/null @@ -1,10 +0,0 @@ -//go:build !linux - -package main - -import "net" - -// peek is a stub on non-Linux platforms. -func peek(net.Conn) peekState { - return peekUnknown -} diff --git a/audit-syslog-bridge/specs.md b/audit-syslog-bridge/specs.md deleted file mode 100644 index a98d2aee7..000000000 --- a/audit-syslog-bridge/specs.md +++ /dev/null @@ -1,76 +0,0 @@ -# audit-syslog-bridge — Specification - -**Status:** pre-v1 (v0.4.0) -**Module / package:** `github.com/GameplanePanel/gameplane/audit-syslog-bridge` - -## Purpose - -Optional, schema-agnostic HTTP-JSON → RFC 5424 syslog relay. Sits behind the API's audit webhook sink (`api.audit.webhook.syslogBridge.enabled`) to forward audit events to a syslog/SIEM collector, but works for *any* JSON webhook source — nothing is Gameplane-specific. - -## Responsibilities - -- Listen on HTTP, accept `POST /` with a JSON body, forward it as one RFC 5424 syslog record -- Encode the received timestamp, hostname, app-name, and collapse the JSON body to a single-line MSG field -- Frame the message for the wire: RFC 6587 octet-counting (` `) for TCP (reliable stream framing), bare message for UDP (one datagram) -- Maintain a lazily-dialed, reused syslog connection; before reusing a TCP connection, check that the collector has not closed it and redial if it has; reconnect once on write error -- Bound each write with a deadline (default 5s) to prevent a hung collector from blocking the HTTP handler indefinitely -- Provide `/healthz` for Kubernetes probes -- Enforce optional bearer-token auth on POST / - -## Non-goals / boundaries - -NOT Gameplane-specific — forwards the received JSON body verbatim as the syslog MSG, so it does not parse or understand the Gameplane audit schema. Works equally well as a generic webhook-to-syslog relay for any source. See README.md for config/run instructions. - -## Directory & package layout - -Single flat package (`main`): `main.go` (relay + config + server logic), `bridge_test.go` (unit tests covering HTTP handler, syslog framing, config validation, TCP/UDP forwarding, auth, reconnection, write-deadline enforcement), `go.mod` (workspace-linked, stdlib-only), `Dockerfile`, `README.md`. - -## External interface / contracts - -**HTTP endpoints:** -- `POST /` — forward JSON body as syslog record - - Request: any Content-Type, JSON body up to 64 KiB - - Response: `204 No Content` (record written to collector connection; best effort, may be lost if collector closes concurrently); `400 Bad Request` if body empty/unreadable; `401 Unauthorized` if `AUTH_HEADER` is set and does not match; `405 Method Not Allowed` for GET/other; `502 Bad Gateway` if forward to collector fails -- `GET /healthz` — Kubernetes probe - - Response: `200 OK` with body "ok" - -**Transports:** -- TCP (RFC 6587 octet-counting framing): ` `, reliable for audit trails -- UDP: bare message, one datagram per record -- TLS: wraps TCP in verified TLS 1.2+; `SYSLOG_TLS=true` (requires `SYSLOG_NETWORK=tcp`) - -**Auth:** -- Optional bearer token: if `AUTH_HEADER` environment variable is set, the HTTP request `Authorization` header must match exactly (constant-time comparison); absence of the env var = any POST accepted - -## Key invariants - -- Forwards the received JSON body verbatim (schema-agnostic; does not parse, validate, or understand audit events) -- Prefers TCP over UDP for audit/compliance trails (UDP has no delivery confirmation; TCP surfaces a dead collector as a 502) -- Connection reuse: lazily dials once, then reuses; before each TCP write a short read probe (5 ms) checks whether the collector has closed the connection, and the bridge redials if it has; on write error, closes and reconnects once before surfacing the error. The probe is best-effort, not a delivery guarantee: a collector close whose FIN/RST lands after the probe goes unnoticed, and one record may then be written into the dead connection (reported as `204`: written to connection, best effort); the next write detects the close and reconnects, returning `204` on successful retry or `502` if the retry fails. Syslog framing has no acknowledgement, so this cannot be closed without a different transport -- Write deadline per frame (5s default) prevents a collector that accepts but does not drain from blocking indefinitely and wedging the handler behind the connection mutex -- RFC 5424 compliance: formats message as `1 TIMESTAMP HOSTNAME APP-NAME PROCID MSGID STRUCTURED-DATA MSG`; collapses embedded newlines/CRs to spaces so each syslog record is one line; PROCID, MSGID, STRUCTURED-DATA are "-" -- `APP_NAME` and `SYSLOG_HOSTNAME` are validated at startup the same way `FACILITY`/`SEVERITY` are: each must be 1*max PRINTUSASCII (RFC 5424 %d33-126, no spaces or control bytes), APP-NAME capped at 48 bytes and HOSTNAME at 255 bytes, or `newServer` rejects the config before the process starts serving. An empty value is accepted and rendered as the RFC 5424 nil value `-`; when `SYSLOG_HOSTNAME` is empty the OS hostname is used instead, and an OS hostname that fails the same check (or can't be read) falls back to `-` - -## Dependencies - -**Go 1.27** (workspace-linked to `go.work` alongside `operator/`, `api/`, `agent/`, etc.) - -**Imports:** stdlib only (`crypto/tls`, `net`, `net/http`, `log/slog`, `sync`, `time`, `context`, etc.). No external dependencies. - -## Security considerations - -- **Auth boundary:** optional bearer token (`AUTH_HEADER` env var) gates who may inject records (constant-time comparison; absence = open) -- **TLS transport:** `SYSLOG_TLS=true` wraps the TCP connection in verified TLS 1.2+, protecting audit events in transit -- **Trust boundary:** API ← audit-syslog-bridge ← SIEM/syslog collector. The API rate-limits webhook submissions; the bridge forwards verbatim and is stateless, so it does not amplify or replay events -- **DoS mitigation:** inbound body capped at 64 KiB; each request must arrive in full (headers and body) within 15 s (`http.Server.ReadTimeout`, with a 10 s header bound) and idle keep-alive connections close after 120 s; the per-frame write deadline bounds the collector side, so a misbehaving client/collector cannot wedge the process - -## Testing & coverage - -**Coverage gate:** 70% (`.testcoverage.yml`). Tests cover HTTP handler (methods, auth, empty body), RFC 5424 framing, APP-NAME/HOSTNAME/facility/severity validation, TCP/UDP forward, connection reuse, reconnect after the collector closes the connection (plain TCP and TLS), reconnect-after-write-failure, write deadline enforcement, forward-failure 502 (including a collector that has gone away), the intake read bound, graceful shutdown on context cancel, and env-var defaults. Uncovered: `main()`/`run()` process signal handling (ListenAndServe + SIGTERM), which is not unit-testable; ~30% gap is acceptable and noted in the gate comment. - -## References - -- `audit-syslog-bridge/README.md` — behavior table, config env-vars, transport tradeoffs, run instructions -- `docs/security.md` — audit integrity, threat model, pre-auth privacy (login page anonymity is separate; the bridge sits behind auth) -- `docs/install.md#audit-log` — Helm values to enable syslog-bridge, auth-header Secret wiring -- API audit webhook sink (`api/internal/audit/audit.go`) — `WebhookSink` calls `POST http://gameplane-audit-syslog-bridge..svc:8514/` with audit events diff --git a/audit-syslog-bridge/system-deps.toml b/audit-syslog-bridge/system-deps.toml deleted file mode 100644 index 5ebd0c027..000000000 --- a/audit-syslog-bridge/system-deps.toml +++ /dev/null @@ -1,15 +0,0 @@ -# System dependencies for audit-syslog-bridge (spec 026). Language libraries stay in go.mod/package.json. - -component = "audit-syslog-bridge" - -[[dep]] -name = "go" -kind = "toolchain" -version = "go" -reason = "Compiles and tests the audit-syslog-bridge module (go.work:3-21; inventory 2.1)." - -[[dep]] -name = "golangci-lint" -kind = "cli" -version = "golangci_lint" -reason = "make lint-go runs golangci-lint in this module (Makefile:302-305; GO_MODULES at Makefile:43)." diff --git a/capture-sidecar b/capture-sidecar new file mode 160000 index 000000000..1ef701cb1 --- /dev/null +++ b/capture-sidecar @@ -0,0 +1 @@ +Subproject commit 1ef701cb15dda75e907e8faf89ec0d9b42b7fbf0 diff --git a/capture-sidecar/.testcoverage.yml b/capture-sidecar/.testcoverage.yml deleted file mode 100644 index d0398bd32..000000000 --- a/capture-sidecar/.testcoverage.yml +++ /dev/null @@ -1,17 +0,0 @@ -# Coverage threshold gate for the capture-sidecar module. -# Enforced by `make cover-go-check` via go-test-coverage/v2. -# -# The capture-sidecar is an optional ephemeral container that captures and -# records network traffic from game pods via AF_PACKET sockets and PCAPNG -# writing. Its tests cover BPF filter compilation and validation, PCAPNG file -# writing, the packet path through an injected synthetic PacketSource, the HTTP -# control plane (routing, start/stop/status/download, size and duration limits, -# path safety) and mTLS certificate handling. The gate is 70, matching sentinel -# and mcp-server; ratchet it up as coverage grows. -profile: coverage/unit.out -github-action-output: false - -threshold: - file: 0 - package: 0 - total: 70 diff --git a/capture-sidecar/Dockerfile b/capture-sidecar/Dockerfile deleted file mode 100644 index a97d12ba7..000000000 --- a/capture-sidecar/Dockerfile +++ /dev/null @@ -1,41 +0,0 @@ -FROM --platform=$BUILDPLATFORM golang:1.27-alpine AS build -WORKDIR /src - -COPY capture-sidecar/go.mod capture-sidecar/go.sum* ./capture-sidecar/ -WORKDIR /src/capture-sidecar -RUN go mod download - -WORKDIR /src -COPY capture-sidecar/ ./capture-sidecar/ -WORKDIR /src/capture-sidecar - -RUN apk add --no-cache libcap~=2.78 - -ARG VERSION=dev -# Cross-compile on the build host ($BUILDPLATFORM above) rather than under -# QEMU emulation: multi-arch release builds of the arm64 image were slow -# enough to hit the release job timeout. -ARG TARGETARCH -RUN CGO_ENABLED=0 GOOS=linux GOARCH=${TARGETARCH} go build \ - -trimpath \ - -ldflags="-s -w -X main.Version=${VERSION}" \ - -o /out/capture-sidecar ./cmd - -# Apply CAP_NET_RAW via file capabilities instead of securityContext.capabilities.add. -# This is required because Kubernetes does not grant ambient capabilities — a -# non-root process's effective capability set is cleared on execve regardless of -# what the pod spec's capabilities.add list contains. File capabilities are the -# only mechanism that survives a non-root execve. The final stage relies on this -# grant and runs as nonroot, accepting allowPrivilegeEscalation: true to permit -# file capabilities to take effect (they are ignored under no_new_privs). -RUN cp /out/capture-sidecar /out/capture-tool && setcap cap_net_raw+ep /out/capture-sidecar - -FROM gcr.io/distroless/static:nonroot -WORKDIR / -COPY --from=build /out/capture-sidecar /capture-sidecar -# No file capabilities: the artifact server is Restricted; the node worker -# receives its explicit root capability set from its dedicated Job spec. -COPY --from=build /out/capture-tool /capture-tool -USER 65532:65532 -EXPOSE 9091 -ENTRYPOINT ["/capture-sidecar"] diff --git a/capture-sidecar/cmd/main.go b/capture-sidecar/cmd/main.go deleted file mode 100644 index c1219037c..000000000 --- a/capture-sidecar/cmd/main.go +++ /dev/null @@ -1,188 +0,0 @@ -// Command capture-sidecar is an optional ephemeral container that runs -// alongside a game server to capture network traffic to PCAPNG files. -// It listens on :9091 for mTLS-authenticated control commands from the -// API server: start a packet capture with a BPF filter, stop an active -// capture, poll capture status, or download a completed PCAPNG file. -// -// Captured packets are written to emptyDir volume at /tmp/captures. -// The sidecar is injected only when spec.capture.enabled = true on the -// GameServer; the capture emptyDir volume is pre-provisioned on all game -// pods (see contracts/capture-sidecar.md for full details). -package main - -import ( - "context" - "encoding/json" - "errors" - "flag" - "log/slog" - "net/http" - "os" - "os/signal" - "strconv" - "syscall" - "time" - - "github.com/GameplanePanel/gameplane/capture-sidecar/internal/auth" - "github.com/GameplanePanel/gameplane/capture-sidecar/internal/httpserver" - "github.com/GameplanePanel/gameplane/capture-sidecar/internal/nodecapture" -) - -// Version is overridden at build time via -ldflags (see Dockerfile). -var Version = "dev" - -// shutdownTimeout bounds the graceful drain on SIGTERM. An in-flight capture -// download may legitimately still be streaming when the pod is torn down. -const shutdownTimeout = 30 * time.Second - -// defaultVolumeBudgetBytes is the fallback used when CAPTURE_VOLUME_BUDGET_BYTES -// is unset or unparsable (e.g. run standalone outside the operator). It -// matches captureVolumeBudgetBytes in -// operator/internal/controller/gameserver_controller.go: the 1Gi "captures" -// emptyDir SizeLimit minus the same 10% safety margin. -const defaultVolumeBudgetBytes int64 = 1*1024*1024*1024 - (1*1024*1024*1024)/10 - -// envOrDefault returns the named environment variable's value, or fallback -// if it is unset or empty. Used for the flag defaults below so an operator- -// set env var actually takes effect (F-188), while an explicit CLI flag -// still wins over both, and running with no env vars at all (standalone, -// tests) keeps the same hardcoded fallback as before. -func envOrDefault(name, fallback string) string { - if v := os.Getenv(name); v != "" { - return v - } - return fallback -} - -func main() { - // TLS_CERT_FILE/TLS_KEY_FILE/TLS_CA_FILE are the env vars specs.md - // documents as required, and the ones buildCaptureEphemeralContainer - // (operator/internal/controller/gameserver_controller.go) actually sets - // on the ephemeral container. They only take effect as flag defaults - // here (mirroring the CAPTURE_VOLUME_BUDGET_BYTES pattern below): the - // operator never passes -tls-cert/-tls-key/-tls-client-ca args, so - // before this the env vars had no effect at all and the sidecar worked - // only because the flag defaults happened to equal the env values - // (F-188). An explicit flag still overrides the env value, same as any - // other flag/default relationship. - listenAddr := flag.String("listen", "0.0.0.0:9091", "HTTP listen address") - certFile := flag.String("tls-cert", envOrDefault("TLS_CERT_FILE", "/etc/tls/tls.crt"), "Server certificate file") - keyFile := flag.String("tls-key", envOrDefault("TLS_KEY_FILE", "/etc/tls/tls.key"), "Server key file") - caFile := flag.String("tls-client-ca", envOrDefault("TLS_CA_FILE", "/etc/tls/ca.crt"), "Client CA certificate file") - captureDataDir := flag.String("capture-dir", "/tmp/captures", "Directory for capture files") - nodeWorker := flag.Bool("node-worker", false, "Run one operator-bound node diagnostic capture and exit") - artifactOnly := flag.Bool("artifacts-only", false, "Serve completed node capture artifacts without capture controls") - - // The operator sets CAPTURE_VOLUME_BUDGET_BYTES on the capture ephemeral - // container (see buildCaptureEphemeralContainer in - // operator/internal/controller/gameserver_controller.go), derived from - // the "captures" emptyDir's own SizeLimit so the two can't drift apart - // (F-187). A flag default keeps this runnable standalone and in tests. - volumeBudgetDefault := defaultVolumeBudgetBytes - if v := os.Getenv("CAPTURE_VOLUME_BUDGET_BYTES"); v != "" { - parsed, err := strconv.ParseInt(v, 10, 64) - if err != nil || parsed <= 0 { - slog.Error("invalid CAPTURE_VOLUME_BUDGET_BYTES, using default", "value", v, "default", defaultVolumeBudgetBytes) - } else { - volumeBudgetDefault = parsed - } - } - volumeBudgetBytes := flag.Int64("capture-volume-budget-bytes", volumeBudgetDefault, - "Maximum total bytes of retained capture files plus a new capture's own maxSizeBytes before HandleStart refuses to start; 0 disables the check") - flag.Parse() - - ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) - defer stop() - if *nodeWorker { - var cfg nodecapture.Config - if *artifactOnly || json.Unmarshal([]byte(os.Getenv("NODE_CAPTURE_CONFIG")), &cfg) != nil { - slog.Error("invalid node capture configuration") - os.Exit(1) - } - if err := nodecapture.Run(ctx, cfg, *captureDataDir); err != nil { - slog.Error("node capture failed", "err", err) - os.Exit(1) - } - return - } - - // Create capture server. ctx (cancelled on SIGTERM/SIGINT) is the parent - // for every capture goroutine, so shutdown cancels in-flight captures - // instead of leaking them past server exit. - captureServer := httpserver.NewServer(ctx, *captureDataDir, *volumeBudgetBytes, os.Getenv("GAMEPLANE_SERVER_UID")) - - // Set up mTLS. The certificates come from the same per-GameServer - // `agent-tls` Secret the agent uses, mounted at /etc/tls. - tlsConfig, err := auth.ServerTLS(*certFile, *keyFile, *caFile) - if err != nil { - slog.Error("failed to setup TLS", "err", err) - os.Exit(1) - } - - // Every capture endpoint is wrapped in the mTLS middleware; /healthz is - // the only route not additionally wrapped by it. That does not make it - // reachable without a client certificate: the http.Server below serves - // every route, /healthz included, over the same TLS listener whose - // TLSConfig requires and verifies a client certificate at the handshake - // (see HandleHealthz's doc comment for why nothing actually calls this - // route today; F-193). - mux := captureServer.Routes(auth.Middleware) - if *artifactOnly { - mux = captureServer.ArtifactRoutes(auth.Middleware) - } - - server := &http.Server{ - Addr: *listenAddr, - Handler: mux, - TLSConfig: tlsConfig, - // ReadHeaderTimeout guards against slow-header connections holding the - // server open indefinitely (gosec G112). - ReadHeaderTimeout: 10 * time.Second, - // ReadTimeout bounds how long reading a full request (headers + body) - // may take. Every request body handled here is a small JSON control - // message, so this is safe to bound tightly. - ReadTimeout: 30 * time.Second, - // WriteTimeout is deliberately left unset (zero == no limit): capture - // file downloads can be multi-GiB and legitimately take far longer to - // stream than any fixed response deadline would allow. - } - - slog.Info("capture-sidecar starting", "addr", server.Addr, "version", Version) - - // Serve TLS with client-certificate verification (RequireAndVerifyClientCert - // and TLS 1.2 minimum, from auth.ServerTLS). This is the sidecar's only - // authentication boundary: on a plaintext listener anything that can reach - // the pod network could start captures and download another server's - // packet data, so svcutil.RunHTTP - which is HTTP-only - must not be used - // here. Empty file arguments make ListenAndServeTLS use the certificates - // already in server.TLSConfig, matching agent/cmd/main.go. - errCh := make(chan error, 1) - go func() { - if err := server.ListenAndServeTLS("", ""); err != nil && !errors.Is(err, http.ErrServerClosed) { - errCh <- err - } - close(errCh) - }() - - select { - case err := <-errCh: - if err != nil { - slog.Error("server error", "err", err) - os.Exit(1) - } - case <-ctx.Done(): - } - - shutdownCtx, cancel := context.WithTimeout(context.Background(), shutdownTimeout) - defer cancel() - if err := server.Shutdown(shutdownCtx); err != nil { - slog.Error("graceful shutdown failed", "err", err) - } - - // Finalize any in-flight capture so its PCAPNG file is closed and valid - // rather than truncated and unreadable. This is called after HTTP shutdown, - // so no new requests will start new captures or stop the one we're finalizing. - captureServer.FinalizeCurrentCapture() - - slog.Info("capture-sidecar stopped") -} diff --git a/capture-sidecar/cmd/main_test.go b/capture-sidecar/cmd/main_test.go deleted file mode 100644 index aa3dd5ed4..000000000 --- a/capture-sidecar/cmd/main_test.go +++ /dev/null @@ -1,42 +0,0 @@ -package main - -import "testing" - -// TestEnvOrDefault_UsesEnvWhenSet is the regression test for F-188: the -// TLS_CERT_FILE/TLS_KEY_FILE/TLS_CA_FILE env vars specs.md documents as -// required (and that the operator's buildCaptureEphemeralContainer actually -// sets) previously had no effect at all - the sidecar only appeared to -// honor them because its flag defaults happened to equal the same paths. -func TestEnvOrDefault_UsesEnvWhenSet(t *testing.T) { - const name = "GAMEPLANE_CAPTURE_SIDECAR_TEST_ENV_OR_DEFAULT" - - t.Run("unset falls back", func(t *testing.T) { - t.Setenv(name, "") - if got := envOrDefault(name, "/fallback/path"); got != "/fallback/path" { - t.Errorf("envOrDefault = %q, want fallback %q", got, "/fallback/path") - } - }) - - t.Run("set value takes effect", func(t *testing.T) { - t.Setenv(name, "/mounted/custom.crt") - if got := envOrDefault(name, "/fallback/path"); got != "/mounted/custom.crt" { - t.Errorf("envOrDefault = %q, want the env value %q", got, "/mounted/custom.crt") - } - }) -} - -// TestDefaultVolumeBudgetBytes_MatchesOperator pins defaultVolumeBudgetBytes -// to the value it must keep matching by hand: the operator's -// captureVolumeBudgetBytes in -// operator/internal/controller/gameserver_controller.go (1Gi "captures" -// emptyDir SizeLimit minus a 10% safety margin, i.e. 966367642 bytes). The -// two constants can't share Go code across modules, so this test exists to -// catch an accidental edit to either side going unnoticed (see -// defaultVolumeBudgetBytes' doc comment in main.go). -func TestDefaultVolumeBudgetBytes_MatchesOperator(t *testing.T) { - const wantOperatorCaptureVolumeBudgetBytes = 966367642 - if defaultVolumeBudgetBytes != wantOperatorCaptureVolumeBudgetBytes { - t.Errorf("defaultVolumeBudgetBytes = %d, want %d (must match captureVolumeBudgetBytes in operator/internal/controller/gameserver_controller.go)", - defaultVolumeBudgetBytes, wantOperatorCaptureVolumeBudgetBytes) - } -} diff --git a/capture-sidecar/go.mod b/capture-sidecar/go.mod deleted file mode 100644 index dcbc4a957..000000000 --- a/capture-sidecar/go.mod +++ /dev/null @@ -1,10 +0,0 @@ -module github.com/GameplanePanel/gameplane/capture-sidecar - -go 1.27.0 - -require ( - github.com/gopacket/gopacket v1.7.7 - github.com/packetcap/go-pcap v0.0.0-20260731105150-c86974bbfbcd - golang.org/x/net v0.62.0 - golang.org/x/sys v0.50.0 -) diff --git a/capture-sidecar/go.sum b/capture-sidecar/go.sum deleted file mode 100644 index 04ee7ad10..000000000 --- a/capture-sidecar/go.sum +++ /dev/null @@ -1,12 +0,0 @@ -github.com/gopacket/gopacket v1.7.7 h1:9MaMKsjcFCnUVPI9CHp/ZDhu1SSV+rs0THQ2ztRAqmE= -github.com/gopacket/gopacket v1.7.7/go.mod h1:QKowPlTLrQU2rqV5C5I14Aoaid3l8da3kbddibc/Wgk= -github.com/packetcap/go-pcap v0.0.0-20260731105150-c86974bbfbcd h1:lRlH5Jge3npkPSIPn2KoD+X+amqeiaz15RRLemt3mMA= -github.com/packetcap/go-pcap v0.0.0-20260731105150-c86974bbfbcd/go.mod h1:wQ9T8epu/dBnGtVB7SwXIGZE3FEy6h2e9zCEZIUnpho= -github.com/vishvananda/netlink v1.1.0 h1:1iyaYNBLmP6L0220aDnYQpo1QEV4t4hJ+xEEhhJH8j0= -github.com/vishvananda/netlink v1.1.0/go.mod h1:cTgwzPIzzgDAYoQrMm0EdrjRUBkTqKYppBueQtXaqoE= -github.com/vishvananda/netns v0.0.0-20211101163701-50045581ed74 h1:gga7acRE695APm9hlsSMoOoE65U4/TcqNj90mc69Rlg= -github.com/vishvananda/netns v0.0.0-20211101163701-50045581ed74/go.mod h1:DD4vA1DwXk04H54A1oHXtwZmA0grkVMdPxx/VGLCah0= -golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= -golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= -golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= -golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= diff --git a/capture-sidecar/internal/auth/tls.go b/capture-sidecar/internal/auth/tls.go deleted file mode 100644 index a5c7cc3d0..000000000 --- a/capture-sidecar/internal/auth/tls.go +++ /dev/null @@ -1,137 +0,0 @@ -// Package auth provides mTLS certificate validation for the capture sidecar's -// :9091 control endpoint, reusing the agent's existing per-GameServer -// certificate infrastructure. -package auth - -import ( - "crypto/tls" - "crypto/x509" - "encoding/pem" - "errors" - "fmt" - "net/http" - "os" - "path/filepath" -) - -// ServerTLS builds a tls.Config enforcing client-cert verification -// against the supplied CA bundle. Material is validated at startup and loaded -// again for each new handshake so projected Secret renewal needs no rollout. -// It advertises HTTP/2 and HTTP/1.1, matching the capture HTTP server. Callers -// using other protocol policies must set NextProtos to their supported list. -func ServerTLS(certFile, keyFile, clientCAFile string) (*tls.Config, error) { - paths := []string{certFile, keyFile, clientCAFile} - cfg, err := loadServerTLS(paths, os.ReadFile) - if err != nil { - return nil, err - } - cfg.GetConfigForClient = func(*tls.ClientHelloInfo) (*tls.Config, error) { - current, err := loadServerTLS(paths, os.ReadFile) - if err != nil { - // Do not fall back to cached certificates or trust after bad rotation. - return nil, err - } - // Retain caller-provided TLS settings without mutating a configuration - // already in use by another handshake. - next := cfg.Clone() - next.GetConfigForClient = nil - next.Certificates = current.Certificates - next.ClientCAs = current.ClientCAs - next.ClientAuth = tls.RequireAndVerifyClientCert - next.MinVersion = max(next.MinVersion, tls.VersionTLS12) - next.SessionTicketsDisabled = true - return next, nil - } - return cfg, nil -} - -// loadServerTLS reads one generation of every projected volume before parsing -// any material. Resolving each visible file separately can mix a serving pair -// from one generation with a client CA from another, even when the key matches. -func loadServerTLS(paths []string, readFile func(string) ([]byte, error)) (*tls.Config, error) { - pinned := make([]string, len(paths)) - generations := make(map[string]string) - for i, path := range paths { - if path == "" { - continue - } - path = filepath.Clean(path) - dir := filepath.Dir(path) - generation, ok := generations[dir] - if !ok { - target, err := os.Readlink(filepath.Join(dir, "..data")) - switch { - case err == nil: - generation = filepath.Join(dir, target) - case errors.Is(err, os.ErrNotExist): - // Regular files remain supported for non-Kubernetes deployments. - generation = dir - default: - return nil, fmt.Errorf("resolve TLS Secret generation: %w", err) - } - generations[dir] = generation - } - pinned[i] = filepath.Join(generation, filepath.Base(path)) - } - certPEM, err := readFile(pinned[0]) - if err != nil { - return nil, fmt.Errorf("server keypair: %w", err) - } - keyPEM, err := readFile(pinned[1]) - if err != nil { - return nil, fmt.Errorf("server keypair: %w", err) - } - cert, err := tls.X509KeyPair(certPEM, keyPEM) - if err != nil { - return nil, fmt.Errorf("server keypair: %w", err) - } - pool := x509.NewCertPool() - if pinned[2] != "" { - ca, err := readFile(pinned[2]) - if err != nil { - return nil, fmt.Errorf("read client CA: %w", err) - } - // AppendCertsFromPEM silently skips invalid certificates. Validate every - // certificate block first so a partially corrupt rotation fails closed. - for rest := ca; len(rest) > 0; { - var block *pem.Block - block, rest = pem.Decode(rest) - if block == nil { - break - } - if block.Type != "CERTIFICATE" { - continue - } - if _, err := x509.ParseCertificate(block.Bytes); err != nil { - return nil, fmt.Errorf("parse client CA certificate: %w", err) - } - } - if !pool.AppendCertsFromPEM(ca) { - return nil, errors.New("client CA bundle contains no valid certs") - } - } - return &tls.Config{ - Certificates: []tls.Certificate{cert}, - ClientCAs: pool, - ClientAuth: tls.RequireAndVerifyClientCert, - MinVersion: tls.VersionTLS12, - // net/http adjusts ALPN on its own clone. Set our HTTP protocols - // explicitly so GetConfigForClient's replacement retains negotiation. - NextProtos: []string{"h2", "http/1.1"}, - // Every new connection must verify against the current client CA. - // TLS 1.2/1.3 session resumption would otherwise retain stale trust. - SessionTicketsDisabled: true, - }, nil -} - -// Middleware returns an HTTP middleware that enforces mTLS validation. -// Rejects requests without a verified client certificate. -func Middleware(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - if req.TLS == nil || len(req.TLS.VerifiedChains) == 0 { - http.Error(w, "client certificate required", http.StatusUnauthorized) - return - } - next.ServeHTTP(w, req) - }) -} diff --git a/capture-sidecar/internal/auth/tls_rotation_test.go b/capture-sidecar/internal/auth/tls_rotation_test.go deleted file mode 100644 index 8d19ff1c3..000000000 --- a/capture-sidecar/internal/auth/tls_rotation_test.go +++ /dev/null @@ -1,409 +0,0 @@ -package auth - -import ( - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "crypto/tls" - "crypto/x509" - "crypto/x509/pkix" - "encoding/pem" - "io" - "math/big" - "net/http" - "net/http/httptest" - "os" - "path/filepath" - "testing" - "time" -) - -type rotationCA struct { - cert *x509.Certificate - key *ecdsa.PrivateKey - pem []byte -} - -func newRotationCA(t *testing.T, serial int64) rotationCA { - t.Helper() - key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - if err != nil { - t.Fatal(err) - } - template := &x509.Certificate{SerialNumber: big.NewInt(serial), Subject: pkix.Name{CommonName: "rotation CA"}, - NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), IsCA: true, - BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature} - der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key) - if err != nil { - t.Fatal(err) - } - cert, err := x509.ParseCertificate(der) - if err != nil { - t.Fatal(err) - } - return rotationCA{cert, key, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})} -} - -func (ca rotationCA) issue(t *testing.T, serial int64, usage x509.ExtKeyUsage) ([]byte, []byte, tls.Certificate) { - t.Helper() - key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - if err != nil { - t.Fatal(err) - } - template := &x509.Certificate{SerialNumber: big.NewInt(serial), DNSNames: []string{"localhost"}, - NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), - KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{usage}} - der, err := x509.CreateCertificate(rand.Reader, template, ca.cert, &key.PublicKey, ca.key) - if err != nil { - t.Fatal(err) - } - keyDER, err := x509.MarshalECPrivateKey(key) - if err != nil { - t.Fatal(err) - } - certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}) - keyPEM := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER}) - cert, err := tls.X509KeyPair(certPEM, keyPEM) - if err != nil { - t.Fatal(err) - } - return certPEM, keyPEM, cert -} - -func writeRotationBundle(t *testing.T, dir string, cert, key, ca []byte) { - t.Helper() - if err := os.MkdirAll(dir, 0o700); err != nil { - t.Fatal(err) - } - for name, data := range map[string][]byte{"tls.crt": cert, "tls.key": key, "ca.crt": ca} { - if err := os.WriteFile(filepath.Join(dir, name), data, 0o600); err != nil { - t.Fatal(err) - } - } -} - -func rotationServer(t *testing.T, cfg *tls.Config) *httptest.Server { - t.Helper() - srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) })) - srv.TLS = cfg - srv.StartTLS() - t.Cleanup(srv.Close) - return srv -} - -func rotationClient(cert tls.Certificate, roots []byte, version uint16) *http.Client { - pool := x509.NewCertPool() - pool.AppendCertsFromPEM(roots) - return &http.Client{Timeout: 5 * time.Second, Transport: &http.Transport{DisableKeepAlives: true, - TLSClientConfig: &tls.Config{Certificates: []tls.Certificate{cert}, RootCAs: pool, ServerName: "localhost", - MinVersion: version, MaxVersion: version, ClientSessionCache: tls.NewLRUClientSessionCache(8)}}} -} - -func rotationRequest(t *testing.T, client *http.Client, srv *httptest.Server) (*tls.ConnectionState, error) { - t.Helper() - req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, srv.URL, nil) - if err != nil { - t.Fatal(err) - } - response, err := client.Do(req) - if err != nil { - return nil, err - } - defer response.Body.Close() - if _, err := io.Copy(io.Discard, response.Body); err != nil { - t.Fatal(err) - } - if response.StatusCode != http.StatusOK { - t.Fatalf("status %d", response.StatusCode) - } - return response.TLS, nil -} - -func TestServerTLS_HandshakeRenewalAndCARotation(t *testing.T) { - for _, version := range []uint16{tls.VersionTLS12, tls.VersionTLS13} { - t.Run(tls.VersionName(version), func(t *testing.T) { - ca1, ca2 := newRotationCA(t, 100), newRotationCA(t, 200) - cert1, key1, _ := ca1.issue(t, 1, x509.ExtKeyUsageServerAuth) - cert2, key2, _ := ca1.issue(t, 2, x509.ExtKeyUsageServerAuth) - _, _, client1 := ca1.issue(t, 11, x509.ExtKeyUsageClientAuth) - _, _, client2 := ca2.issue(t, 22, x509.ExtKeyUsageClientAuth) - dir := t.TempDir() - writeRotationBundle(t, dir, cert1, key1, ca1.pem) - cfg, err := ServerTLS(filepath.Join(dir, "tls.crt"), filepath.Join(dir, "tls.key"), filepath.Join(dir, "ca.crt")) - if err != nil { - t.Fatal(err) - } - srv := rotationServer(t, cfg) - oldClient := rotationClient(client1, ca1.pem, version) - for range 2 { - state, err := rotationRequest(t, oldClient, srv) - if err != nil { - t.Fatal(err) - } - if state.DidResume || state.PeerCertificates[0].SerialNumber.Int64() != 1 { - t.Fatalf("unexpected initial handshake: %+v", state) - } - } - writeRotationBundle(t, dir, cert2, key2, ca1.pem) - state, err := rotationRequest(t, oldClient, srv) - if err != nil { - t.Fatal(err) - } - if state.DidResume || state.PeerCertificates[0].SerialNumber.Int64() != 2 { - t.Fatalf("renewed certificate not served: %+v", state) - } - writeRotationBundle(t, dir, cert2, key2, ca2.pem) - if _, err := rotationRequest(t, oldClient, srv); err == nil { - t.Fatal("removed client CA still trusted, including cached sessions") - } - if _, err := rotationRequest(t, rotationClient(client2, ca1.pem, version), srv); err != nil { - t.Fatalf("new client CA rejected: %v", err) - } - if _, err := rotationRequest(t, rotationClient(tls.Certificate{}, ca1.pem, version), srv); err == nil { - t.Fatal("client certificate requirement weakened") - } - }) - } -} - -func TestServerTLS_InvalidRotationFailsClosedAndRecovers(t *testing.T) { - ca := newRotationCA(t, 100) - cert, key, _ := ca.issue(t, 1, x509.ExtKeyUsageServerAuth) - _, wrongKey, clientCert := ca.issue(t, 11, x509.ExtKeyUsageClientAuth) - dir := t.TempDir() - writeRotationBundle(t, dir, cert, key, ca.pem) - cfg, err := ServerTLS(filepath.Join(dir, "tls.crt"), filepath.Join(dir, "tls.key"), filepath.Join(dir, "ca.crt")) - if err != nil { - t.Fatal(err) - } - srv := rotationServer(t, cfg) - client := rotationClient(clientCert, ca.pem, tls.VersionTLS13) - if _, err := rotationRequest(t, client, srv); err != nil { - t.Fatal(err) - } - for _, tc := range []struct { - name string - bad []byte - }{ - {"ca.crt", []byte("not PEM")}, {"tls.crt", []byte("not PEM")}, {"tls.key", wrongKey}, {"ca.crt", nil}, {"tls.crt", nil}, {"tls.key", nil}, - } { - writeRotationBundle(t, dir, cert, key, ca.pem) - path := filepath.Join(dir, tc.name) - if tc.bad == nil { - if err := os.Remove(path); err != nil { - t.Fatal(err) - } - } else if err := os.WriteFile(path, tc.bad, 0o600); err != nil { - t.Fatal(err) - } - if _, err := rotationRequest(t, client, srv); err == nil { - t.Fatalf("invalid %s rotation reused old TLS material", tc.name) - } - } - writeRotationBundle(t, dir, cert, key, ca.pem) - if _, err := rotationRequest(t, client, srv); err != nil { - t.Fatalf("valid material did not recover: %v", err) - } -} - -// TestServerTLS_MalformedCertificateRejectsEntireCABundle covers startup and -// live rotation, including recovery to a valid bundle with multiple trusted CAs. -func TestServerTLS_MalformedCertificateRejectsEntireCABundle(t *testing.T) { - ca1, ca2 := newRotationCA(t, 100), newRotationCA(t, 200) - cert, key, _ := ca1.issue(t, 1, x509.ExtKeyUsageServerAuth) - _, _, client1 := ca1.issue(t, 11, x509.ExtKeyUsageClientAuth) - _, _, client2 := ca2.issue(t, 22, x509.ExtKeyUsageClientAuth) - invalid := string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: []byte("invalid DER")})) - valid := []byte(string(ca1.pem) + string(ca2.pem)) - for _, version := range []uint16{tls.VersionTLS12, tls.VersionTLS13} { - t.Run(tls.VersionName(version), func(t *testing.T) { - for _, tc := range []struct { - name string - bundle string - }{ - {"invalid first", invalid + string(valid)}, - {"invalid last", string(valid) + invalid}, - {"invalid between CAs", string(ca1.pem) + invalid + string(ca2.pem)}, - } { - t.Run(tc.name, func(t *testing.T) { - dir := t.TempDir() - writeRotationBundle(t, dir, cert, key, valid) - certPath, keyPath, caPath := filepath.Join(dir, "tls.crt"), filepath.Join(dir, "tls.key"), filepath.Join(dir, "ca.crt") - cfg, err := ServerTLS(certPath, keyPath, caPath) - if err != nil { - t.Fatalf("valid multi-CA bundle rejected: %v", err) - } - srv := rotationServer(t, cfg) - clients := []*http.Client{ - rotationClient(client1, ca1.pem, version), - rotationClient(client2, ca1.pem, version), - } - for i, client := range clients { - if _, err := rotationRequest(t, client, srv); err != nil { - t.Fatalf("CA %d rejected before rotation: %v", i+1, err) - } - } - writeRotationBundle(t, dir, cert, key, []byte(tc.bundle)) - if cfg, err := ServerTLS(certPath, keyPath, caPath); err == nil || cfg != nil { - t.Error("mixed valid/malformed CA bundle accepted at startup") - } - for i, client := range clients { - if _, err := rotationRequest(t, client, srv); err == nil { - t.Errorf("CA %d still trusted after malformed rotation", i+1) - } - } - writeRotationBundle(t, dir, cert, key, valid) - for i, client := range clients { - if _, err := rotationRequest(t, client, srv); err != nil { - t.Fatalf("CA %d did not recover after repair: %v", i+1, err) - } - } - }) - } - }) - } -} - -func TestServerTLS_HTTPProtocolsSurviveRenewal(t *testing.T) { - ca := newRotationCA(t, 100) - cert1, key1, _ := ca.issue(t, 1, x509.ExtKeyUsageServerAuth) - cert2, key2, _ := ca.issue(t, 2, x509.ExtKeyUsageServerAuth) - _, _, clientCert := ca.issue(t, 11, x509.ExtKeyUsageClientAuth) - dir := t.TempDir() - writeRotationBundle(t, dir, cert1, key1, ca.pem) - cfg, err := ServerTLS(filepath.Join(dir, "tls.crt"), filepath.Join(dir, "tls.key"), filepath.Join(dir, "ca.crt")) - if err != nil { - t.Fatal(err) - } - srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) })) - srv.EnableHTTP2 = true - srv.TLS = cfg - srv.StartTLS() - t.Cleanup(srv.Close) - h2 := rotationClient(clientCert, ca.pem, tls.VersionTLS13) - h2.Transport.(*http.Transport).ForceAttemptHTTP2 = true - h1 := rotationClient(clientCert, ca.pem, tls.VersionTLS13) - h1.Transport.(*http.Transport).TLSClientConfig.NextProtos = []string{"http/1.1"} - for _, serial := range []int64{1, 2} { - if serial == 2 { - writeRotationBundle(t, dir, cert2, key2, ca.pem) - } - for _, tc := range []struct { - client *http.Client - protocol string - major int - }{{h2, "h2", 2}, {h1, "http/1.1", 1}} { - tc.client.Transport.(*http.Transport).CloseIdleConnections() - req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, srv.URL, nil) - if err != nil { - t.Fatal(err) - } - response, err := tc.client.Do(req) - if err != nil { - t.Fatal(err) - } - _, readErr := io.Copy(io.Discard, response.Body) - closeErr := response.Body.Close() - if readErr != nil || closeErr != nil { - t.Fatalf("read: %v, close: %v", readErr, closeErr) - } - if response.StatusCode != http.StatusOK || response.ProtoMajor != tc.major || response.TLS.NegotiatedProtocol != tc.protocol || response.TLS.PeerCertificates[0].SerialNumber.Int64() != serial { - t.Fatalf("serial %d: got status %d protocol %s ALPN %q certificate %s", serial, response.StatusCode, response.Proto, response.TLS.NegotiatedProtocol, response.TLS.PeerCertificates[0].SerialNumber) - } - } - } -} - -func swapRotationProjection(t *testing.T, dir, generation string) { - t.Helper() - if err := os.Symlink(generation, filepath.Join(dir, "..data-new")); err != nil { - t.Fatal(err) - } - if err := os.Rename(filepath.Join(dir, "..data-new"), filepath.Join(dir, "..data")); err != nil { - t.Fatal(err) - } -} - -func TestServerTLS_ProjectedSecretPinsOneGenerationAcrossReads(t *testing.T) { - ca1, ca2 := newRotationCA(t, 100), newRotationCA(t, 200) - // Keep the serving keypair identical: only checking keypair consistency - // would miss an old certificate combined with a new client CA. - cert, key, _ := ca1.issue(t, 1, x509.ExtKeyUsageServerAuth) - _, _, oldCert := ca1.issue(t, 11, x509.ExtKeyUsageClientAuth) - _, _, newCert := ca2.issue(t, 22, x509.ExtKeyUsageClientAuth) - dir := t.TempDir() - writeRotationBundle(t, filepath.Join(dir, "generation-a"), cert, key, ca1.pem) - writeRotationBundle(t, filepath.Join(dir, "generation-b"), cert, key, ca2.pem) - swapRotationProjection(t, dir, "generation-a") - for _, name := range []string{"tls.crt", "tls.key", "ca.crt"} { - if err := os.Symlink(filepath.Join("..data", name), filepath.Join(dir, name)); err != nil { - t.Fatal(err) - } - } - paths := []string{filepath.Join(dir, "tls.crt"), filepath.Join(dir, "tls.key"), filepath.Join(dir, "ca.crt")} - reads := 0 - pinned, err := loadServerTLS(paths, func(path string) ([]byte, error) { - data, err := os.ReadFile(path) - reads++ - if reads == 1 { - swapRotationProjection(t, dir, "generation-b") - } - return data, err - }) - if err != nil { - t.Fatal(err) - } - srv := rotationServer(t, pinned) - if _, err := rotationRequest(t, rotationClient(oldCert, ca1.pem, tls.VersionTLS13), srv); err != nil { - t.Fatalf("pinned generation lost its CA: %v", err) - } - if _, err := rotationRequest(t, rotationClient(newCert, ca1.pem, tls.VersionTLS13), srv); err == nil { - t.Fatal("CA from a different generation was mixed into pinned material") - } - // Production callback must resolve the newer projection on the next handshake. - cfg, err := ServerTLS(paths[0], paths[1], paths[2]) - if err != nil { - t.Fatal(err) - } - live := rotationServer(t, cfg) - if _, err := rotationRequest(t, rotationClient(newCert, ca1.pem, tls.VersionTLS13), live); err != nil { - t.Fatal(err) - } - swapRotationProjection(t, dir, "generation-a") - if _, err := rotationRequest(t, rotationClient(oldCert, ca1.pem, tls.VersionTLS13), live); err != nil { - t.Fatalf("projection rotation not reloaded: %v", err) - } - if _, err := rotationRequest(t, rotationClient(newCert, ca1.pem, tls.VersionTLS13), live); err == nil { - t.Fatal("removed projected CA retained") - } - // Kubelet may remove the old generation after swapping ..data. An - // interrupted read must fail rather than finish using replacement files. - reads = 0 - partial, err := loadServerTLS(paths, func(path string) ([]byte, error) { - data, err := os.ReadFile(path) - reads++ - if reads == 1 { - swapRotationProjection(t, dir, "generation-b") - if err := os.RemoveAll(filepath.Join(dir, "generation-a")); err != nil { - t.Fatal(err) - } - } - return data, err - }) - if err == nil || partial != nil { - t.Fatal("removed generation fell back to mixed material") - } - if _, err := rotationRequest(t, rotationClient(newCert, ca1.pem, tls.VersionTLS13), live); err != nil { - t.Fatalf("next handshake did not recover from removed projection: %v", err) - } - // An invalid ..data entry cannot be treated as ordinary files. - if err := os.Remove(filepath.Join(dir, "..data")); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(dir, "..data"), []byte("invalid projection"), 0o600); err != nil { - t.Fatal(err) - } - if _, err := ServerTLS(paths[0], paths[1], paths[2]); err == nil { - t.Fatal("invalid projection accepted at startup") - } -} diff --git a/capture-sidecar/internal/auth/tls_test.go b/capture-sidecar/internal/auth/tls_test.go deleted file mode 100644 index 03f1bc74f..000000000 --- a/capture-sidecar/internal/auth/tls_test.go +++ /dev/null @@ -1,290 +0,0 @@ -package auth - -import ( - "context" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "crypto/tls" - "crypto/x509" - "crypto/x509/pkix" - "encoding/pem" - "math/big" - "net" - "net/http" - "net/http/httptest" - "os" - "path/filepath" - "strings" - "testing" - "time" -) - -func TestServerTLS(t *testing.T) { - ca := newTestCA(t) - certPath, keyPath := ca.issue(t, "capture-sidecar") - - t.Run("success without a client CA bundle", func(t *testing.T) { - cfg, err := ServerTLS(certPath, keyPath, "") - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if cfg.ClientAuth != tls.RequireAndVerifyClientCert { - t.Errorf("ClientAuth = %v, want RequireAndVerifyClientCert", cfg.ClientAuth) - } - if cfg.MinVersion != tls.VersionTLS12 { - t.Errorf("MinVersion = %d, want %d", cfg.MinVersion, tls.VersionTLS12) - } - if len(cfg.Certificates) != 1 { - t.Errorf("Certificates = %d, want 1", len(cfg.Certificates)) - } - }) - - t.Run("success with a client CA bundle", func(t *testing.T) { - cfg, err := ServerTLS(certPath, keyPath, ca.certPath) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if cfg.ClientCAs == nil { - t.Fatal("ClientCAs is nil; the CA bundle was not loaded") - } - if cfg.ClientAuth != tls.RequireAndVerifyClientCert { - t.Errorf("ClientAuth = %v, want RequireAndVerifyClientCert", cfg.ClientAuth) - } - }) - - t.Run("missing keypair", func(t *testing.T) { - _, err := ServerTLS(filepath.Join(t.TempDir(), "nope.crt"), filepath.Join(t.TempDir(), "nope.key"), "") - if err == nil || !strings.Contains(err.Error(), "server keypair") { - t.Fatalf("err = %v, want a server keypair error", err) - } - }) - - t.Run("malformed keypair", func(t *testing.T) { - dir := t.TempDir() - badCert := filepath.Join(dir, "bad.crt") - badKey := filepath.Join(dir, "bad.key") - writeFile(t, badCert, "not a certificate") - writeFile(t, badKey, "not a key") - _, err := ServerTLS(badCert, badKey, "") - if err == nil || !strings.Contains(err.Error(), "server keypair") { - t.Fatalf("err = %v, want a server keypair error", err) - } - }) - - t.Run("missing client CA file", func(t *testing.T) { - _, err := ServerTLS(certPath, keyPath, filepath.Join(t.TempDir(), "nope.crt")) - if err == nil || !strings.Contains(err.Error(), "read client CA") { - t.Fatalf("err = %v, want a read client CA error", err) - } - }) - - t.Run("client CA file holds no certificates", func(t *testing.T) { - bogus := filepath.Join(t.TempDir(), "ca.crt") - writeFile(t, bogus, "-----BEGIN NOT A CERTIFICATE-----\n") - _, err := ServerTLS(certPath, keyPath, bogus) - if err == nil || !strings.Contains(err.Error(), "no valid certs") { - t.Fatalf("err = %v, want a no-valid-certs error", err) - } - }) -} - -func TestMiddleware(t *testing.T) { - called := false - next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - called = true - w.WriteHeader(http.StatusOK) - }) - - cases := []struct { - name string - state *tls.ConnectionState - want int - }{ - {"plaintext request", nil, http.StatusUnauthorized}, - {"TLS without a verified chain", &tls.ConnectionState{}, http.StatusUnauthorized}, - {"TLS with a verified chain", &tls.ConnectionState{VerifiedChains: [][]*x509.Certificate{{}}}, http.StatusOK}, - } - - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - called = false - req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/captures/cap-1/status", nil) - req.TLS = tc.state - rr := httptest.NewRecorder() - - Middleware(next).ServeHTTP(rr, req) - - if rr.Code != tc.want { - t.Fatalf("status = %d, want %d", rr.Code, tc.want) - } - if called != (tc.want == http.StatusOK) { - t.Fatalf("next called = %v, want %v", called, tc.want == http.StatusOK) - } - }) - } -} - -// TestServerTLSRejectsClientWithoutCertificate drives a real TLS handshake -// against a listener configured by ServerTLS. The middleware alone cannot -// prove mTLS is enforced - only the TLS layer refuses a client that presents -// no certificate at all, and that is the sidecar's actual security boundary. -func TestServerTLSRejectsClientWithoutCertificate(t *testing.T) { - ca := newTestCA(t) - serverCert, serverKey := ca.issue(t, "capture-sidecar") - clientCert, clientKey := ca.issue(t, "gameplane-operator") - - cfg, err := ServerTLS(serverCert, serverKey, ca.certPath) - if err != nil { - t.Fatalf("ServerTLS: %v", err) - } - - listener, err := tls.Listen("tcp", "127.0.0.1:0", cfg) - if err != nil { - t.Fatalf("listen: %v", err) - } - handler := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(http.StatusOK) - }) - srv := &http.Server{ - Handler: Middleware(handler), - ReadHeaderTimeout: 5 * time.Second, - } - go func() { _ = srv.Serve(listener) }() - t.Cleanup(func() { _ = srv.Close() }) - - url := "https://" + listener.Addr().String() + "/captures/cap-1/status" - - t.Run("no client certificate is refused at the TLS layer", func(t *testing.T) { - client := httpClient(t, nil) - req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, url, nil) - if err != nil { - t.Fatalf("new request: %v", err) - } - resp, err := client.Do(req) - if err == nil { - _ = resp.Body.Close() - t.Fatalf("request succeeded with status %d; want a TLS failure", resp.StatusCode) - } - }) - - t.Run("a CA-signed client certificate is accepted", func(t *testing.T) { - pair, err := tls.LoadX509KeyPair(clientCert, clientKey) - if err != nil { - t.Fatalf("load client keypair: %v", err) - } - client := httpClient(t, &pair) - req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, url, nil) - if err != nil { - t.Fatalf("new request: %v", err) - } - resp, err := client.Do(req) - if err != nil { - t.Fatalf("request failed: %v", err) - } - defer func() { _ = resp.Body.Close() }() - if resp.StatusCode != http.StatusOK { - t.Fatalf("status = %d, want 200", resp.StatusCode) - } - }) -} - -// helpers - -// httpClient builds a client that skips server-name verification (the test -// certificates carry no SANs) but presents cert, if any, to the server. Only -// the server's client-certificate enforcement is under test here. -func httpClient(t *testing.T, cert *tls.Certificate) *http.Client { - t.Helper() - cfg := &tls.Config{ - InsecureSkipVerify: true, - MinVersion: tls.VersionTLS12, - MaxVersion: tls.VersionTLS12, - } - if cert != nil { - cfg.Certificates = []tls.Certificate{*cert} - } - transport := &http.Transport{TLSClientConfig: cfg} - t.Cleanup(transport.CloseIdleConnections) - return &http.Client{Transport: transport, Timeout: 10 * time.Second} -} - -func writeFile(t *testing.T, path, content string) { - t.Helper() - if err := os.WriteFile(path, []byte(content), 0o600); err != nil { - t.Fatalf("write %s: %v", path, err) - } -} - -// testCA is a throwaway certificate authority that issues the server and -// client certificates used by these tests. -type testCA struct { - dir string - certPath string - cert *x509.Certificate - key *ecdsa.PrivateKey -} - -func newTestCA(t *testing.T) *testCA { - t.Helper() - key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - if err != nil { - t.Fatalf("generate CA key: %v", err) - } - tmpl := &x509.Certificate{ - SerialNumber: big.NewInt(1), - Subject: pkix.Name{CommonName: "gameplane-test-ca"}, - NotBefore: time.Now().Add(-time.Hour), - NotAfter: time.Now().Add(time.Hour), - KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature, - BasicConstraintsValid: true, - IsCA: true, - } - der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key) - if err != nil { - t.Fatalf("create CA certificate: %v", err) - } - cert, err := x509.ParseCertificate(der) - if err != nil { - t.Fatalf("parse CA certificate: %v", err) - } - - dir := t.TempDir() - certPath := filepath.Join(dir, "ca.crt") - writeFile(t, certPath, string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}))) - - return &testCA{dir: dir, certPath: certPath, cert: cert, key: key} -} - -// issue writes a CA-signed keypair usable for both server and client auth. -func (c *testCA) issue(t *testing.T, name string) (certPath, keyPath string) { - t.Helper() - key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - if err != nil { - t.Fatalf("generate key for %s: %v", name, err) - } - tmpl := &x509.Certificate{ - SerialNumber: big.NewInt(time.Now().UnixNano()), - Subject: pkix.Name{CommonName: name}, - NotBefore: time.Now().Add(-time.Hour), - NotAfter: time.Now().Add(time.Hour), - KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, - ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth}, - IPAddresses: []net.IP{net.ParseIP("127.0.0.1")}, - BasicConstraintsValid: true, - } - der, err := x509.CreateCertificate(rand.Reader, tmpl, c.cert, &key.PublicKey, c.key) - if err != nil { - t.Fatalf("sign certificate for %s: %v", name, err) - } - keyDER, err := x509.MarshalECPrivateKey(key) - if err != nil { - t.Fatalf("marshal key for %s: %v", name, err) - } - - certPath = filepath.Join(c.dir, name+".crt") - keyPath = filepath.Join(c.dir, name+".key") - writeFile(t, certPath, string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}))) - writeFile(t, keyPath, string(pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER}))) - return certPath, keyPath -} diff --git a/capture-sidecar/internal/capture/afpacket.go b/capture-sidecar/internal/capture/afpacket.go deleted file mode 100644 index 26d8db7ba..000000000 --- a/capture-sidecar/internal/capture/afpacket.go +++ /dev/null @@ -1,289 +0,0 @@ -// Package capture implements live packet capture for the network capture -// sidecar: reading frames off an AF_PACKET socket, compiling and applying a -// BPF filter expression over them, and writing the matched packets out as a -// PCAPNG file. -package capture - -import ( - "context" - "errors" - "fmt" - "sync" - "time" - - "github.com/gopacket/gopacket" - "github.com/gopacket/gopacket/afpacket" - "golang.org/x/net/bpf" -) - -// pollTimeout bounds how long a single AF_PACKET poll blocks before -// ReadPacket rechecks ctx.Done()/closed and retries. -// -// gopacket/afpacket has no native read cancellation: TPacket.ReadPacketData -// only returns once a packet arrives, the poll(2) call errors, or the poll -// times out (returning the exported afpacket.ErrTimeout). Passing a short, -// finite afpacket.OptPollTimeout is what makes ctx cancellation and Close -// responsive, without spinning up a goroutine per read that can outlive its -// caller if the underlying blocking syscall never returns on its own. -const pollTimeout = 250 * time.Millisecond - -// PacketSource is an interface for reading packets. This allows tests to -// inject mock packet sources without requiring root access or a real network -// interface. Real captures use the AF_PACKET implementation; tests can provide -// synthetic packets. -type PacketSource interface { - // ReadPacket returns the next packet and its receive timestamp. - // It blocks until a packet is available or the context is canceled. - // Returns nil packet and non-nil error on context cancellation or I/O error. - ReadPacket(ctx context.Context) (*RawPacket, error) - // Close closes the packet source and releases any resources. - Close() error -} - -// RawPacket represents a single captured network packet. -type RawPacket struct { - // Data is the packet bytes as captured, already truncated to the - // source's snaplen. - Data []byte - - // Timestamp is when the packet was received. - Timestamp time.Time - - // OriginalLength is the length of the frame on the wire, before any - // snaplen truncation. It is what a PCAPNG reader reports as the packet's - // real size, so it must not be derived from len(Data). Zero means the - // source did not report one. - OriginalLength int -} - -// AFPacketSource implements PacketSource using Linux AF_PACKET sockets -// with an mmap'd TPacket buffer for efficient live capture. -type AFPacketSource struct { - handle packetHandle - filterVM *bpf.VM - snaplen uint32 - - mu sync.Mutex - closed bool -} - -type packetHandle interface { - ReadPacketData() ([]byte, gopacket.CaptureInfo, error) - Close() -} - -// NewAFPacketSource creates a new AF_PACKET packet source listening on -// the specified interface with the given snaplen (maximum captured packet size). -// The BPF filter (if non-empty) is compiled and loaded into the kernel. -func NewAFPacketSource(iface string, snaplen uint32, bpfFilter string) (*AFPacketSource, error) { - if snaplen == 0 { - snaplen = DefaultSnaplen - } - // Prepare both copies of the same filter before opening a receiving socket. - // NewTPacket activates reception before SetBPF is available, so packets - // queued during setup must also pass the VM before they can leave ReadPacket. - var raw []bpf.RawInstruction - var filterVM *bpf.VM - if bpfFilter != "" { - f, err := CompileFilter(bpfFilter) - if err != nil { - return nil, fmt.Errorf("compile BPF filter: %w", err) - } - raw, err = bpf.Assemble(f.Instructions()) - if err != nil { - return nil, fmt.Errorf("assemble BPF filter: %w", err) - } - filterVM, err = bpf.NewVM(f.Instructions()) - if err != nil { - return nil, fmt.Errorf("prepare BPF output filter: %w", err) - } - } - - // Open an AF_PACKET TPacket socket bound to the specified interface. - // The interface is selected via afpacket.OptInterface at construction - // time; TPacket has no SetInterface/SetSnaplen setters (verified against - // github.com/gopacket/gopacket@v1.7.2/afpacket/{afpacket,options}.go: - // NewTPacket at afpacket.go:261, OptInterface at options.go:80, - // OptPollTimeout at options.go:100). - // OptPollTimeout bounds each internal poll(2) call so ReadPacketData - // returns periodically (afpacket.ErrTimeout) instead of blocking forever, - // which is what ReadPacket below relies on for ctx cancellation. - handle, err := afpacket.NewTPacket( - afpacket.OptInterface(iface), - afpacket.OptPollTimeout(pollTimeout), - ) - if err != nil { - return nil, fmt.Errorf("open AF_PACKET socket on %s: %w", iface, err) - } - - // Kernel filtering remains the primary filter. It cannot retroactively - // remove frames already queued in the ring before this call. - if len(raw) > 0 { - if err := handle.SetBPF(raw); err != nil { - handle.Close() - return nil, fmt.Errorf("set BPF filter: %w", err) - } - } - - return &AFPacketSource{ - handle: handle, - filterVM: filterVM, - snaplen: snaplen, - }, nil -} - -// ReadPacket reads the next available packet from the AF_PACKET socket. -// It blocks until a packet arrives or the context is canceled. -// -// TPacket.ReadPacketData has no cancellation of its own, so this loops on -// the bounded-timeout poll configured in NewAFPacketSource: every pollTimeout -// interval with no packet, ReadPacketData returns afpacket.ErrTimeout, and -// the loop rechecks ctx.Done()/closed before polling again. This keeps -// cancellation responsive without ever leaving a goroutine blocked on a -// syscall past the point the caller stopped waiting for it. -func (a *AFPacketSource) ReadPacket(ctx context.Context) (*RawPacket, error) { - for { - select { - case <-ctx.Done(): - return nil, fmt.Errorf("context canceled: %w", ctx.Err()) - default: - } - - a.mu.Lock() - if a.closed { - a.mu.Unlock() - return nil, fmt.Errorf("packet source is closed") - } - handle := a.handle - a.mu.Unlock() - - data, ci, err := handle.ReadPacketData() - if err != nil { - if errors.Is(err, afpacket.ErrTimeout) { - // No packet within pollTimeout; loop back and recheck - // ctx/closed rather than treating this as a read failure. - continue - } - return nil, fmt.Errorf("read packet: %w", err) - } - // Evaluate the original frame, before snaplen can remove bytes the - // filter examines. This also rejects unfiltered startup-ring packets. - if a.filterVM != nil { - accepted, err := a.filterVM.Run(data) - if err != nil { - return nil, fmt.Errorf("evaluate BPF output filter: %w", err) - } - if accepted == 0 { - continue - } - } - - if a.snaplen > 0 && int64(len(data)) > int64(a.snaplen) { - data = data[:a.snaplen] - } - // ci.Length is the frame's length on the wire (afpacket fills it from - // the ring-buffer header's tp_len, not from the captured slice), so it - // survives both the kernel's snaplen and the truncation above. - return &RawPacket{ - Data: data, - Timestamp: ci.Timestamp, - OriginalLength: ci.Length, - }, nil - } -} - -// Close closes the AF_PACKET socket and releases the mmap'd buffer. -func (a *AFPacketSource) Close() error { - a.mu.Lock() - defer a.mu.Unlock() - - if a.closed { - return nil - } - a.closed = true - - // (*afpacket.TPacket).Close returns no value (verified against - // github.com/gopacket/gopacket@v1.7.2/afpacket/afpacket.go:243); it just - // munmaps the ring buffer and closes the fd. - a.handle.Close() - return nil -} - -// Capturer manages packet capture from a PacketSource. -// It reads packets from the source and delivers them to the Writer for recording. -type Capturer struct { - source PacketSource - mu sync.Mutex - closed bool -} - -// NewCapturer creates a new Capturer using the provided PacketSource. -// This design allows tests to inject mock sources without requiring root or a real interface. -func NewCapturer(source PacketSource) *Capturer { - return &Capturer{ - source: source, - } -} - -// Start validates that the capturer may begin: it rejects a capturer that is -// already closed and honors an already-canceled/expired ctx up front, so a -// caller that raced a start against its own shutdown gets a clear error -// instead of silently proceeding. The actual packet reads happen in -// ReadPackets, which takes its own ctx and is what makes cancellation of an -// in-progress capture responsive. -func (c *Capturer) Start(ctx context.Context) error { - c.mu.Lock() - defer c.mu.Unlock() - - if c.closed { - return fmt.Errorf("capturer is closed") - } - if err := ctx.Err(); err != nil { - return fmt.Errorf("start capturer: %w", err) - } - return nil -} - -// Stop closes the Capturer. -func (c *Capturer) Stop() error { - c.mu.Lock() - defer c.mu.Unlock() - - if c.closed { - return nil - } - c.closed = true - - if err := c.source.Close(); err != nil { - return fmt.Errorf("close packet source: %w", err) - } - return nil -} - -// ReadPackets reads packets from the source and delivers them to a callback. -// It runs until the context is canceled or an error occurs. -func (c *Capturer) ReadPackets(ctx context.Context, callback func(*RawPacket) error) error { - c.mu.Lock() - if c.closed { - c.mu.Unlock() - return fmt.Errorf("capturer is closed") - } - c.mu.Unlock() - - for { - select { - case <-ctx.Done(): - return ctx.Err() - default: - } - - pkt, err := c.source.ReadPacket(ctx) - if err != nil { - return fmt.Errorf("read packet: %w", err) - } - - if err := callback(pkt); err != nil { - return fmt.Errorf("packet callback failed: %w", err) - } - } -} diff --git a/capture-sidecar/internal/capture/afpacket_filter_test.go b/capture-sidecar/internal/capture/afpacket_filter_test.go deleted file mode 100644 index 927ad4bc7..000000000 --- a/capture-sidecar/internal/capture/afpacket_filter_test.go +++ /dev/null @@ -1,176 +0,0 @@ -package capture - -import ( - "bytes" - "context" - "errors" - "io" - "net" - "strings" - "testing" - "time" - - "github.com/gopacket/gopacket" - "github.com/gopacket/gopacket/afpacket" - "github.com/gopacket/gopacket/layers" - "golang.org/x/net/bpf" -) - -type queuedFrame struct { - data []byte - info gopacket.CaptureInfo - err error -} - -// queuedPacketHandle models frames already resident in the packet ring when -// the kernel filter is attached. Attaching BPF cannot remove these frames. -type queuedPacketHandle struct { - frames []queuedFrame - reads int - closes int - afterRead func() -} - -func (h *queuedPacketHandle) ReadPacketData() ([]byte, gopacket.CaptureInfo, error) { - h.reads++ - if h.afterRead != nil { - h.afterRead() - } - if len(h.frames) == 0 { - return nil, gopacket.CaptureInfo{}, io.EOF - } - frame := h.frames[0] - h.frames = h.frames[1:] - return frame.data, frame.info, frame.err -} - -func (h *queuedPacketHandle) Close() { h.closes++ } - -func captureTCPFrame(t *testing.T, source, destination layers.TCPPort) []byte { - t.Helper() - ethernet := &layers.Ethernet{ - SrcMAC: net.HardwareAddr{0, 1, 2, 3, 4, 5}, DstMAC: net.HardwareAddr{6, 7, 8, 9, 10, 11}, - EthernetType: layers.EthernetTypeIPv4, - } - ip := &layers.IPv4{Version: 4, IHL: 5, TTL: 64, Protocol: layers.IPProtocolTCP, - SrcIP: net.IPv4(10, 0, 0, 1), DstIP: net.IPv4(10, 0, 0, 2)} - tcp := &layers.TCP{SrcPort: source, DstPort: destination, SYN: true, Seq: 1, Window: 1024} - if err := tcp.SetNetworkLayerForChecksum(ip); err != nil { - t.Fatal(err) - } - buffer := gopacket.NewSerializeBuffer() - if err := gopacket.SerializeLayers(buffer, gopacket.SerializeOptions{FixLengths: true, ComputeChecksums: true}, ethernet, ip, tcp); err != nil { - t.Fatal(err) - } - return buffer.Bytes() -} - -func captureFilterVM(t *testing.T) *bpf.VM { - t.Helper() - filter, err := CompileFilter("tcp port 12345") - if err != nil { - t.Fatal(err) - } - vm, err := bpf.NewVM(filter.Instructions()) - if err != nil { - t.Fatal(err) - } - return vm -} - -func TestAFPacketSourceRejectsQueuedControlTrafficBeforeOutput(t *testing.T) { - for _, test := range []struct { - name string - source layers.TCPPort - destination layers.TCPPort - snaplen uint32 - }{ - {"inbound game frame", 54606, 12345, DefaultSnaplen}, - {"outbound game frame", 12345, 54606, DefaultSnaplen}, - {"filter before short snaplen", 54606, 12345, 14}, - } { - t.Run(test.name, func(t *testing.T) { - control := captureTCPFrame(t, 9091, 54606) - game := captureTCPFrame(t, test.source, test.destination) - timestamp := time.Unix(1_700_000_000, 123456789) - handle := &queuedPacketHandle{frames: []queuedFrame{ - {data: control, info: gopacket.CaptureInfo{Timestamp: timestamp.Add(-time.Second), Length: len(control)}}, - {data: game, info: gopacket.CaptureInfo{Timestamp: timestamp, Length: len(game)}}, - }} - source := &AFPacketSource{handle: handle, filterVM: captureFilterVM(t), snaplen: test.snaplen} - packet, err := source.ReadPacket(t.Context()) - if err != nil { - t.Fatal(err) - } - want := game - if int(test.snaplen) < len(want) { - want = want[:test.snaplen] - } - if handle.reads != 2 || !bytes.Equal(packet.Data, want) || packet.OriginalLength != len(game) || !packet.Timestamp.Equal(timestamp) { - t.Fatalf("queued control packet escaped or accepted metadata changed: reads=%d packet=%+v", handle.reads, packet) - } - }) - } -} - -func TestAFPacketSourceCancellationWhileDiscarding(t *testing.T) { - ctx, cancel := context.WithCancel(t.Context()) - defer cancel() - handle := &queuedPacketHandle{frames: []queuedFrame{ - {data: captureTCPFrame(t, 9091, 54606)}, - {data: captureTCPFrame(t, 12345, 54606)}, - }, afterRead: cancel} - source := &AFPacketSource{handle: handle, filterVM: captureFilterVM(t)} - packet, err := source.ReadPacket(ctx) - if packet != nil || !errors.Is(err, context.Canceled) || handle.reads != 1 { - t.Fatalf("discard loop ignored cancellation: packet=%v err=%v reads=%d", packet, err, handle.reads) - } -} - -func TestAFPacketSourceTimeoutThenHandleError(t *testing.T) { - readErr := errors.New("capture socket failed") - handle := &queuedPacketHandle{frames: []queuedFrame{{err: afpacket.ErrTimeout}, {err: readErr}}} - source := &AFPacketSource{handle: handle, filterVM: captureFilterVM(t)} - packet, err := source.ReadPacket(t.Context()) - if packet != nil || !errors.Is(err, readErr) || handle.reads != 2 { - t.Fatalf("socket error was not preserved: packet=%v err=%v reads=%d", packet, err, handle.reads) - } -} - -func TestAFPacketSourceVMErrorFailsClosed(t *testing.T) { - // NegateA assembles successfully but is not implemented by x/net/bpf's - // VM. Use that real VM error path rather than an artificial filter hook. - vm, err := bpf.NewVM([]bpf.Instruction{bpf.NegateA{}, bpf.RetConstant{Val: 65535}}) - if err != nil { - t.Fatal(err) - } - handle := &queuedPacketHandle{frames: []queuedFrame{{data: captureTCPFrame(t, 12345, 54606)}}} - source := &AFPacketSource{handle: handle, filterVM: vm} - packet, err := source.ReadPacket(t.Context()) - if packet != nil || err == nil || !strings.Contains(err.Error(), "evaluate BPF output filter") || handle.reads != 1 { - t.Fatalf("VM error did not fail closed: packet=%v err=%v reads=%d", packet, err, handle.reads) - } -} - -func TestAFPacketSourceInvalidFilterRejectedBeforeOpen(t *testing.T) { - // Neither privileges nor an interface should be needed to reject syntax. - source, err := NewAFPacketSource("no-such-interface", DefaultSnaplen, "tcp port definitely-not-a-port") - if source != nil || err == nil || !strings.Contains(err.Error(), "compile BPF filter") { - t.Fatalf("invalid filter reached socket creation: source=%v err=%v", source, err) - } -} - -func TestAFPacketSourceCloseIsIdempotent(t *testing.T) { - handle := &queuedPacketHandle{} - source := &AFPacketSource{handle: handle} - if err := source.Close(); err != nil { - t.Fatal(err) - } - if err := source.Close(); err != nil { - t.Fatal(err) - } - packet, err := source.ReadPacket(t.Context()) - if handle.closes != 1 || handle.reads != 0 || packet != nil || err == nil { - t.Fatalf("closed source touched handle: closes=%d reads=%d packet=%v err=%v", handle.closes, handle.reads, packet, err) - } -} diff --git a/capture-sidecar/internal/capture/afpacket_test.go b/capture-sidecar/internal/capture/afpacket_test.go deleted file mode 100644 index 046c21e5b..000000000 --- a/capture-sidecar/internal/capture/afpacket_test.go +++ /dev/null @@ -1,179 +0,0 @@ -package capture - -import ( - "context" - "errors" - "sync" - "testing" - "time" -) - -// fakePacketSource is an in-memory PacketSource used to exercise Capturer -// without requiring root, CAP_NET_RAW, or a real network interface. -type fakePacketSource struct { - mu sync.Mutex - packets []*RawPacket - idx int - closed bool - closeCh chan struct{} -} - -func newFakePacketSource(packets []*RawPacket) *fakePacketSource { - return &fakePacketSource{ - packets: packets, - closeCh: make(chan struct{}), - } -} - -func (f *fakePacketSource) ReadPacket(ctx context.Context) (*RawPacket, error) { - f.mu.Lock() - if f.closed { - f.mu.Unlock() - return nil, errors.New("packet source is closed") - } - if f.idx < len(f.packets) { - pkt := f.packets[f.idx] - f.idx++ - f.mu.Unlock() - return pkt, nil - } - f.mu.Unlock() - - // No more synthetic packets: block until the source is closed or the - // caller's context is canceled, mirroring the real AFPacketSource's - // blocking-until-cancel-or-data contract. - select { - case <-ctx.Done(): - return nil, ctx.Err() - case <-f.closeCh: - return nil, errors.New("packet source is closed") - } -} - -func (f *fakePacketSource) Close() error { - f.mu.Lock() - defer f.mu.Unlock() - if f.closed { - return nil - } - f.closed = true - close(f.closeCh) - return nil -} - -// TestCapturer_ReadPackets_DeliversAllPackets verifies that ReadPackets -// delivers every packet from the source to the callback, in order. -func TestCapturer_ReadPackets_DeliversAllPackets(t *testing.T) { - want := []*RawPacket{ - {Data: []byte{0x01}, Timestamp: time.Now()}, - {Data: []byte{0x02}, Timestamp: time.Now()}, - {Data: []byte{0x03}, Timestamp: time.Now()}, - } - source := newFakePacketSource(want) - c := NewCapturer(source) - - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - - var got []*RawPacket - var mu sync.Mutex - done := make(chan error, 1) - go func() { - done <- c.ReadPackets(ctx, func(pkt *RawPacket) error { - mu.Lock() - got = append(got, pkt) - shouldStop := len(got) == len(want) - mu.Unlock() - if shouldStop { - cancel() - } - return nil - }) - }() - - select { - case err := <-done: - if err != nil && !errors.Is(err, context.Canceled) { - t.Fatalf("ReadPackets returned unexpected error: %v", err) - } - case <-time.After(5 * time.Second): - t.Fatal("ReadPackets did not return after all packets were delivered") - } - - mu.Lock() - defer mu.Unlock() - if len(got) != len(want) { - t.Fatalf("got %d packets; want %d", len(got), len(want)) - } - for i := range want { - if string(got[i].Data) != string(want[i].Data) { - t.Errorf("packet %d: got %v; want %v", i, got[i].Data, want[i].Data) - } - } -} - -// TestCapturer_Stop_UnblocksReadPackets verifies that Stop() closes the -// underlying source and causes an in-progress ReadPackets call to return, -// rather than blocking forever. -func TestCapturer_Stop_UnblocksReadPackets(t *testing.T) { - source := newFakePacketSource(nil) // no packets; ReadPacket blocks immediately - c := NewCapturer(source) - - ctx := context.Background() - done := make(chan error, 1) - go func() { - done <- c.ReadPackets(ctx, func(*RawPacket) error { return nil }) - }() - - // Give the goroutine a moment to enter the blocking read. - time.Sleep(50 * time.Millisecond) - - if err := c.Stop(); err != nil { - t.Fatalf("Stop failed: %v", err) - } - - select { - case err := <-done: - if err == nil { - t.Fatal("ReadPackets returned nil error after Stop; want an error unblocking the read") - } - case <-time.After(5 * time.Second): - t.Fatal("ReadPackets did not return after Stop; source close did not unblock it (goroutine leak)") - } -} - -// TestCapturer_Start_RejectsCanceledContext verifies that Start honors an -// already-canceled context rather than silently ignoring it. -func TestCapturer_Start_RejectsCanceledContext(t *testing.T) { - c := NewCapturer(newFakePacketSource(nil)) - - ctx, cancel := context.WithCancel(context.Background()) - cancel() - - if err := c.Start(ctx); err == nil { - t.Fatal("Start with an already-canceled context succeeded; want error") - } -} - -// TestCapturer_Start_RejectsAfterStop verifies that Start fails once the -// capturer has been stopped. -func TestCapturer_Start_RejectsAfterStop(t *testing.T) { - c := NewCapturer(newFakePacketSource(nil)) - if err := c.Stop(); err != nil { - t.Fatalf("Stop failed: %v", err) - } - if err := c.Start(context.Background()); err == nil { - t.Fatal("Start after Stop succeeded; want error") - } -} - -// TestCapturer_Stop_Idempotent verifies that Stop can be called multiple -// times without error. -func TestCapturer_Stop_Idempotent(t *testing.T) { - c := NewCapturer(newFakePacketSource(nil)) - for i := 0; i < 3; i++ { - if err := c.Stop(); err != nil { - t.Fatalf("Stop call %d failed: %v", i, err) - } - } -} diff --git a/capture-sidecar/internal/capture/filter.go b/capture-sidecar/internal/capture/filter.go deleted file mode 100644 index 6c210deb9..000000000 --- a/capture-sidecar/internal/capture/filter.go +++ /dev/null @@ -1,147 +0,0 @@ -package capture - -import ( - "fmt" - "strings" - - "github.com/packetcap/go-pcap/filter" - "golang.org/x/net/bpf" -) - -// Filter represents a compiled BPF filter for packet capture. -// It must be validated before capture starts to provide early rejection -// of invalid expressions (FR-003). -type Filter struct { - instructions []bpf.Instruction // compiled BPF program, ready for bpf.Assemble - expr string // original expression for logging/debugging -} - -// unsupportedProtocolKeywords are protocol keywords the go-pcap expression -// parser accepts but its compiler does not turn into a matching test. -// -// Verified against github.com/packetcap/go-pcap@c86974bbfbcd: every keyword in -// filter/constants.go's subProtocols/protocols map parses, but -// filter/primitive.go's Compile only emits comparisons for tcp, udp, ip, ip6, -// arp and rarp. A primitive qualified by any other keyword — "icmp" being the -// obvious one a user would reach for — compiles to a program with no test in -// it at all, i.e. one that captures every packet on the interface. That is a -// silent correctness failure and a data-exposure footgun: the user believes -// they recorded ICMP and instead recorded the pod's entire network namespace, -// game traffic and control-plane traffic included. Rejecting these keywords -// outright is the only honest behaviour available to us; go-pcap gives no -// signal we could surface instead. -var unsupportedProtocolKeywords = map[string]struct{}{ - "aarp": {}, - "ah": {}, - "atalk": {}, - "decnet": {}, - "decnett": {}, - "esp": {}, - "fddi": {}, - "icmp": {}, - "icmp6": {}, - "igmp": {}, - "igrp": {}, - "ipx": {}, - "iso": {}, - "lat": {}, - "modpl": {}, - "morpc": {}, - "netbeui": {}, - "pim": {}, - "sca": {}, - "stp": {}, - "tr": {}, - "vrrp": {}, - "wlan": {}, -} - -// CompileFilter validates and compiles a BPF filter expression. -// It returns an error immediately if the filter is invalid, ensuring -// invalid filters are rejected before any capture starts (FR-003). -// An empty expression returns an error (no implicit default here); -// callers must construct a default port-based filter if needed. -// -// Beyond syntax, this rejects expressions the underlying compiler cannot -// honour: a filter that would silently capture more than it says is worse than -// no capture at all, so anything that does not compile to a program which -// actually discards non-matching packets is refused. -func CompileFilter(expr string) (*Filter, error) { - if expr == "" { - return nil, fmt.Errorf("filter expression is empty") - } - - if err := rejectUnsupportedKeywords(expr); err != nil { - return nil, err - } - - // Parse the tcpdump-style expression into an AST (github.com/packetcap/go-pcap/filter.Expression), - // then compile that AST down to a BPF program. NewExpression never returns - // an error itself (it returns nil only for an empty string, already - // excluded above); syntax/semantic errors surface from the second Compile - // call, which walks the AST and emits []bpf.Instruction. - elem := filter.NewExpression(expr).Compile() - instructions, err := elem.Compile() - if err != nil { - return nil, fmt.Errorf("invalid filter: %w", err) - } - - if len(instructions) == 0 { - return nil, fmt.Errorf("invalid filter: %q compiled to an empty program", expr) - } - if !testsPacketContents(instructions) { - return nil, fmt.Errorf("invalid filter: %q compiled to a program with no packet test, so it would not restrict the capture at all", expr) - } - - return &Filter{ - instructions: instructions, - expr: expr, - }, nil -} - -// rejectUnsupportedKeywords fails an expression that names a protocol the -// compiler cannot express. Words are taken between whitespace and parentheses, -// which is how go-pcap's own lexer splits them, and a leading backslash is -// stripped because "proto \icmp" is the escaped spelling of the same keyword. -func rejectUnsupportedKeywords(expr string) error { - words := strings.FieldsFunc(expr, func(r rune) bool { - return r == ' ' || r == '\t' || r == '\n' || r == '(' || r == ')' - }) - for _, word := range words { - normalized := strings.ToLower(strings.TrimLeft(word, `\`)) - if _, unsupported := unsupportedProtocolKeywords[normalized]; unsupported { - return fmt.Errorf("invalid filter: protocol %q is not supported; use tcp/udp, host, net or port expressions", normalized) - } - } - return nil -} - -// testsPacketContents reports whether prog actually inspects the packet before -// deciding its fate. A BPF program without a conditional branch has a single -// execution path and therefore one verdict for every packet — it either keeps -// everything or drops everything — which is never what a capture filter is -// asked for. go-pcap produces exactly that shape for the qualifiers its -// compiler does not implement, so this is the structural backstop behind the -// keyword list above. -func testsPacketContents(prog []bpf.Instruction) bool { - for _, ins := range prog { - switch ins.(type) { - case bpf.JumpIf, bpf.JumpIfX: - return true - } - } - return false -} - -// Expression returns the original filter expression string. -func (f *Filter) Expression() string { - return f.expr -} - -// Instructions returns the compiled BPF program as gopacket/x-net's portable -// []bpf.Instruction representation. Callers that need the kernel-consumable -// []bpf.RawInstruction form (e.g. for afpacket.TPacket.SetBPF) must assemble -// it first via golang.org/x/net/bpf.Assemble. -func (f *Filter) Instructions() []bpf.Instruction { - return f.instructions -} diff --git a/capture-sidecar/internal/capture/filter_test.go b/capture-sidecar/internal/capture/filter_test.go deleted file mode 100644 index 55f33567b..000000000 --- a/capture-sidecar/internal/capture/filter_test.go +++ /dev/null @@ -1,149 +0,0 @@ -package capture - -import ( - "strings" - "testing" -) - -// TestCompileFilter_ValidFilter tests that a valid BPF expression is accepted. -func TestCompileFilter_ValidFilter(t *testing.T) { - expr := "tcp port 8080" - f, err := CompileFilter(expr) - if err != nil { - t.Fatalf("CompileFilter(%q) failed: %v", expr, err) - } - if f == nil { - t.Fatal("CompileFilter returned nil Filter with nil error") - } - if f.Expression() != expr { - t.Errorf("Expression() = %q; want %q", f.Expression(), expr) - } - if len(f.Instructions()) == 0 { - t.Error("Instructions() returned empty slice; expected a non-empty compiled BPF program") - } -} - -// TestCompileFilter_InvalidFilter tests that an invalid BPF expression is rejected -// before any capture starts, with a clear error. -func TestCompileFilter_InvalidFilter(t *testing.T) { - // A malformed port primitive fails in the compiler itself, with no name - // resolution involved, so this test asserts on syntax rather than on - // whatever the ambient resolver happens to do with a bogus hostname. - expr := "tcp port notaport" - f, err := CompileFilter(expr) - if err == nil { - t.Fatalf("CompileFilter(%q) succeeded; want error", expr) - } - if f != nil { - t.Error("CompileFilter returned non-nil Filter after error") - } - // Error message must include "invalid filter" per contract. - if !strings.Contains(err.Error(), "invalid filter") { - t.Errorf("error message = %q; want substring 'invalid filter'", err.Error()) - } -} - -// TestCompileFilter_EmptyFilter tests that an empty filter is rejected. -func TestCompileFilter_EmptyFilter(t *testing.T) { - f, err := CompileFilter("") - if err == nil { - t.Fatal("CompileFilter(\"\") succeeded; want error") - } - if f != nil { - t.Error("CompileFilter returned non-nil Filter after error") - } -} - -// TestCompileFilter_VariousValidFilters tests a range of valid BPF expressions. -func TestCompileFilter_VariousValidFilters(t *testing.T) { - tests := []string{ - "tcp port 80", - "udp port 53", - "ip src 192.168.1.1", - "tcp and dst port 443", - "udp port 25565 or tcp port 25565", - "tcp port 22 or tcp port 23", - } - for _, expr := range tests { - t.Run(expr, func(t *testing.T) { - f, err := CompileFilter(expr) - if err != nil { - t.Fatalf("CompileFilter(%q) failed: %v", expr, err) - } - if f == nil { - t.Fatal("CompileFilter returned nil Filter with nil error") - } - if f.Expression() != expr { - t.Errorf("Expression() = %q; want %q", f.Expression(), expr) - } - if len(f.Instructions()) == 0 { - t.Error("Instructions() returned empty slice") - } - }) - } -} - -// TestFilter_NoPartialState ensures the rejection path leaves no partial state. -// This is verified implicitly: if CompileFilter returns an error, f is nil and -// the caller's code path that would store or use the Filter is not reached. -// A direct test would check that a failed compile leaves no file handles or -// goroutines open, but that's verified at the writer and HTTP handler level. -func TestFilter_NoPartialState(t *testing.T) { - // Attempt to compile an invalid filter multiple times. - // Each should cleanly fail with no state leakage between attempts. - for i := 0; i < 3; i++ { - f, err := CompileFilter("udp port notaport") - if err == nil { - t.Fatal("unexpected success") - } - if f != nil { - t.Error("non-nil Filter after error") - } - } -} - -// TestCompileFilter_RejectsUnimplementedProtocols pins down the reason bare -// "icmp" is refused: go-pcap parses it, but its compiler emits no test for it, -// so the resulting BPF program keeps every packet on the interface. Accepting -// such a filter would silently record traffic the user never asked for — game -// payloads, RCON, and the agent's own control-plane traffic — so it must be an -// error rather than a surprise. -func TestCompileFilter_RejectsUnimplementedProtocols(t *testing.T) { - tests := []string{ - "icmp", - "icmp or arp", - "udp port 53 and icmp", - "proto \\icmp", - "ICMP", - "esp", - "vrrp", - } - - for _, expr := range tests { - t.Run(expr, func(t *testing.T) { - f, err := CompileFilter(expr) - if err == nil { - t.Fatalf("CompileFilter(%q) succeeded; want a rejection", expr) - } - if f != nil { - t.Error("CompileFilter returned non-nil Filter after error") - } - if !strings.Contains(err.Error(), "invalid filter") { - t.Errorf("error message = %q; want substring 'invalid filter'", err.Error()) - } - }) - } -} - -// TestCompileFilter_CompiledProgramDiscriminates asserts that an accepted -// filter compiles to a program that actually tests the packet, which is the -// structural backstop behind the keyword list. -func TestCompileFilter_CompiledProgramDiscriminates(t *testing.T) { - f, err := CompileFilter("udp port 25565") - if err != nil { - t.Fatalf("CompileFilter failed: %v", err) - } - if !testsPacketContents(f.Instructions()) { - t.Error("compiled program has no conditional branch; it would match every packet") - } -} diff --git a/capture-sidecar/internal/capture/writer.go b/capture-sidecar/internal/capture/writer.go deleted file mode 100644 index 9acf279df..000000000 --- a/capture-sidecar/internal/capture/writer.go +++ /dev/null @@ -1,351 +0,0 @@ -package capture - -import ( - "errors" - "fmt" - "io" - "os" - "path/filepath" - "sync" - "syscall" - "time" - - "github.com/gopacket/gopacket" - "github.com/gopacket/gopacket/layers" - "github.com/gopacket/gopacket/pcapgo" -) - -// PacketWriter is an interface for writing captured packets to a file. -// This allows tests to inject mock writers without requiring disk I/O. -// Real captures use the Writer implementation; tests can provide synthetic -// failures to exercise error handling paths. -type PacketWriter interface { - // WritePacket writes a single packet to the capture file. - // It returns an error wrapping ErrLimitReached once a hard limit is reached. - WritePacket(pkt *RawPacket) error - // Close finalizes the capture file and closes the underlying file handle. - Close() error - // BytesWritten returns the size of the capture file on disk. - BytesWritten() int64 - // PacketsWritten returns the cumulative number of packets written. - PacketsWritten() int64 - // IsLimitReached returns true if a hard limit has been reached. - IsLimitReached() bool - // LimitReason returns the reason why capture stopped (if a limit was reached). - LimitReason() string -} - -// DefaultSnaplen is the snaplen used when the caller passes 0: a full -// Ethernet frame including jumbo frames, i.e. no truncation in practice. -const DefaultSnaplen uint32 = 65535 - -// MaxCaptureDurationSeconds is the hard upper bound this writer accepts for -// maxDurationSeconds. The sidecar is its own trust boundary — the API tier -// caps requests far lower (1..3600) — and without a bound a caller-supplied -// value large enough to overflow time.Duration (>= ~9.2e9 seconds) turns into -// a negative duration, which makes timers fire immediately and ends the -// capture the instant it starts. 604800s (7 days) is the ratified retention -// maximum, so nothing legitimate needs more. -const MaxCaptureDurationSeconds int64 = 604800 - -// epbFixedOverheadBytes is the on-disk cost of one PCAPNG Enhanced Packet -// Block excluding the packet data and its 4-byte alignment padding: a 28-byte -// header (block type, block length, interface id, timestamp high/low, captured -// length, original length) plus the 4-byte trailing block-length field. -// Verified against github.com/gopacket/gopacket@v1.7.2/pcapgo/ngwrite.go -// (*NgWriter).WritePacketWithOptions, which writes w.buf[:28], the data, the -// padding, then a 4-byte trailer. -const epbFixedOverheadBytes int64 = 32 - -// Limit reasons reported through LimitReason once a hard limit stops a capture. -const ( - LimitReasonDurationReached = "max_duration_reached" - LimitReasonSizeReached = "max_size_reached" - LimitReasonDiskFull = "disk_full" - LimitReasonUserRequested = "user_requested" -) - -// ErrLimitReached is returned by WritePacket as soon as a hard limit is hit — -// including for the very packet that reaches the size limit, which *is* -// written to the file. Callers must treat it as "stop capturing now" rather -// than as a lost packet: returning it from the read loop is what stops a -// capture promptly instead of leaving it nominally running until the next -// packet arrives (which may never happen if traffic goes quiet). Match it with -// errors.Is; LimitReason reports why. -var ErrLimitReached = errors.New("capture limit reached") - -// countingWriter counts the bytes handed to the underlying capture file so the -// writer can enforce maxSizeBytes against real on-disk size rather than -// against packet payload bytes, which ignore per-packet block overhead. -type countingWriter struct { - w io.Writer - n int64 -} - -func (c *countingWriter) Write(p []byte) (int, error) { - n, err := c.w.Write(p) - c.n += int64(n) - if err != nil { - return n, fmt.Errorf("write capture file: %w", err) - } - return n, nil -} - -// Writer writes captured packets to a PCAPNG file and enforces -// duration/size hard limits. Once either limit is reached, the writer -// stops accepting packets and finalizes the file. -type Writer struct { - file *os.File - counter *countingWriter - writer *pcapgo.NgWriter - snaplen uint32 - maxSizeBytes int64 - maxDurationSeconds int64 - startTime time.Time - - mu sync.Mutex - closed bool - bytesWritten int64 - packetsWritten int64 - limitReached bool - limitReason string -} - -// NewWriter creates a new PCAPNG writer that records packets to the specified -// file with the given hard limits on duration and file size. -// -// snaplen is the maximum captured packet size (0 means DefaultSnaplen); every -// packet is truncated to it before being written. filterExpr is the BPF filter -// expression the capture runs with: it is recorded in the file's single -// interface block, so the file documents which traffic it does and does not -// contain. It may be empty when no filter is in force. -func NewWriter(filePath string, maxDurationSeconds int64, maxSizeBytes int64, snaplen uint32, filterExpr string) (*Writer, error) { - if maxDurationSeconds <= 0 { - return nil, fmt.Errorf("maxDurationSeconds must be positive, got %d", maxDurationSeconds) - } - if maxDurationSeconds > MaxCaptureDurationSeconds { - return nil, fmt.Errorf("maxDurationSeconds must be at most %d, got %d", MaxCaptureDurationSeconds, maxDurationSeconds) - } - if maxSizeBytes <= 0 { - return nil, fmt.Errorf("maxSizeBytes must be positive, got %d", maxSizeBytes) - } - if snaplen == 0 { - snaplen = DefaultSnaplen - } - - // Create or truncate the capture file. filePath's only production caller - // (httpserver.Server.captureFilePath) already builds it from a - // regex-validated capture id and re-verifies containment under its - // capture directory before this is ever reached (see that method's doc - // comment) - so there is no untrusted input reaching this open. Clean it - // again here regardless: NewWriter is this package's exported entry - // point, so it must not assume every future caller repeats that - // containment check, and a cleaned path also can't carry a redundant - // ".." that would otherwise resolve outside whatever directory the - // caller intended. - file, err := os.Create(filepath.Clean(filePath)) - if err != nil { - return nil, fmt.Errorf("create capture file %s: %w", filePath, err) - } - - // Initialize the PCAPNG writer with exactly one interface block, whose - // metadata (name, snaplen, filter) describes the interface every packet - // is written against. NewNgWriter would write an anonymous default - // interface of its own and any AddInterface call would then append a - // *second* block that no packet references, so the descriptive form is - // the only correct one here (verified against - // github.com/gopacket/gopacket@v1.7.2/pcapgo/ngwrite.go: NewNgWriter - // delegates to NewNgWriterInterface, which writes the section header and - // then adds the interface it is given). - counter := &countingWriter{w: file} - iface := pcapgo.NgInterface{ - Name: "eth0", - Filter: filterExpr, - LinkType: layers.LinkTypeEthernet, - SnapLength: snaplen, - } - ngWriter, err := pcapgo.NewNgWriterInterface(counter, iface, pcapgo.DefaultNgWriterOptions) - if err != nil { - _ = file.Close() - return nil, fmt.Errorf("initialize PCAPNG writer: %w", err) - } - - // Flush the section and interface blocks now so the counter reflects the - // exact size of the file header, which counts against maxSizeBytes just - // like packet data does. - if err := ngWriter.Flush(); err != nil { - _ = file.Close() - return nil, fmt.Errorf("flush PCAPNG header: %w", err) - } - - return &Writer{ - file: file, - counter: counter, - writer: ngWriter, - snaplen: snaplen, - maxSizeBytes: maxSizeBytes, - maxDurationSeconds: maxDurationSeconds, - startTime: time.Now(), - bytesWritten: counter.n, - }, nil -} - -// WritePacket writes a single packet to the PCAPNG file, truncated to the -// configured snaplen. -// -// It returns an error wrapping ErrLimitReached once a hard limit is reached. -// For the duration limit and for any call after a limit was already reached, -// the packet is rejected without being written. For the size limit, the packet -// that crosses the limit *is* written first — the error says "stop", not "this -// packet was dropped". -func (w *Writer) WritePacket(pkt *RawPacket) error { - w.mu.Lock() - defer w.mu.Unlock() - - if w.closed { - return fmt.Errorf("writer is closed") - } - - // Check if a limit has already been reached. - if w.limitReached { - return fmt.Errorf("capture stopped: %s: %w", w.limitReason, ErrLimitReached) - } - - // Check duration limit (hard stop at or past the limit). - elapsed := time.Since(w.startTime).Seconds() - if elapsed >= float64(w.maxDurationSeconds) { - w.limitReached = true - w.limitReason = LimitReasonDurationReached - return fmt.Errorf("capture stopped: %s: %w", w.limitReason, ErrLimitReached) - } - - // Truncate packet to snaplen if necessary. - packetData := pkt.Data - if int64(len(packetData)) > int64(w.snaplen) { - packetData = packetData[:w.snaplen] - } - - // Length must be the length of the frame on the wire, before both the - // kernel's snaplen truncation and ours. The source reports it on the - // packet; fall back to what we actually hold when it is unset, which - // keeps the CaptureLength <= Length invariant pcapgo enforces. - originalLength := pkt.OriginalLength - if originalLength < len(pkt.Data) { - originalLength = len(pkt.Data) - } - - ci := gopacket.CaptureInfo{ - Timestamp: pkt.Timestamp, - CaptureLength: len(packetData), - Length: originalLength, - InterfaceIndex: 0, - } - - if err := w.writer.WritePacket(ci, packetData); err != nil { - // Check if this is a disk-full error (ENOSPC). - if isENOSPC(err) { - w.limitReached = true - w.limitReason = LimitReasonDiskFull - return fmt.Errorf("disk full during capture: %w", err) - } - return fmt.Errorf("write packet to PCAPNG: %w", err) - } - - // Account for the real on-disk cost of this packet: the Enhanced Packet - // Block header and trailer plus the data padded to a 4-byte boundary. - // Counting payload alone under-reports by ~32 bytes per packet, which for - // small game packets overruns maxSizeBytes by tens of percent. - padding := int64((4 - len(packetData)&3) & 3) - w.bytesWritten += epbFixedOverheadBytes + int64(len(packetData)) + padding - w.packetsWritten++ - - // Check size limit (hard stop at or past the limit). The packet above was - // written; returning ErrLimitReached stops the capture immediately rather - // than waiting for a subsequent packet that may never arrive. - if w.bytesWritten >= w.maxSizeBytes { - w.limitReached = true - w.limitReason = LimitReasonSizeReached - return fmt.Errorf("capture stopped: %s: %w", w.limitReason, ErrLimitReached) - } - - return nil -} - -// Close finalizes the PCAPNG file and closes the underlying file handle. -// This must always produce a valid, complete PCAPNG file, even if called -// mid-capture (e.g., when a hard limit is hit). -// -// The PCAPNG writer buffers, so a full disk usually surfaces here rather than -// from WritePacket; a flush that fails with ENOSPC is therefore recorded as -// the disk_full limit reason as well as returned, so callers report a -// truncated capture as truncated instead of as a clean completion. -func (w *Writer) Close() error { - w.mu.Lock() - defer w.mu.Unlock() - - if w.closed { - return nil - } - w.closed = true - - // The NgWriter.Flush() writes any remaining data. - // The file already has a valid PCAPNG structure with sections and interface blocks, - // so closing the writer produces a complete, valid file. - if err := w.writer.Flush(); err != nil { - if isENOSPC(err) { - w.limitReached = true - w.limitReason = LimitReasonDiskFull - } - _ = w.file.Close() - return fmt.Errorf("flush PCAPNG writer: %w", err) - } - - // Everything the writer buffered has now reached the file, so the counter - // is the authoritative file size. - w.bytesWritten = w.counter.n - - if err := w.file.Close(); err != nil { - return fmt.Errorf("close capture file: %w", err) - } - - return nil -} - -// BytesWritten returns the size of the capture file on disk: the PCAPNG -// header blocks plus every packet block written so far. -func (w *Writer) BytesWritten() int64 { - w.mu.Lock() - defer w.mu.Unlock() - return w.bytesWritten -} - -// PacketsWritten returns the cumulative number of packets written to the file. -func (w *Writer) PacketsWritten() int64 { - w.mu.Lock() - defer w.mu.Unlock() - return w.packetsWritten -} - -// IsLimitReached returns true if a hard limit has been reached. -func (w *Writer) IsLimitReached() bool { - w.mu.Lock() - defer w.mu.Unlock() - return w.limitReached -} - -// LimitReason returns the reason why capture stopped (if a limit was reached). -// Returns an empty string if no limit has been reached. -func (w *Writer) LimitReason() string { - w.mu.Lock() - defer w.mu.Unlock() - return w.limitReason -} - -// isENOSPC checks if an error is a disk-full (ENOSPC) error. Real write -// errors from *os.File/*pcapgo.NgWriter wrap the underlying syscall error -// (typically with a path prefix via *fs.PathError), so this walks the error -// chain with errors.Is rather than comparing error strings, which never -// match once the error has been wrapped. -func isENOSPC(err error) bool { - return errors.Is(err, syscall.ENOSPC) -} diff --git a/capture-sidecar/internal/capture/writer_test.go b/capture-sidecar/internal/capture/writer_test.go deleted file mode 100644 index 4f8c24b21..000000000 --- a/capture-sidecar/internal/capture/writer_test.go +++ /dev/null @@ -1,675 +0,0 @@ -package capture - -import ( - "errors" - "io" - "io/fs" - "os" - "syscall" - "testing" - "time" - - "github.com/gopacket/gopacket/pcapgo" -) - -const testFilter = "udp port 25565" - -// TestWriter_NormalStop tests that a normal stop produces a valid file -// openable via gopacket's own reader, and that counters are accurate. -func TestWriter_NormalStop(t *testing.T) { - // Create a temporary file for the test. - tmpFile := t.TempDir() + "/test_normal_stop.pcapng" - - // Create a writer with generous limits. - w, err := NewWriter(tmpFile, 300, 1000000, 65535, testFilter) - if err != nil { - t.Fatalf("NewWriter failed: %v", err) - } - defer w.Close() - - // Write a few test packets. - testPackets := []*RawPacket{ - { - Data: []byte{0x45, 0x00, 0x00, 0x28}, - Timestamp: time.Now(), - }, - { - Data: []byte{0x45, 0x00, 0x00, 0x30, 0x00, 0x01}, - Timestamp: time.Now().Add(1 * time.Millisecond), - }, - { - Data: []byte{0x45, 0x00, 0x00, 0x20}, - Timestamp: time.Now().Add(2 * time.Millisecond), - }, - } - - for _, pkt := range testPackets { - if err := w.WritePacket(pkt); err != nil { - t.Fatalf("WritePacket failed: %v", err) - } - } - - // Verify counters. - if w.PacketsWritten() != int64(len(testPackets)) { - t.Errorf("PacketsWritten() = %d; want %d", w.PacketsWritten(), len(testPackets)) - } - - payloadBytes := int64(len(testPackets[0].Data) + len(testPackets[1].Data) + len(testPackets[2].Data)) - if w.BytesWritten() <= payloadBytes { - t.Errorf("BytesWritten() = %d; want more than the %d payload bytes (file overhead must count)", w.BytesWritten(), payloadBytes) - } - - // Close and verify the file is valid PCAPNG. - if err := w.Close(); err != nil { - t.Fatalf("Close failed: %v", err) - } - - // BytesWritten is the file's real size, not a payload total. - info, err := os.Stat(tmpFile) - if err != nil { - t.Fatalf("stat capture file: %v", err) - } - if info.Size() != w.BytesWritten() { - t.Errorf("BytesWritten() = %d; want the on-disk size %d", w.BytesWritten(), info.Size()) - } - - // Read back the file using gopacket's reader. - f, err := os.Open(tmpFile) - if err != nil { - t.Fatalf("open file for reading: %v", err) - } - defer f.Close() - - reader, err := pcapgo.NewNgReader(f, pcapgo.DefaultNgReaderOptions) - if err != nil { - t.Fatalf("NewNgReader failed: %v", err) - } - - // Count packets read back. - packetsRead := 0 - for { - data, _, err := reader.ReadPacketData() - if err != nil { - if errors.Is(err, io.EOF) { - break - } - t.Fatalf("ReadPacketData failed: %v", err) - } - if len(data) > 0 { - packetsRead++ - } - } - - if packetsRead != len(testPackets) { - t.Errorf("read back %d packets; want %d", packetsRead, len(testPackets)) - } -} - -// TestWriter_SingleInterfaceBlock verifies the file describes exactly one -// interface and that every packet belongs to it. A second, anonymous interface -// block (which is what an extra AddInterface call produces) would leave the -// packets pointing at metadata that describes nothing. -func TestWriter_SingleInterfaceBlock(t *testing.T) { - tmpFile := t.TempDir() + "/test_interface_block.pcapng" - - const snaplen uint32 = 1024 - - w, err := NewWriter(tmpFile, 300, 1000000, snaplen, testFilter) - if err != nil { - t.Fatalf("NewWriter failed: %v", err) - } - - if err := w.WritePacket(&RawPacket{Data: []byte{0x01, 0x02, 0x03}, Timestamp: time.Now()}); err != nil { - t.Fatalf("WritePacket failed: %v", err) - } - if err := w.Close(); err != nil { - t.Fatalf("Close failed: %v", err) - } - - f, err := os.Open(tmpFile) - if err != nil { - t.Fatalf("open file: %v", err) - } - defer f.Close() - - reader, err := pcapgo.NewNgReader(f, pcapgo.DefaultNgReaderOptions) - if err != nil { - t.Fatalf("NewNgReader failed: %v", err) - } - if _, _, err := reader.ReadPacketData(); err != nil { - t.Fatalf("ReadPacketData failed: %v", err) - } - - if reader.NInterfaces() != 1 { - t.Fatalf("file has %d interface blocks; want exactly 1", reader.NInterfaces()) - } - - iface, err := reader.Interface(0) - if err != nil { - t.Fatalf("Interface(0) failed: %v", err) - } - if iface.Name != "eth0" { - t.Errorf("interface name = %q; want %q", iface.Name, "eth0") - } - if iface.SnapLength != snaplen { - t.Errorf("interface snaplen = %d; want %d", iface.SnapLength, snaplen) - } - if iface.Filter != testFilter { - t.Errorf("interface filter = %q; want %q", iface.Filter, testFilter) - } -} - -// TestWriter_RecordsWireLengthAndSnaplen verifies that a truncated packet -// records how long the frame was on the wire, not how much of it was kept. -func TestWriter_RecordsWireLengthAndSnaplen(t *testing.T) { - tmpFile := t.TempDir() + "/test_wire_length.pcapng" - - const snaplen uint32 = 16 - - w, err := NewWriter(tmpFile, 300, 1000000, snaplen, testFilter) - if err != nil { - t.Fatalf("NewWriter failed: %v", err) - } - - pkt := &RawPacket{ - Data: make([]byte, 64), - Timestamp: time.Now(), - OriginalLength: 1500, - } - if err := w.WritePacket(pkt); err != nil { - t.Fatalf("WritePacket failed: %v", err) - } - if err := w.Close(); err != nil { - t.Fatalf("Close failed: %v", err) - } - - f, err := os.Open(tmpFile) - if err != nil { - t.Fatalf("open file: %v", err) - } - defer f.Close() - - reader, err := pcapgo.NewNgReader(f, pcapgo.DefaultNgReaderOptions) - if err != nil { - t.Fatalf("NewNgReader failed: %v", err) - } - - data, ci, err := reader.ReadPacketData() - if err != nil { - t.Fatalf("ReadPacketData failed: %v", err) - } - if len(data) != int(snaplen) { - t.Errorf("captured %d bytes; want the snaplen %d", len(data), snaplen) - } - if ci.CaptureLength != int(snaplen) { - t.Errorf("CaptureLength = %d; want %d", ci.CaptureLength, snaplen) - } - if ci.Length != 1500 { - t.Errorf("Length = %d; want the wire length 1500", ci.Length) - } -} - -// TestWriter_WireLengthFallsBackToPayload verifies that a source which does -// not report an original length still yields a self-consistent file. -func TestWriter_WireLengthFallsBackToPayload(t *testing.T) { - tmpFile := t.TempDir() + "/test_wire_length_fallback.pcapng" - - w, err := NewWriter(tmpFile, 300, 1000000, 65535, testFilter) - if err != nil { - t.Fatalf("NewWriter failed: %v", err) - } - - if err := w.WritePacket(&RawPacket{Data: make([]byte, 20), Timestamp: time.Now()}); err != nil { - t.Fatalf("WritePacket failed: %v", err) - } - if err := w.Close(); err != nil { - t.Fatalf("Close failed: %v", err) - } - - f, err := os.Open(tmpFile) - if err != nil { - t.Fatalf("open file: %v", err) - } - defer f.Close() - - reader, err := pcapgo.NewNgReader(f, pcapgo.DefaultNgReaderOptions) - if err != nil { - t.Fatalf("NewNgReader failed: %v", err) - } - - _, ci, err := reader.ReadPacketData() - if err != nil { - t.Fatalf("ReadPacketData failed: %v", err) - } - if ci.Length != 20 || ci.CaptureLength != 20 { - t.Errorf("CaptureLength/Length = %d/%d; want 20/20", ci.CaptureLength, ci.Length) - } -} - -// TestWriter_SizeLimitCountsFileOverhead tests that the size limit is enforced -// against the real on-disk size — header blocks and per-packet block overhead -// included — and that hitting it stops the capture on the spot rather than on -// the next packet, which may never arrive. -func TestWriter_SizeLimitCountsFileOverhead(t *testing.T) { - tmpFile := t.TempDir() + "/test_size_limit.pcapng" - - const maxSize int64 = 4096 - const payloadSize = 40 - - w, err := NewWriter(tmpFile, 300, maxSize, 65535, testFilter) - if err != nil { - t.Fatalf("NewWriter failed: %v", err) - } - defer w.Close() - - headerBytes := w.BytesWritten() - if headerBytes <= 0 { - t.Fatalf("BytesWritten() = %d before any packet; want the PCAPNG header size", headerBytes) - } - - testPacket := &RawPacket{ - Data: make([]byte, payloadSize), - Timestamp: time.Now(), - } - - written := int64(0) - for i := 0; i < 1000; i++ { - err := w.WritePacket(testPacket) - if err != nil { - if !errors.Is(err, ErrLimitReached) { - t.Fatalf("WritePacket failed unexpectedly: %v", err) - } - // The packet that crosses the limit is still written. - written++ - break - } - written++ - } - - if written == 0 { - t.Fatal("no packets were written before the size limit") - } - if !w.IsLimitReached() { - t.Fatal("size limit was not reached") - } - if w.LimitReason() != LimitReasonSizeReached { - t.Errorf("LimitReason() = %q; want %q", w.LimitReason(), LimitReasonSizeReached) - } - - // Each packet costs its payload plus the enhanced-packet-block overhead; - // payloadSize is 4-byte aligned, so there is no padding to account for. - wantBytes := headerBytes + written*(epbFixedOverheadBytes+payloadSize) - if w.BytesWritten() != wantBytes { - t.Errorf("BytesWritten() = %d; want %d (%d packets plus %d header bytes)", w.BytesWritten(), wantBytes, written, headerBytes) - } - if w.BytesWritten() < maxSize { - t.Errorf("BytesWritten() = %d; want at least the limit %d", w.BytesWritten(), maxSize) - } - if payloadOnly := written * payloadSize; payloadOnly >= maxSize { - t.Errorf("payload alone (%d bytes) already reached the limit; the test cannot show overhead is counted", payloadOnly) - } - - // A further packet is rejected outright. - err = w.WritePacket(testPacket) - if !errors.Is(err, ErrLimitReached) { - t.Errorf("WritePacket after the limit = %v; want ErrLimitReached", err) - } - - // Close and verify the file is valid and no larger than we reported. - if err := w.Close(); err != nil { - t.Fatalf("Close failed: %v", err) - } - - info, err := os.Stat(tmpFile) - if err != nil { - t.Fatalf("stat capture file: %v", err) - } - if info.Size() != wantBytes { - t.Errorf("on-disk size = %d; want the accounted %d", info.Size(), wantBytes) - } - - f, err := os.Open(tmpFile) - if err != nil { - t.Fatalf("open file: %v", err) - } - defer f.Close() - - if _, err := pcapgo.NewNgReader(f, pcapgo.DefaultNgReaderOptions); err != nil { - t.Fatalf("NewNgReader failed: %v", err) - } -} - -// TestWriter_DurationLimitStop tests that a duration limit triggers a clean stop -// and produces a valid file. -// Note: this test uses a short duration for speed, but the actual check in WritePacket -// uses real time.Since(), so we need to wait or simulate time passage. -func TestWriter_DurationLimitStop(t *testing.T) { - tmpFile := t.TempDir() + "/test_duration_limit.pcapng" - - // Create a writer with a very short duration limit (1 second). - // We'll use a generous size limit so size doesn't trigger first. - w, err := NewWriter(tmpFile, 1, 1000000, 65535, testFilter) - if err != nil { - t.Fatalf("NewWriter failed: %v", err) - } - defer w.Close() - - // Write one packet immediately. - testPacket := &RawPacket{ - Data: []byte{0x45, 0x00, 0x00, 0x28}, - Timestamp: time.Now(), - } - - if err := w.WritePacket(testPacket); err != nil { - t.Fatalf("WritePacket failed: %v", err) - } - - // Wait for the duration limit to expire. - time.Sleep(1100 * time.Millisecond) - - // Try to write another packet; it should be rejected. - err = w.WritePacket(testPacket) - if !errors.Is(err, ErrLimitReached) { - t.Fatalf("WritePacket after the duration limit = %v; want ErrLimitReached", err) - } - - if !w.IsLimitReached() { - t.Fatal("duration limit was not reached") - } - - if w.LimitReason() != LimitReasonDurationReached { - t.Errorf("LimitReason() = %q; want %q", w.LimitReason(), LimitReasonDurationReached) - } - - // Close and verify the file is valid. - if err := w.Close(); err != nil { - t.Fatalf("Close failed: %v", err) - } - - f, err := os.Open(tmpFile) - if err != nil { - t.Fatalf("open file: %v", err) - } - defer f.Close() - - _, err = pcapgo.NewNgReader(f, pcapgo.DefaultNgReaderOptions) - if err != nil { - t.Fatalf("NewNgReader failed: %v", err) - } -} - -// TestWriter_RejectsInvalidLimits tests that limits outside the accepted range -// are refused at construction. An unbounded duration is the dangerous case: a -// value large enough to overflow time.Duration turns into a negative one, -// which would end a capture the instant it started. -func TestWriter_RejectsInvalidLimits(t *testing.T) { - tests := []struct { - name string - maxDurationSeconds int64 - maxSizeBytes int64 - }{ - {"zero duration", 0, 1000000}, - {"negative duration", -1, 1000000}, - {"duration above maximum", MaxCaptureDurationSeconds + 1, 1000000}, - {"duration that overflows a time.Duration", 1 << 62, 1000000}, - {"zero size", 300, 0}, - {"negative size", 300, -1}, - } - - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - tmpFile := t.TempDir() + "/test_invalid_limits.pcapng" - w, err := NewWriter(tmpFile, tc.maxDurationSeconds, tc.maxSizeBytes, 65535, testFilter) - if err == nil { - _ = w.Close() - t.Fatal("NewWriter succeeded; want an error") - } - if w != nil { - t.Error("NewWriter returned a non-nil Writer with an error") - } - if _, statErr := os.Stat(tmpFile); statErr == nil { - t.Error("NewWriter left a capture file behind after rejecting its limits") - } - }) - } - - // The documented maximum itself must be accepted. - tmpFile := t.TempDir() + "/test_max_duration.pcapng" - w, err := NewWriter(tmpFile, MaxCaptureDurationSeconds, 1000000, 65535, testFilter) - if err != nil { - t.Fatalf("NewWriter with the maximum duration failed: %v", err) - } - if err := w.Close(); err != nil { - t.Fatalf("Close failed: %v", err) - } -} - -// TestWriter_MidCaptureStop tests that stopping mid-capture (without hitting limits) -// still produces a valid file with correct counters. -func TestWriter_MidCaptureStop(t *testing.T) { - tmpFile := t.TempDir() + "/test_mid_stop.pcapng" - - w, err := NewWriter(tmpFile, 300, 1000000, 65535, testFilter) - if err != nil { - t.Fatalf("NewWriter failed: %v", err) - } - - // Write some packets. - for i := 0; i < 5; i++ { - pkt := &RawPacket{ - Data: []byte{byte(i), 0x45, 0x00}, - Timestamp: time.Now(), - } - if err := w.WritePacket(pkt); err != nil { - t.Fatalf("WritePacket failed: %v", err) - } - } - - // Immediately close without hitting any limits. - if err := w.Close(); err != nil { - t.Fatalf("Close failed: %v", err) - } - - // Verify the file is valid and readable. - f, err := os.Open(tmpFile) - if err != nil { - t.Fatalf("open file: %v", err) - } - defer f.Close() - - reader, err := pcapgo.NewNgReader(f, pcapgo.DefaultNgReaderOptions) - if err != nil { - t.Fatalf("NewNgReader failed: %v", err) - } - - packetsRead := 0 - for { - data, _, err := reader.ReadPacketData() - if err != nil { - if errors.Is(err, io.EOF) { - break - } - t.Fatalf("ReadPacketData failed: %v", err) - } - if len(data) > 0 { - packetsRead++ - } - } - - if packetsRead != 5 { - t.Errorf("read back %d packets; want 5", packetsRead) - } -} - -// TestWriter_PacketCounterAccuracy tests that packet and byte counters -// accurately reflect what was written, including per-packet block overhead -// and the padding that aligns each block to a 4-byte boundary. -func TestWriter_PacketCounterAccuracy(t *testing.T) { - tmpFile := t.TempDir() + "/test_counters.pcapng" - - w, err := NewWriter(tmpFile, 300, 1000000, 65535, testFilter) - if err != nil { - t.Fatalf("NewWriter failed: %v", err) - } - defer w.Close() - - testCases := []struct { - data []byte - want int64 - }{ - {[]byte{0x01, 0x02, 0x03}, epbFixedOverheadBytes + 3 + 1}, - {[]byte{0x04, 0x05, 0x06, 0x07}, epbFixedOverheadBytes + 4}, - {make([]byte, 100), epbFixedOverheadBytes + 100}, - } - - totalBytes := w.BytesWritten() - totalPackets := int64(0) - - for i, tc := range testCases { - pkt := &RawPacket{ - Data: tc.data, - Timestamp: time.Now(), - } - if err := w.WritePacket(pkt); err != nil { - t.Fatalf("WritePacket %d failed: %v", i, err) - } - totalBytes += tc.want - totalPackets++ - - if w.PacketsWritten() != totalPackets { - t.Errorf("after packet %d: PacketsWritten() = %d; want %d", i, w.PacketsWritten(), totalPackets) - } - if w.BytesWritten() != totalBytes { - t.Errorf("after packet %d: BytesWritten() = %d; want %d", i, w.BytesWritten(), totalBytes) - } - } - - if err := w.Close(); err != nil { - t.Fatalf("Close failed: %v", err) - } - - info, err := os.Stat(tmpFile) - if err != nil { - t.Fatalf("stat capture file: %v", err) - } - if info.Size() != totalBytes { - t.Errorf("on-disk size = %d; want the accounted %d", info.Size(), totalBytes) - } -} - -// TestWriter_CloseIdempotent tests that Close() can be called multiple times -// without error (idempotent behavior). -func TestWriter_CloseIdempotent(t *testing.T) { - tmpFile := t.TempDir() + "/test_close_idempotent.pcapng" - - w, err := NewWriter(tmpFile, 300, 1000000, 65535, testFilter) - if err != nil { - t.Fatalf("NewWriter failed: %v", err) - } - - // Close multiple times. - for i := 0; i < 3; i++ { - if err := w.Close(); err != nil { - t.Fatalf("Close call %d failed: %v", i, err) - } - } -} - -// TestWriter_WriteAfterClose tests that writing after Close() returns an error. -func TestWriter_WriteAfterClose(t *testing.T) { - tmpFile := t.TempDir() + "/test_write_after_close.pcapng" - - w, err := NewWriter(tmpFile, 300, 1000000, 65535, testFilter) - if err != nil { - t.Fatalf("NewWriter failed: %v", err) - } - - if err := w.Close(); err != nil { - t.Fatalf("Close failed: %v", err) - } - - pkt := &RawPacket{ - Data: []byte{0x01, 0x02}, - Timestamp: time.Now(), - } - - err = w.WritePacket(pkt) - if err == nil { - t.Fatal("WritePacket after Close should return an error") - } -} - -// enospcWriter simulates a filesystem that has run out of space: every Write -// call fails with syscall.ENOSPC, wrapped the way a real *os.File's write -// error is (via *fs.PathError), so isENOSPC's errors.Is walk is exercised the -// same way it would be against a genuine full disk. -type enospcWriter struct{} - -func (enospcWriter) Write(_ []byte) (int, error) { - return 0, &fs.PathError{Op: "write", Path: "capture.pcapng", Err: syscall.ENOSPC} -} - -// TestWriter_ENOSPCDuringFlushReportsDiskFull simulates a disk that fills up -// mid-capture. pcapgo.NgWriter buffers through a 4096-byte bufio.Writer (see -// github.com/gopacket/gopacket@v1.7.2/pcapgo/ngwrite.go, NewNgWriterInterface -// -> bufio.NewWriter), so a handful of small packets sit in that buffer -// without ever reaching the underlying writer: WritePacket must keep -// succeeding right up until a flush actually hits the full disk, which here -// is forced by Close. That flush failure must be reported as disk_full, not -// as a clean completion, and reading back the file - which on a real full -// disk still holds whatever was durably flushed before the failure, in this -// case just the header the constructor already flushed - must not panic. -func TestWriter_ENOSPCDuringFlushReportsDiskFull(t *testing.T) { - tmpFile := t.TempDir() + "/test_enospc.pcapng" - - w, err := NewWriter(tmpFile, 300, 1_000_000, 65535, testFilter) - if err != nil { - t.Fatalf("NewWriter failed: %v", err) - } - - // Swap the destination the PCAPNG writer's internal bufio.Writer flushes - // to. The real file handle (used by Close's os.File.Close and by the - // read-back below) is untouched, so this only affects where buffered - // bytes go from here on - exactly what happens when a disk fills up - // partway through a capture. - w.counter.w = enospcWriter{} - - testPacket := &RawPacket{ - Data: []byte{0x01, 0x02, 0x03, 0x04}, - Timestamp: time.Now(), - } - for i := 0; i < 3; i++ { - if err := w.WritePacket(testPacket); err != nil { - t.Fatalf("WritePacket %d before any flush reached the full disk: %v", i, err) - } - } - if w.IsLimitReached() { - t.Fatal("limit reached before any flush reached the simulated full disk") - } - - err = w.Close() - if err == nil { - t.Fatal("Close() = nil; want an error from the simulated full disk") - } - if !errors.Is(err, syscall.ENOSPC) { - t.Fatalf("Close() error = %v; want it to wrap syscall.ENOSPC", err) - } - if !w.IsLimitReached() { - t.Fatal("a disk-full flush failure must mark the limit reached") - } - if w.LimitReason() != LimitReasonDiskFull { - t.Errorf("LimitReason() = %q; want %q", w.LimitReason(), LimitReasonDiskFull) - } - - // The on-disk file must still be a valid, readable PCAPNG up to whatever - // was durably flushed - no panic, no corruption of the bytes that did - // make it out. - f, err := os.Open(tmpFile) - if err != nil { - t.Fatalf("open capture file: %v", err) - } - defer f.Close() - if _, err := pcapgo.NewNgReader(f, pcapgo.DefaultNgReaderOptions); err != nil { - t.Fatalf("NewNgReader on the durably-flushed prefix failed: %v", err) - } -} diff --git a/capture-sidecar/internal/httpserver/artifacts.go b/capture-sidecar/internal/httpserver/artifacts.go deleted file mode 100644 index 8eeafa1b7..000000000 --- a/capture-sidecar/internal/httpserver/artifacts.go +++ /dev/null @@ -1,57 +0,0 @@ -package httpserver - -import ( - "encoding/json" - "io" - "net/http" - - "github.com/GameplanePanel/gameplane/capture-sidecar/internal/nodecapture" -) - -// ArtifactRoutes exposes retained node-worker results without any operation -// that can open a raw socket or start privileged work. The Pod is Restricted. -func (s *Server) ArtifactRoutes(mw func(http.Handler) http.Handler) *http.ServeMux { - mux := http.NewServeMux() - if mw == nil { - mw = func(h http.Handler) http.Handler { return h } - } - mux.HandleFunc("GET /healthz", HandleHealthz) - mux.Handle("GET /captures/{id}/status", mw(http.HandlerFunc(s.handleArtifactStatus))) - mux.Handle("GET /v1/targets/{serverUID}/captures/{id}/uids/{captureUID}/file", mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - result, ok := s.artifactResult(r.PathValue("id")) - if !ok || result.Status != "completed" { - http.NotFound(w, r) - return - } - s.HandleBoundDownload(w, r) - }))) - mux.Handle("DELETE /v1/targets/{serverUID}/captures/{id}/uids/{captureUID}/file", mw(http.HandlerFunc(s.HandleBoundDelete))) - return mux -} - -func (s *Server) artifactResult(id string) (nodecapture.Result, bool) { - var result nodecapture.Result - if !validCaptureID(id) { - return result, false - } - f, err := s.openCaptureRegular("capture-" + id + ".result.json") - if err != nil { - return result, false - } - defer func() { _ = f.Close() }() - raw, err := io.ReadAll(io.LimitReader(f, 4097)) - if err != nil || len(raw) > 4096 || json.Unmarshal(raw, &result) != nil || result.CaptureID != id || result.ServerUID != s.serverUID || !captureUIDPattern.MatchString(result.CaptureUID) { - return result, false - } - return result, true -} - -func (s *Server) handleArtifactStatus(w http.ResponseWriter, r *http.Request) { - result, ok := s.artifactResult(r.PathValue("id")) - if !ok || r.Header.Get("X-Gameplane-Server-UID") != result.ServerUID || r.Header.Get("X-Gameplane-Capture-UID") != result.CaptureUID { - http.NotFound(w, r) - return - } - w.Header().Set("Content-Type", "application/json") - _ = json.NewEncoder(w).Encode(result) -} diff --git a/capture-sidecar/internal/httpserver/artifacts_test.go b/capture-sidecar/internal/httpserver/artifacts_test.go deleted file mode 100644 index 959f4d66d..000000000 --- a/capture-sidecar/internal/httpserver/artifacts_test.go +++ /dev/null @@ -1,31 +0,0 @@ -package httpserver - -import ( - "net/http" - "net/http/httptest" - "os" - "path/filepath" - "testing" -) - -func TestArtifactServerCannotStartCaptureAndBindsResult(t *testing.T) { - dir := t.TempDir() - s := NewServer(t.Context(), dir, 0, "server-uid") - routes := s.ArtifactRoutes(nil) - if err := os.WriteFile(filepath.Join(dir, "capture-cap-one.result.json"), []byte(`{"serverUID":"server-uid","captureUID":"capture-uid","captureId":"cap-one","status":"completed"}`), 0o600); err != nil { - t.Fatal(err) - } - for _, test := range []struct { - method, path, uid string - want int - }{{http.MethodPost, "/captures/cap-one/start", "capture-uid", http.StatusNotFound}, {http.MethodGet, "/captures/cap-one/status", "other-uid", http.StatusNotFound}, {http.MethodGet, "/captures/cap-one/status", "capture-uid", http.StatusOK}} { - req := httptest.NewRequestWithContext(t.Context(), test.method, test.path, nil) - req.Header.Set("X-Gameplane-Server-UID", "server-uid") - req.Header.Set("X-Gameplane-Capture-UID", test.uid) - rr := httptest.NewRecorder() - routes.ServeHTTP(rr, req) - if rr.Code != test.want { - t.Fatalf("%s %s: %d %s", test.method, test.path, rr.Code, rr.Body) - } - } -} diff --git a/capture-sidecar/internal/httpserver/handlers.go b/capture-sidecar/internal/httpserver/handlers.go deleted file mode 100644 index eea5abf94..000000000 --- a/capture-sidecar/internal/httpserver/handlers.go +++ /dev/null @@ -1,975 +0,0 @@ -// Package httpserver provides the mTLS-authenticated HTTP control plane -// for the capture sidecar: starting/stopping captures, polling status, -// and downloading completed PCAPNG files. -package httpserver - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "io" - "io/fs" - "log/slog" - "net/http" - "os" - "path/filepath" - "regexp" - "strings" - "sync" - "syscall" - "time" - - "github.com/GameplanePanel/gameplane/capture-sidecar/internal/capture" -) - -const ( - // captureInterface is the network interface the sidecar captures from. - // Game pods have exactly one pod-network interface, so this is fixed - // rather than request-configurable; the PCAPNG file's interface block - // documents it under this name (see capture.NewWriter). - captureInterface = "eth0" - - // maxDurationSecondsLimit is the sidecar's own outer bound on a capture's - // runtime. The API tier caps requests far lower, but the sidecar is a - // separate trust boundary and must not accept a value that overflows - // int64 nanoseconds when multiplied by time.Second: that yields a negative - // duration, and time.AfterFunc fires a negative duration immediately, so - // an absurdly large request would silently produce a zero-length capture. - maxDurationSecondsLimit = 7 * 24 * 60 * 60 - - // stopDrainTimeout bounds how long HandleStop waits for the packet-reading - // goroutine to exit. WriteTimeout is deliberately unset on this server so - // multi-GiB downloads can stream, which means an unbounded wait here would - // hang the request forever with no diagnostic if the read loop ever failed - // to observe cancellation. - stopDrainTimeout = 5 * time.Second - - // maxCompletedRetained bounds the number of finished captures whose - // terminal state is kept in memory for status/stop replay. Only one - // capture runs at a time and the retention reconciler deletes the files, - // so a small ring is ample; it exists purely so a long-lived pod cannot - // accumulate state without bound. - maxCompletedRetained = 16 -) - -// Capture status values reported in the `status` field of every response. -// The operator's NetworkCapture reconciler switches on exactly these strings, -// so they must not drift. -const ( - statusRunning = "running" - statusCompleted = "completed" - statusFailed = "failed" -) - -// Stopping reasons reported in `stoppingReason`. The size- and duration-limit -// reasons are produced by capture.Writer itself and read back through -// LimitReason, so they are deliberately not duplicated here. -const ( - reasonUserRequested = "user_requested" - reasonMaxDuration = "max_duration_reached" - reasonDiskFull = "disk_full" - reasonError = "error" -) - -// captureIDPattern bounds a capture id to a conservative charset before it is -// ever used to build a filesystem path. Ids are operator-generated -// (`cap-`), so nothing exotic has any business reaching the filesystem. -var captureIDPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{1,64}$`) - -// captureState holds the state of a single capture session. -// BytesWritten/PacketsWritten are deliberately not duplicated here: the -// underlying capture.Writer already tracks them under its own mutex, and is -// the single source of truth read by HandleStatus/HandleStop. -type captureState struct { - // Immutable after construction; safe to read without the mutex. - id string - serverUID string - captureUID string - startedAt time.Time - maxDurationSecs int64 - maxSizeBytes int64 - filePath string - - writer capture.PacketWriter - cancel context.CancelFunc - done chan struct{} - timer *time.Timer - - // mu guards the mutable fields below. finish writes them from whichever - // path ends the capture (the duration timer, the packet-reading goroutine, - // or a stop request) while status and stop responses read them, so both - // sides must hold it: CI runs `go test -race`. - mu sync.Mutex - status string - completedAt time.Time - stoppingReason string - message string -} - -// captureSnapshot is a value copy of the mutable half of captureState, taken -// under its mutex so a single response is always internally consistent. -type captureSnapshot struct { - status string - completedAt time.Time - stoppingReason string - message string -} - -// snapshot copies the mutable fields under the capture's mutex. Every read of -// those fields goes through it, so no handler ever touches them unguarded. -func (c *captureState) snapshot() captureSnapshot { - c.mu.Lock() - defer c.mu.Unlock() - return captureSnapshot{ - status: c.status, - completedAt: c.completedAt, - stoppingReason: c.stoppingReason, - message: c.message, - } -} - -// Server manages the capture control plane. -type Server struct { - mu sync.Mutex - currentCapture *captureState - finishingCapture *captureState - completed map[string]*captureState - completedOrder []string - - captureDataDir string - serverUID string - - // budgetBytes is the maximum total bytes (already-retained capture files - // on captureDataDir, plus one new capture's own maxSizeBytes) HandleStart - // will allow before refusing to start (F-187: the volume this directory - // lives on is a size-limited emptyDir, and retained files that are never - // counted here can silently push total usage past that limit and get the - // whole pod evicted). Zero disables the check - used by tests that don't - // exercise it and don't want retained on-disk fixtures from a previous - // case to affect an unrelated one. Production always sets it: see - // cmd/main.go's CAPTURE_VOLUME_BUDGET_BYTES handling, which the operator - // derives from the "captures" emptyDir's own SizeLimit (see - // operator/internal/controller/gameserver_controller.go's - // captureVolumeBudgetBytes) so the two limits can never drift apart. - budgetBytes int64 - - // newSource opens the live packet source for a capture. It is a field - // rather than a direct call to capture.NewAFPacketSource so tests can - // inject a synthetic source - and a failing one - without root, a NIC, or - // CAP_NET_RAW. Production always uses the AF_PACKET implementation wired - // up in NewServer. - newSource func(iface, filterExpr string) (capture.PacketSource, error) - - // baseCtx is the parent for every capture goroutine's context. It is - // deliberately NOT derived from the HTTP request that starts a capture: - // a capture is meant to keep running, independent of that request, until - // it hits its own duration/size limit, is explicitly stopped, or the - // process itself is shutting down. Deriving from r.Context() instead - // would cancel the capture the instant the "started" response finished - // sending, which would silently truncate every capture to ~nothing. Tying - // it to baseCtx instead means process shutdown (see cmd/main.go, which - // passes its signal.NotifyContext here) cancels any still-running capture - // cleanly, rather than leaking its goroutine past server exit. - baseCtx context.Context -} - -// NewServer creates a new capture server. ctx is the parent context for every -// capture goroutine the server starts; cancelling it (e.g. on process -// shutdown) stops all in-flight captures. Pass a context that outlives the -// server's HTTP handling, not a per-request one. budgetBytes is the volume -// budget HandleStart enforces (see the Server.budgetBytes field doc); pass 0 -// to disable the check. -func NewServer(ctx context.Context, captureDataDir string, budgetBytes int64, serverUID ...string) *Server { - s := &Server{ - captureDataDir: filepath.Clean(captureDataDir), - budgetBytes: budgetBytes, - completed: make(map[string]*captureState), - baseCtx: ctx, - } - if len(serverUID) > 0 { - s.serverUID = serverUID[0] - } - s.newSource = func(iface, filterExpr string) (capture.PacketSource, error) { - src, err := capture.NewAFPacketSource(iface, 0, filterExpr) - if err != nil { - return nil, err - } - return src, nil - } - return s -} - -// Routes builds the sidecar's HTTP router, wrapping every capture endpoint in -// mw (the mTLS middleware in production; nil means "no wrapper", for tests). -// -// This lives here rather than in cmd/main.go so a test can exercise the real -// patterns. net/http.ServeMux validates patterns at registration time and -// panics on a bad one - a wildcard segment must be exactly `{name}`, so the -// chi-style `{id}:start` suffix used elsewhere in this project is invalid -// here - and no test that calls the handler functions directly can catch it. -func (s *Server) Routes(mw func(http.Handler) http.Handler) *http.ServeMux { - if mw == nil { - mw = func(next http.Handler) http.Handler { return next } - } - mux := http.NewServeMux() - mux.HandleFunc("GET /healthz", HandleHealthz) - mux.Handle("POST /captures/{id}/start", mw(http.HandlerFunc(s.HandleStart))) - mux.Handle("POST /captures/{id}/stop", mw(http.HandlerFunc(s.HandleStop))) - mux.Handle("GET /captures/{id}/status", mw(http.HandlerFunc(s.HandleStatus))) - mux.Handle("GET /captures/{id}/file", mw(http.HandlerFunc(s.HandleDownload))) - mux.Handle("DELETE /captures/{id}", mw(http.HandlerFunc(s.HandleDelete))) - mux.Handle("GET /v1/targets/{serverUID}/captures/{id}/uids/{captureUID}/file", mw(http.HandlerFunc(s.HandleBoundDownload))) - mux.Handle("DELETE /v1/targets/{serverUID}/captures/{id}/uids/{captureUID}/file", mw(http.HandlerFunc(s.HandleBoundDelete))) - return mux -} - -// HandleHealthz answers a liveness check that reports nothing about the pod, -// the cluster, or any capture. -// -// It is not wrapped in the mTLS auth middleware here (unlike every other -// route), but that does not make it reachable without a client certificate: -// cmd/main.go serves every route, including this one, over the same -// ListenAndServeTLS listener whose TLSConfig requires and verifies a client -// certificate at the TLS handshake, before any request reaches this mux at -// all. Nothing calls this route today - the Kubernetes API does not support -// probes on ephemeral containers, which is what the sidecar always is - so -// it is unauthenticated only in the sense that this file's own middleware -// wrapping does not gate it a second time (F-193). -func HandleHealthz(w http.ResponseWriter, _ *http.Request) { - if _, err := fmt.Fprint(w, "ok"); err != nil { - slog.Error("failed to write healthz response", "err", err) - } -} - -// startRequest represents a POST /captures/{id}/start request body. -type startRequest struct { - ServerUID string `json:"serverUID,omitempty"` - CaptureUID string `json:"captureUID,omitempty"` - Filter string `json:"filter"` - MaxDurationSeconds int64 `json:"maxDurationSeconds"` - MaxSizeBytes int64 `json:"maxSizeBytes"` -} - -// startResponse represents a successful start response. -type startResponse struct { - Status string `json:"status"` - CaptureID string `json:"captureId"` - StartedAt string `json:"startedAt"` - BytesWritten int64 `json:"bytesWritten"` - PacketsWritten int64 `json:"packetsWritten"` -} - -// stopRequest represents a POST /captures/{id}/stop request body. -type stopRequest struct { - Reason string `json:"reason,omitempty"` -} - -// stopResponse represents a successful stop response. -type stopResponse struct { - Status string `json:"status"` - CaptureID string `json:"captureId"` - StartedAt string `json:"startedAt"` - CompletedAt string `json:"completedAt"` - StoppingReason string `json:"stoppingReason"` - Message string `json:"message,omitempty"` - BytesWritten int64 `json:"bytesWritten"` - PacketsWritten int64 `json:"packetsWritten"` - File string `json:"file"` -} - -// statusResponseRunning represents a GET /captures/{id}/status response -// (running state). completedAt and stoppingReason are explicit JSON nulls. -type statusResponseRunning struct { - CaptureID string `json:"captureId"` - Status string `json:"status"` - StartedAt string `json:"startedAt"` - CompletedAt *string `json:"completedAt"` - StoppingReason *string `json:"stoppingReason"` - BytesWritten int64 `json:"bytesWritten"` - PacketsWritten int64 `json:"packetsWritten"` - EstimatedTimeRemainingSeconds int64 `json:"estimatedTimeRemainingSeconds"` - EstimatedBytesRemaining int64 `json:"estimatedBytesRemaining"` -} - -// statusResponseCompleted represents a GET /captures/{id}/status response for -// a capture that has reached a terminal state (completed or failed). -type statusResponseCompleted struct { - CaptureID string `json:"captureId"` - Status string `json:"status"` - StartedAt string `json:"startedAt"` - CompletedAt string `json:"completedAt"` - StoppingReason string `json:"stoppingReason"` - Message string `json:"message,omitempty"` - BytesWritten int64 `json:"bytesWritten"` - PacketsWritten int64 `json:"packetsWritten"` - File string `json:"file"` -} - -// validCaptureID reports whether id is safe to use as a filesystem path -// component. Every handler validates the {id} path value with this before -// using it to build a path under captureDataDir. -func validCaptureID(id string) bool { - return captureIDPattern.MatchString(id) -} - -// captureFilePath returns the on-disk path for a capture's PCAPNG file. -// -// Every caller of this method has already rejected id with validCaptureID -// (letters, digits, '_', '-' only - no '.', so no ".." segment is even -// expressible), so the join below cannot escape captureDataDir today. It is -// still defensively re-verified here, mirroring the containment check in -// agent/internal/files: filepath.Join + Clean the candidate path, then -// require it to fall strictly under captureDataDir (or equal it) by prefix -// comparison on the *cleaned* forms, so that check can never be fooled by a -// literal ".." that made it past validCaptureID some other way (e.g. a -// future caller that forgets to validate). captureDataDir itself is cleaned -// once in NewServer, so both sides of the comparison are in the same form. -func (s *Server) captureFilePath(id string) string { - candidate := filepath.Clean(filepath.Join(s.captureDataDir, fmt.Sprintf("capture-%s.pcapng", id))) - if candidate != s.captureDataDir && !strings.HasPrefix(candidate, s.captureDataDir+string(os.PathSeparator)) { - // Every id reaching here was already validated by validCaptureID, so - // this is unreachable in practice; treat it as a programmer error - // rather than silently falling back to some other path. - panic(fmt.Sprintf("capture id %q resolved outside capture directory", id)) - } - return candidate -} - -// retainedCaptureBytes sums the size of every capture PCAPNG file currently -// on dir. A file only exists here while it is "retained": expiry is -// deletion in this system (the operator's NetworkCapture reconciler deletes -// a capture's file via HandleDelete once its retention window elapses, see -// expireCapture in operator/internal/controller/networkcapture_controller.go), -// so a file this glob finds is by definition not yet expired, and a file -// that has expired and been deleted is by definition absent from this sum - -// no separate age check is needed here. -// -// A file left over from an earlier capture that reused the same id (for -// example after a pod restart and retry of a start that was interrupted -// mid-write) is counted the same as any other retained file: it is real, -// unexpired bytes on the volume, so counting it is harmless and correct, -// even though it will be overwritten rather than accumulate once the retry -// succeeds. -func retainedCaptureBytes(dir string) (int64, error) { - matches, err := filepath.Glob(filepath.Join(dir, "capture-*.pcapng")) - if err != nil { - return 0, fmt.Errorf("glob capture files in %s: %w", dir, err) - } - var total int64 - for _, path := range matches { - info, err := os.Stat(path) - if err != nil { - if errors.Is(err, fs.ErrNotExist) { - // Deleted between the glob and the stat (e.g. a concurrent - // expiry) - it no longer occupies space, so it correctly - // drops out of the sum rather than failing the whole start. - continue - } - return 0, fmt.Errorf("stat %s: %w", path, err) - } - total += info.Size() - } - return total, nil -} - -// rememberCompletedLocked records a finished capture so its terminal state can -// still be served after it stops being the current one. Callers must hold s.mu. -func (s *Server) rememberCompletedLocked(state *captureState) { - if _, dup := s.completed[state.id]; !dup { - s.completedOrder = append(s.completedOrder, state.id) - } - s.completed[state.id] = state - for len(s.completedOrder) > maxCompletedRetained { - delete(s.completed, s.completedOrder[0]) - s.completedOrder = s.completedOrder[1:] - } -} - -// lookup returns the capture with the given id, current or finished. -func (s *Server) lookup(id string) *captureState { - s.mu.Lock() - defer s.mu.Unlock() - if s.currentCapture != nil && s.currentCapture.id == id { - return s.currentCapture - } - return s.completed[id] -} - -// newCaptureContext derives the context that will govern one capture -// goroutine's lifetime. It deliberately returns a child of s.baseCtx (the -// server's own lifetime - see the baseCtx field doc), not of the caller's -// request context: a capture must keep running after the "started" response -// has been sent, and must only stop on its own duration/size limit, an -// explicit stop, or process shutdown. -// -// The unused context.Context parameter (the caller passes r.Context()) exists -// purely so contextcheck's static analysis has a validated context.Context -// value to anchor this function's return to. Without it, the linter's -// whole-program walk cannot see that s.baseCtx already traces back to a -// legitimately inherited context (the one NewServer was constructed with, -// itself signal.NotifyContext wrapping the process's root context in -// cmd/main.go) and independently -// re-flags both the WithCancel call here and every downstream call site -// (including the `go` statement that spawns runCapture) as a "non-inherited -// new context" - even though the break from the request context is -// deliberate, not accidental. This is the pattern the analyzer's own docs -// recommend for exactly this case: https://github.com/kkHAIKE/contextcheck#example. -func (s *Server) newCaptureContext(_ context.Context) (context.Context, context.CancelFunc) { - return context.WithCancel(s.baseCtx) -} - -// HandleStart handles POST /captures/{id}/start requests to begin capturing. -func (s *Server) HandleStart(w http.ResponseWriter, r *http.Request) { - id := r.PathValue("id") - if !validCaptureID(id) { - http.Error(w, "capture id required", http.StatusBadRequest) - return - } - - var req startRequest - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { - http.Error(w, "invalid request body", http.StatusBadRequest) - return - } - - if req.MaxDurationSeconds <= 0 || req.MaxDurationSeconds > maxDurationSecondsLimit { - http.Error(w, "maxDurationSeconds out of range", http.StatusBadRequest) - return - } - if req.MaxSizeBytes <= 0 { - http.Error(w, "maxSizeBytes out of range", http.StatusBadRequest) - return - } - if !s.validStartIdentity(req) { - http.Error(w, "capture identity does not match this server", http.StatusBadRequest) - return - } - - // FR-003 makes the filter optional at the *API* boundary, where an omitted - // filter means "restrict the capture to the game server's own advertised - // ports". Only the control plane knows those ports, so it must materialise - // that default before calling here. The sidecar cannot reconstruct it, and - // must never fall back to "no filter": that records every packet on the pod - // network - the agent's and the API's mTLS traffic, RCON, any plaintext - // protocol - into a file the requester can download, and silently voids the - // contract's guarantee that 100% of packets in the file match the filter. - if req.Filter == "" { - http.Error(w, "filter is required: the control plane must supply the default port filter", http.StatusBadRequest) - return - } - // Validate up front (defense-in-depth; the API tier already validated it) - // so a malformed expression is rejected before any capture resource is - // opened (FR-003). - if _, err := capture.CompileFilter(req.Filter); err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - - s.mu.Lock() - if s.currentCapture != nil || s.finishingCapture != nil { - // Name the capture that is actually running (s.currentCapture.id), - // not the rejected request's id: they differ whenever a second, - // different capture id is requested while one is already in - // progress, and naming the rejected id here would describe a - // capture that never started as "in progress" (F-192). - active := s.currentCapture - if active == nil { - active = s.finishingCapture - } - runningID := active.id - s.mu.Unlock() - http.Error(w, fmt.Sprintf("capture '%s' already in progress", runningID), http.StatusConflict) - return - } - - // F-187: refuse a start that would push the volume past its budget, - // before opening any socket or file. Bytes already on disk from - // retained (not-yet-expired) captures count against the same budget as - // this new capture's own ceiling - counting only the new capture's - // maxSizeBytes, as the check used to, lets retained files accumulate - // past the "captures" emptyDir's real SizeLimit and get the pod evicted - // (see captureVolumeBudgetBytes in - // operator/internal/controller/gameserver_controller.go). - if s.budgetBytes > 0 { - retained, err := retainedCaptureBytes(s.captureDataDir) - if err != nil { - s.mu.Unlock() - slog.Error("failed to compute retained capture bytes", "id", id, "err", err) - http.Error(w, fmt.Sprintf("failed to check capture volume budget: %v", err), http.StatusInternalServerError) - return - } - // Compare without adding: retained is always >= 0 (it is a sum of - // non-negative file sizes) and s.budgetBytes is always > 0 (checked - // above), so budgetBytes-retained cannot overflow. req.MaxSizeBytes - // is attacker/operator controlled and can be as large as - // math.MaxInt64 (a NetworkCapture CR applied directly, bypassing the - // API tier's DefaultMaxSizeBytes clamp, reaches here unclamped via - // nc.Spec.MaxSize.Value()); retained+req.MaxSizeBytes would wrap - // negative in that case and silently defeat this check. - if req.MaxSizeBytes > s.budgetBytes-retained { - s.mu.Unlock() - http.Error(w, fmt.Sprintf( - "capture volume budget exceeded: %d bytes retained + %d bytes requested would exceed the %d byte budget; wait for retained captures to expire or request a smaller maxSizeBytes", - retained, req.MaxSizeBytes, s.budgetBytes, - ), http.StatusInsufficientStorage) - return - } - } - - // Open the live packet source synchronously, before the capture file and - // before the 200. An AF_PACKET open can fail (no CAP_NET_RAW, no such - // interface), and a capture that answered "running" but never opened a - // socket finalises to a valid, empty PCAPNG that the user cannot tell apart - // from "your filter matched nothing" - which the contract's Guarantee 6 - // forbids: a capture that cannot start must return a clear error. - source, err := s.newSource(captureInterface, req.Filter) - if err != nil { - s.mu.Unlock() - slog.Error("failed to open packet source", "id", id, "iface", captureInterface, "err", err) - http.Error(w, fmt.Sprintf("failed to start capture: %v", err), http.StatusInternalServerError) - return - } - - bound, err := s.prepareCaptureBinding(id, req) - if err != nil { - _ = source.Close() - s.mu.Unlock() - if errors.Is(err, fs.ErrExist) { - http.Error(w, "capture name is retained; delete it before reuse", http.StatusConflict) - } else if errors.Is(err, errCaptureIdentityBudget) { - http.Error(w, "capture identity retention budget reached", http.StatusInsufficientStorage) - } else { - slog.Error("failed to bind capture identity", "id", id, "err", err) - http.Error(w, "failed to bind capture identity", http.StatusInternalServerError) - } - return - } - filePath := s.captureFilePath(id) - writer, err := capture.NewWriter(filePath, req.MaxDurationSeconds, req.MaxSizeBytes, 0, req.Filter) - if err != nil { - if bound { - _ = os.Remove(s.captureIdentityPath(id)) - } - _ = source.Close() - s.mu.Unlock() - http.Error(w, fmt.Sprintf("failed to open capture file: %v", err), http.StatusInternalServerError) - return - } - - now := time.Now() - // Derived from s.baseCtx (the server's own lifetime), not r.Context(): see - // the baseCtx field doc for why this must outlive the HTTP request. - ctx, cancel := s.newCaptureContext(r.Context()) - state := &captureState{ - id: id, - serverUID: req.ServerUID, - captureUID: req.CaptureUID, - startedAt: now, - maxDurationSecs: req.MaxDurationSeconds, - maxSizeBytes: req.MaxSizeBytes, - filePath: filePath, - writer: writer, - cancel: cancel, - done: make(chan struct{}), - status: statusRunning, - } - s.currentCapture = state - - // Hard duration cap, independent of the writer's own per-packet duration - // check: a quiet capture that never receives a matching packet must still - // stop on time. It is armed only once the capture is published as current, - // and matches on pointer identity, so a stale timer can never terminate a - // successor capture that happens to reuse the same id. - state.timer = time.AfterFunc(time.Duration(req.MaxDurationSeconds)*time.Second, func() { - s.finish("", state, reasonMaxDuration, nil) - }) - s.mu.Unlock() - - go s.runCapture(ctx, state, source) - - slog.Info("capture started", "id", id, "filter", req.Filter) - - w.Header().Set("Content-Type", "application/json") - if err := json.NewEncoder(w).Encode(startResponse{ - Status: statusRunning, - CaptureID: id, - StartedAt: now.Format(time.RFC3339), - BytesWritten: 0, - PacketsWritten: 0, - }); err != nil { - slog.Error("failed to encode start response", "id", id, "err", err) - } -} - -// runCapture drives one capture session's packet loop. The source is already -// open (HandleStart opens it synchronously so a failure is reported to the -// caller), so this only reads until ctx is canceled - by finish, via an -// explicit stop or the duration timer - or a limit or a real I/O failure ends -// it. It always runs in its own goroutine and always closes state.done. -func (s *Server) runCapture(ctx context.Context, state *captureState, source capture.PacketSource) { - defer close(state.done) - - capturer := capture.NewCapturer(source) - defer func() { _ = capturer.Stop() }() - - if err := capturer.Start(ctx); err != nil { - s.finish("", state, reasonError, err) - return - } - - readErr := capturer.ReadPackets(ctx, func(pkt *capture.RawPacket) error { - return state.writer.WritePacket(pkt) - }) - - switch { - case ctx.Err() != nil: - // finish canceled us; it owns the terminal state. - case errors.Is(readErr, capture.ErrLimitReached): - s.finish("", state, state.writer.LimitReason(), nil) - default: - // A genuine mid-capture failure: link down, socket closed, write - // error. The file already holds real packets and stays downloadable, - // but the capture must not be reported as a clean completion. - // When ENOSPC surfaces from WritePacket (rare, since Close normally - // catches it during flush), check both the error and the writer's - // LimitReason to distinguish disk-full from other errors. - reason := reasonError - if errors.Is(readErr, syscall.ENOSPC) || state.writer.LimitReason() == capture.LimitReasonDiskFull { - reason = reasonDiskFull - } - s.finish("", state, reason, readErr) - } -} - -// finish finalizes a capture and moves it into the completed set so its -// terminal state remains observable: it cancels the capture's context, stops -// its duration timer, and closes the PCAPNG writer so the file is always left -// valid and readable. -// -// Exactly one of target and id selects the capture. target matches on pointer -// identity (used by the timer and the packet goroutine, which must never touch -// a successor capture that reuses the same id); id matches the current -// capture's id (used by HandleStop). finish is idempotent: a capture that has -// already finished, or never existed, returns ok == false without touching -// anything, so a duplicate stop or timeout never double-closes the writer. -// -// failure, when non-nil, marks the capture failed rather than completed. -func (s *Server) finish(id string, target *captureState, reason string, failure error) (*captureState, bool) { - s.mu.Lock() - state := s.currentCapture - matched := state != nil - if matched { - if target != nil { - matched = state == target - } else { - matched = state.id == id - } - } - if !matched { - s.mu.Unlock() - return nil, false - } - s.currentCapture = nil - s.finishingCapture = state - s.rememberCompletedLocked(state) - if state.timer != nil { - state.timer.Stop() - } - s.mu.Unlock() - - state.cancel() - - if reason == "" { - reason = reasonUserRequested - } - status := statusCompleted - message := "" - if failure != nil { - status = statusFailed - message = failure.Error() - } - - // Close before the terminal state is published, so that any observer who - // sees a status other than "running" is guaranteed a fully flushed, closed - // file on disk. Close is also where a full disk actually surfaces: - // pcapgo.NgWriter buffers through a bufio.Writer, so ENOSPC normally - // appears at this final flush rather than at WritePacket, and a capture - // whose file could not be finalized has a truncated tail and must not be - // reported as "completed". - if err := state.writer.Close(); err != nil { - slog.Error("failed to finalize capture file", "id", state.id, "err", err) - status = statusFailed - if errors.Is(err, syscall.ENOSPC) { - reason = reasonDiskFull - } - message = fmt.Sprintf("finalize capture file: %v", err) - } - - state.mu.Lock() - state.status = status - state.completedAt = time.Now() - state.stoppingReason = reason - state.message = message - state.mu.Unlock() - s.mu.Lock() - if s.finishingCapture == state { - s.finishingCapture = nil - } - s.mu.Unlock() - - return state, true -} - -// HandleStop handles POST /captures/{id}/stop requests to end a capture. -func (s *Server) HandleStop(w http.ResponseWriter, r *http.Request) { - id := r.PathValue("id") - if !validCaptureID(id) { - http.Error(w, "capture id required", http.StatusBadRequest) - return - } - - var req stopRequest - // The body is optional. A client that builds the request without an - // explicit ContentLength sends it chunked (ContentLength == -1), so test - // for "not empty" rather than "> 0", and tolerate an empty stream. - if r.ContentLength != 0 && r.Body != nil { - if err := json.NewDecoder(r.Body).Decode(&req); err != nil && !errors.Is(err, io.EOF) { - http.Error(w, "invalid request body", http.StatusBadRequest) - return - } - } - - var target *captureState - if hasControlIdentity(r) { - target = s.lookup(id) - if !s.controlIdentityMatches(r, target) { - http.NotFound(w, r) - return - } - } - state, ok := s.finish(id, target, req.Reason, nil) - if !ok { - // Already finished - by the duration timer, the size limit, or an - // earlier stop. Replay its stored terminal result instead of a 404, so - // the final counters and stopping reason are never lost. - state = s.lookup(id) - if state == nil || !s.controlIdentityMatches(r, state) { - http.Error(w, fmt.Sprintf("capture '%s' not found", id), http.StatusNotFound) - return - } - writeStopResponse(w, state) - return - } - - // Bounded wait for the capture goroutine to exit, so a client that stops - // and immediately polls never observes a terminal response while a packet - // write is still in flight. Bounded, because WriteTimeout is unset on this - // server: an unbounded wait on a stuck read loop would hang forever. - select { - case <-state.done: - case <-time.After(stopDrainTimeout): - slog.Warn("capture goroutine did not exit before the stop deadline", - "id", id, "timeout", stopDrainTimeout) - } - - snap := state.snapshot() - slog.Info("capture stopped", "id", id, "reason", snap.stoppingReason, "status", snap.status) - writeStopResponse(w, state) -} - -// writeStopResponse encodes a capture's terminal state as a stop response. -func writeStopResponse(w http.ResponseWriter, state *captureState) { - snap := state.snapshot() - w.Header().Set("Content-Type", "application/json") - if err := json.NewEncoder(w).Encode(stopResponse{ - Status: snap.status, - CaptureID: state.id, - StartedAt: state.startedAt.Format(time.RFC3339), - CompletedAt: snap.completedAt.Format(time.RFC3339), - StoppingReason: snap.stoppingReason, - Message: snap.message, - BytesWritten: state.writer.BytesWritten(), - PacketsWritten: state.writer.PacketsWritten(), - File: state.filePath, - }); err != nil { - slog.Error("failed to encode stop response", "id", state.id, "err", err) - } -} - -// HandleStatus handles GET /captures/{id}/status requests for capture state. -func (s *Server) HandleStatus(w http.ResponseWriter, r *http.Request) { - id := r.PathValue("id") - if !validCaptureID(id) { - http.Error(w, "capture id required", http.StatusBadRequest) - return - } - - state := s.lookup(id) - if state == nil || !s.controlIdentityMatches(r, state) { - http.Error(w, fmt.Sprintf("capture '%s' not found", id), http.StatusNotFound) - return - } - - snap := state.snapshot() - w.Header().Set("Content-Type", "application/json") - - if snap.status == statusRunning { - elapsed := time.Since(state.startedAt).Seconds() - remaining := float64(state.maxDurationSecs) - elapsed - if remaining < 0 { - remaining = 0 - } - bytesWritten := state.writer.BytesWritten() - if err := json.NewEncoder(w).Encode(statusResponseRunning{ - CaptureID: id, - Status: statusRunning, - StartedAt: state.startedAt.Format(time.RFC3339), - CompletedAt: nil, - StoppingReason: nil, - BytesWritten: bytesWritten, - PacketsWritten: state.writer.PacketsWritten(), - EstimatedTimeRemainingSeconds: int64(remaining), - EstimatedBytesRemaining: state.maxSizeBytes - bytesWritten, - }); err != nil { - slog.Error("failed to encode status response", "id", id, "err", err) - } - return - } - - if err := json.NewEncoder(w).Encode(statusResponseCompleted{ - CaptureID: id, - Status: snap.status, - StartedAt: state.startedAt.Format(time.RFC3339), - CompletedAt: snap.completedAt.Format(time.RFC3339), - StoppingReason: snap.stoppingReason, - Message: snap.message, - BytesWritten: state.writer.BytesWritten(), - PacketsWritten: state.writer.PacketsWritten(), - File: state.filePath, - }); err != nil { - slog.Error("failed to encode status response", "id", id, "err", err) - } -} - -// HandleDownload handles GET /captures/{id}/file requests to download PCAPNG. -func (s *Server) HandleDownload(w http.ResponseWriter, r *http.Request) { - id := r.PathValue("id") - if !validCaptureID(id) { - http.Error(w, "capture id required", http.StatusBadRequest) - return - } - - s.mu.Lock() - running := s.captureBusyLocked(id) - s.mu.Unlock() - - if running { - http.Error(w, "capture is still running", http.StatusConflict) - return - } - - filePath := s.captureFilePath(id) - file, err := os.Open(filepath.Clean(filePath)) - if err != nil { - // 410 is reserved for a capture this sidecar knows about whose file is - // genuinely gone (retention deleted it). Any other open failure - - // EACCES, EIO, EINVAL - is a real server-side fault and must not be - // dressed up as "deleted", which sends an operator down the wrong - // diagnostic path. - if os.IsNotExist(err) { - if s.lookup(id) != nil { - http.Error(w, "capture file has been deleted", http.StatusGone) - return - } - http.Error(w, fmt.Sprintf("capture '%s' not found", id), http.StatusNotFound) - return - } - slog.Error("failed to open capture file", "id", id, "err", err) - http.Error(w, fmt.Sprintf("failed to open capture file: %v", err), http.StatusInternalServerError) - return - } - defer func() { _ = file.Close() }() - - stat, err := file.Stat() - if err != nil { - http.Error(w, "failed to read capture file", http.StatusInternalServerError) - return - } - - name := fmt.Sprintf("capture-%s.pcapng", id) - w.Header().Set("Content-Type", "application/vnd.tcpdump.pcap") - w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", name)) - - // ServeContent streams the file without buffering (a capture can be - // multi-GiB), sets Content-Length and Accept-Ranges, and - unlike a bare - // io.Copy - actually honours a Range header with 206/416 instead of - // silently resending from byte 0 and corrupting a resumed download. - http.ServeContent(w, r, name, stat.ModTime(), file) -} - -// FinalizeCurrentCapture finalizes an in-flight capture on server shutdown. -// If there is a currently-running capture, it stops the capture, closes the -// writer to finalize the PCAPNG file, and moves it into the completed set. -// Called after server.Shutdown to ensure the capture is properly finalized -// instead of leaving the PCAPNG file truncated and unreadable. -func (s *Server) FinalizeCurrentCapture() { - s.mu.Lock() - state := s.currentCapture - s.mu.Unlock() - - if state != nil { - s.finish("", state, reasonUserRequested, nil) - // Wait for the capture goroutine to fully exit, honoring the stop drain - // timeout to avoid hanging if the goroutine is stuck. Log if it times out - // so the operator knows the capture may be truncated. - select { - case <-state.done: - case <-time.After(stopDrainTimeout): - slog.Warn("capture goroutine did not exit before finalization deadline", - "id", state.id, "timeout", stopDrainTimeout) - } - } -} - -// HandleDelete handles DELETE /captures/{id} requests to delete a capture file. -func (s *Server) HandleDelete(w http.ResponseWriter, r *http.Request) { - id := r.PathValue("id") - if !validCaptureID(id) { - http.Error(w, "capture id required", http.StatusBadRequest) - return - } - - s.mu.Lock() - defer s.mu.Unlock() - if hasControlIdentity(r) { - r.SetPathValue("serverUID", r.Header.Get("X-Gameplane-Server-UID")) - r.SetPathValue("captureUID", r.Header.Get("X-Gameplane-Capture-UID")) - if !s.matchCaptureIdentity(r) { - http.NotFound(w, r) - return - } - } - running := s.captureBusyLocked(id) - - if running { - http.Error(w, "capture is still running", http.StatusConflict) - return - } - - filePath := s.captureFilePath(id) - err := os.Remove(filepath.Clean(filePath)) - if err != nil && !errors.Is(err, fs.ErrNotExist) { - slog.Error("failed to delete capture file", "id", id, "err", err) - http.Error(w, fmt.Sprintf("failed to delete capture file: %v", err), http.StatusInternalServerError) - return - } - - slog.Info("capture file deleted", "id", id) - if err := os.Remove(s.captureIdentityPath(id)); err != nil && !errors.Is(err, fs.ErrNotExist) { - slog.Error("failed to delete capture identity", "id", id, "err", err) - http.Error(w, "failed to delete capture identity", http.StatusInternalServerError) - return - } - w.WriteHeader(http.StatusNoContent) -} diff --git a/capture-sidecar/internal/httpserver/handlers_test.go b/capture-sidecar/internal/httpserver/handlers_test.go deleted file mode 100644 index 06151004f..000000000 --- a/capture-sidecar/internal/httpserver/handlers_test.go +++ /dev/null @@ -1,1426 +0,0 @@ -package httpserver - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "io" - "math" - "net/http" - "net/http/httptest" - "os" - "runtime" - "strings" - "sync" - "syscall" - "testing" - "time" - - "github.com/GameplanePanel/gameplane/capture-sidecar/internal/capture" - "github.com/gopacket/gopacket/pcapgo" -) - -// --------------------------------------------------------------------------- -// Test doubles -// --------------------------------------------------------------------------- - -// fakeSource is a synthetic capture.PacketSource. It hands out queued frames -// and then idles until the capture's context is canceled or it is closed, so -// the handler tests can drive the real packet path with no root, no NIC and -// no CAP_NET_RAW. -type fakeSource struct { - mu sync.Mutex - queue [][]byte - closed bool - readErr error -} - -func (f *fakeSource) feed(frames ...[]byte) { - f.mu.Lock() - defer f.mu.Unlock() - f.queue = append(f.queue, frames...) -} - -// failWith makes every subsequent read fail, simulating a link going down -// mid-capture. -func (f *fakeSource) failWith(err error) { - f.mu.Lock() - defer f.mu.Unlock() - f.readErr = err -} - -func (f *fakeSource) ReadPacket(ctx context.Context) (*capture.RawPacket, error) { - for { - f.mu.Lock() - if f.readErr != nil { - err := f.readErr - f.mu.Unlock() - return nil, err - } - if len(f.queue) > 0 { - data := f.queue[0] - f.queue = f.queue[1:] - f.mu.Unlock() - return &capture.RawPacket{Data: data, Timestamp: time.Now()}, nil - } - closed := f.closed - f.mu.Unlock() - - if closed { - return nil, errors.New("fake source closed") - } - select { - case <-ctx.Done(): - return nil, ctx.Err() - case <-time.After(time.Millisecond): - } - } -} - -func (f *fakeSource) Close() error { - f.mu.Lock() - defer f.mu.Unlock() - f.closed = true - return nil -} - -// sourceFactory hands each capture its own fakeSource and remembers them, so a -// test can feed the source that belongs to the capture it just started. -type sourceFactory struct { - mu sync.Mutex - opened []*fakeSource - openErr error -} - -func (sf *sourceFactory) open(_, _ string) (capture.PacketSource, error) { - sf.mu.Lock() - defer sf.mu.Unlock() - if sf.openErr != nil { - return nil, sf.openErr - } - src := &fakeSource{} - sf.opened = append(sf.opened, src) - return src, nil -} - -func (sf *sourceFactory) last(t *testing.T) *fakeSource { - t.Helper() - sf.mu.Lock() - defer sf.mu.Unlock() - if len(sf.opened) == 0 { - t.Fatal("no packet source was opened") - } - return sf.opened[len(sf.opened)-1] -} - -func (sf *sourceFactory) count() int { - sf.mu.Lock() - defer sf.mu.Unlock() - return len(sf.opened) -} - -// --------------------------------------------------------------------------- -// Helpers -// --------------------------------------------------------------------------- - -func newTestServer(t *testing.T) (*Server, *sourceFactory) { - t.Helper() - // budgetBytes 0 disables the F-187 volume-budget check: unrelated tests - // use captureFilePath-derived fixtures that would otherwise interact - // with it. See newTestServerWithBudget for tests that exercise it. - srv := NewServer(context.Background(), t.TempDir(), 0) - factory := &sourceFactory{} - srv.newSource = factory.open - t.Cleanup(func() { - // Never leave an armed duration timer and a live packet goroutine - // behind: they would outlive the test and pollute a later leak check. - srv.mu.Lock() - state := srv.currentCapture - srv.mu.Unlock() - if state != nil { - srv.finish("", state, reasonUserRequested, nil) - <-state.done - } - }) - return srv, factory -} - -func startBody(filter string, durationSeconds, sizeBytes int64) string { - return fmt.Sprintf(`{"filter":%q,"maxDurationSeconds":%d,"maxSizeBytes":%d}`, filter, durationSeconds, sizeBytes) -} - -func doStart(t *testing.T, s *Server, id, body string) *httptest.ResponseRecorder { - t.Helper() - req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/captures/"+id+"/start", strings.NewReader(body)) - req.SetPathValue("id", id) - rr := httptest.NewRecorder() - s.HandleStart(rr, req) - return rr -} - -func doStop(t *testing.T, s *Server, id, body string) *httptest.ResponseRecorder { - t.Helper() - req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/captures/"+id+"/stop", strings.NewReader(body)) - req.SetPathValue("id", id) - rr := httptest.NewRecorder() - s.HandleStop(rr, req) - return rr -} - -func doStatus(t *testing.T, s *Server, id string) *httptest.ResponseRecorder { - t.Helper() - req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/captures/"+id+"/status", nil) - req.SetPathValue("id", id) - rr := httptest.NewRecorder() - s.HandleStatus(rr, req) - return rr -} - -func doDownload(t *testing.T, s *Server, id string, rangeHeader string) *httptest.ResponseRecorder { - t.Helper() - req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/captures/"+id+"/file", nil) - req.SetPathValue("id", id) - if rangeHeader != "" { - req.Header.Set("Range", rangeHeader) - } - rr := httptest.NewRecorder() - s.HandleDownload(rr, req) - return rr -} - -func doDelete(t *testing.T, s *Server, id string) *httptest.ResponseRecorder { - t.Helper() - req := httptest.NewRequestWithContext(t.Context(), http.MethodDelete, "/captures/"+id, nil) - req.SetPathValue("id", id) - rr := httptest.NewRecorder() - s.HandleDelete(rr, req) - return rr -} - -func decodeStop(t *testing.T, rr *httptest.ResponseRecorder) stopResponse { - t.Helper() - var resp stopResponse - if err := json.NewDecoder(rr.Body).Decode(&resp); err != nil { - t.Fatalf("decode stop response: %v", err) - } - return resp -} - -func decodeCompleted(t *testing.T, rr *httptest.ResponseRecorder) statusResponseCompleted { - t.Helper() - var resp statusResponseCompleted - if err := json.NewDecoder(rr.Body).Decode(&resp); err != nil { - t.Fatalf("decode completed status: %v", err) - } - return resp -} - -// frame builds a fixed-size synthetic Ethernet frame filled with marker. -func frame(marker byte) []byte { - data := make([]byte, 64) - for i := range data { - data[i] = marker - } - return data -} - -// waitForPackets polls the status endpoint until the capture reports at least -// want packets, so a test never races the packet-reading goroutine. -func waitForPackets(t *testing.T, s *Server, id string, want int64) { - t.Helper() - deadline := time.Now().Add(5 * time.Second) - for time.Now().Before(deadline) { - rr := doStatus(t, s, id) - if rr.Code == http.StatusOK { - var resp statusResponseRunning - if err := json.NewDecoder(rr.Body).Decode(&resp); err == nil && resp.PacketsWritten >= want { - return - } - } - time.Sleep(5 * time.Millisecond) - } - t.Fatalf("capture %s never reported %d packets", id, want) -} - -// waitForTerminal polls until the capture leaves the running state. -func waitForTerminal(t *testing.T, s *Server, id string) statusResponseCompleted { - t.Helper() - deadline := time.Now().Add(5 * time.Second) - for time.Now().Before(deadline) { - rr := doStatus(t, s, id) - if rr.Code == http.StatusOK && !strings.Contains(rr.Body.String(), `"status":"running"`) { - return decodeCompleted(t, rr) - } - time.Sleep(5 * time.Millisecond) - } - t.Fatalf("capture %s never reached a terminal state", id) - return statusResponseCompleted{} -} - -// readPCAPNG re-reads a finalized capture with gopacket's PCAPNG reader, which -// is an implementation independent of the writer's own bookkeeping. -func readPCAPNG(t *testing.T, path string) [][]byte { - t.Helper() - f, err := os.Open(path) - if err != nil { - t.Fatalf("open capture file: %v", err) - } - defer func() { _ = f.Close() }() - - reader, err := pcapgo.NewNgReader(f, pcapgo.DefaultNgReaderOptions) - if err != nil { - t.Fatalf("parse PCAPNG: %v", err) - } - var packets [][]byte - for { - data, _, err := reader.ReadPacketData() - if errors.Is(err, io.EOF) { - return packets - } - if err != nil { - t.Fatalf("read PCAPNG packet %d: %v", len(packets), err) - } - packets = append(packets, data) - } -} - -// --------------------------------------------------------------------------- -// Routing -// --------------------------------------------------------------------------- - -// TestRoutes_PatternsAreValid exercises the real ServeMux. net/http validates -// route patterns at registration time and panics on an invalid one - a -// wildcard segment must be exactly "{name}", so the chi-style "{id}:start" -// suffix is fatal here - and calling the handler functions directly, as the -// rest of this file does, can never catch that. -func TestRoutes_PatternsAreValid(t *testing.T) { - srv, factory := newTestServer(t) - mux := srv.Routes(nil) - - t.Run("healthz", func(t *testing.T) { - rr := httptest.NewRecorder() - mux.ServeHTTP(rr, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/healthz", nil)) - if rr.Code != http.StatusOK || rr.Body.String() != "ok" { - t.Fatalf("healthz = %d %q", rr.Code, rr.Body.String()) - } - }) - - t.Run("start extracts the id wildcard", func(t *testing.T) { - rr := httptest.NewRecorder() - body := strings.NewReader(startBody("tcp port 8080", 300, 1000000)) - mux.ServeHTTP(rr, httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/captures/cap-route/start", body)) - if rr.Code != http.StatusOK { - t.Fatalf("start via mux = %d, body %q", rr.Code, rr.Body.String()) - } - var resp startResponse - if err := json.NewDecoder(rr.Body).Decode(&resp); err != nil { - t.Fatalf("decode: %v", err) - } - if resp.CaptureID != "cap-route" { - t.Fatalf("captureId = %q, want cap-route", resp.CaptureID) - } - if factory.count() != 1 { - t.Fatalf("opened %d packet sources, want 1", factory.count()) - } - }) - - t.Run("status and file route to their handlers", func(t *testing.T) { - rr := httptest.NewRecorder() - mux.ServeHTTP(rr, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/captures/cap-route/status", nil)) - if rr.Code != http.StatusOK { - t.Fatalf("status via mux = %d", rr.Code) - } - - rr = httptest.NewRecorder() - mux.ServeHTTP(rr, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/captures/cap-route/file", nil)) - if rr.Code != http.StatusConflict { - t.Fatalf("file via mux = %d, want 409 while running", rr.Code) - } - }) - - t.Run("stop finishes the capture", func(t *testing.T) { - rr := httptest.NewRecorder() - body := strings.NewReader(`{"reason":"user_requested"}`) - mux.ServeHTTP(rr, httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/captures/cap-route/stop", body)) - if rr.Code != http.StatusOK { - t.Fatalf("stop via mux = %d, body %q", rr.Code, rr.Body.String()) - } - }) - - t.Run("the old chi-style colon paths are not routes", func(t *testing.T) { - rr := httptest.NewRecorder() - body := strings.NewReader(startBody("tcp port 8080", 300, 1000000)) - mux.ServeHTTP(rr, httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/captures/cap-x:start", body)) - // The colon path /captures/cap-x:start is a two-segment path that matches the - // DELETE /captures/{id} pattern (with id="cap-x:start"), but is rejected on method. - // This produces 405 Method Not Allowed, proving the colon path is not a start route. - // We accept either 404 (not found) or 405 (method not allowed) as evidence the - // colon path did not reach HandleStart. - if rr.Code != http.StatusNotFound && rr.Code != http.StatusMethodNotAllowed { - t.Fatalf("colon-suffix start = %d, want 404 or 405", rr.Code) - } - }) -} - -func TestRoutes_MiddlewareWrapsEveryCaptureEndpoint(t *testing.T) { - srv, _ := newTestServer(t) - - var wrapped int - mux := srv.Routes(func(_ http.Handler) http.Handler { - wrapped++ - return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(http.StatusTeapot) - }) - }) - routes := []struct{ method, path string }{ - {http.MethodPost, "/captures/cap-1/start"}, - {http.MethodPost, "/captures/cap-1/stop"}, - {http.MethodGet, "/captures/cap-1/status"}, - {http.MethodGet, "/captures/cap-1/file"}, - {http.MethodDelete, "/captures/cap-1"}, - {http.MethodGet, "/v1/targets/server-uid/captures/cap-1/uids/capture-uid/file"}, - {http.MethodDelete, "/v1/targets/server-uid/captures/cap-1/uids/capture-uid/file"}, - } - if wrapped != len(routes) { - t.Fatalf("middleware applied to %d handlers, want %d", wrapped, len(routes)) - } - for _, route := range routes { - rr := httptest.NewRecorder() - mux.ServeHTTP(rr, httptest.NewRequestWithContext(t.Context(), route.method, route.path, nil)) - if rr.Code != http.StatusTeapot { - t.Fatalf("%s %s bypassed the middleware: %d", route.method, route.path, rr.Code) - } - } - - // /healthz must stay unauthenticated. - rr := httptest.NewRecorder() - mux.ServeHTTP(rr, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/healthz", nil)) - if rr.Code != http.StatusOK { - t.Fatalf("healthz = %d, want 200 (unauthenticated)", rr.Code) - } -} - -// --------------------------------------------------------------------------- -// Start -// --------------------------------------------------------------------------- - -func TestHandleStart_InvalidBody(t *testing.T) { - srv, _ := newTestServer(t) - rr := doStart(t, srv, "cap-test", "invalid json") - if rr.Code != http.StatusBadRequest { - t.Fatalf("status = %d, want 400", rr.Code) - } -} - -func TestHandleStart_InvalidID(t *testing.T) { - srv, _ := newTestServer(t) - for _, id := range []string{"", ".", "..", "a/b", `a\b`, "cap test", strings.Repeat("a", 65)} { - req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/captures/x/start", strings.NewReader(startBody("tcp port 1", 5, 100))) - req.SetPathValue("id", id) - rr := httptest.NewRecorder() - srv.HandleStart(rr, req) - if rr.Code != http.StatusBadRequest { - t.Fatalf("id %q: status = %d, want 400", id, rr.Code) - } - } -} - -func TestHandleStart_LimitsOutOfRange(t *testing.T) { - srv, _ := newTestServer(t) - - cases := []struct { - name string - duration int64 - size int64 - }{ - {"zero duration", 0, 1000000}, - {"negative duration", -1, 1000000}, - {"duration beyond the sidecar cap", maxDurationSecondsLimit + 1, 1000000}, - {"duration that overflows int64 nanoseconds", 1 << 62, 1000000}, - {"zero size", 300, 0}, - {"negative size", 300, -1}, - } - - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - rr := doStart(t, srv, "cap-test", startBody("tcp port 8080", tc.duration, tc.size)) - if rr.Code != http.StatusBadRequest { - t.Fatalf("status = %d, want 400", rr.Code) - } - }) - } -} - -func TestHandleStart_InvalidFilterRejected(t *testing.T) { - srv, factory := newTestServer(t) - rr := doStart(t, srv, "cap-test", startBody("tcp port notaport", 300, 1000000)) - if rr.Code != http.StatusBadRequest { - t.Fatalf("status = %d, want 400", rr.Code) - } - if factory.count() != 0 { - t.Fatal("a packet source was opened for an invalid filter") - } -} - -// TestHandleStart_EmptyFilterRejected pins FR-003's boundary: the sidecar -// cannot construct the default advertised-port filter (it does not know the -// ports), and "no filter" must never be allowed to mean "capture the whole pod -// network", which would put the agent's and API's traffic into a downloadable -// file. -func TestHandleStart_EmptyFilterRejected(t *testing.T) { - srv, factory := newTestServer(t) - rr := doStart(t, srv, "cap-test", startBody("", 300, 1000000)) - if rr.Code != http.StatusBadRequest { - t.Fatalf("status = %d, want 400", rr.Code) - } - if !strings.Contains(rr.Body.String(), "filter is required") { - t.Fatalf("body = %q", rr.Body.String()) - } - if factory.count() != 0 { - t.Fatal("a packet source was opened without a filter") - } -} - -// TestHandleStart_SourceOpenFailure is the regression test for a capture that -// answered 200 while its AF_PACKET socket had failed to open: the user then -// got a valid, empty PCAPNG indistinguishable from "the filter matched -// nothing". The contract requires a clear error instead. -func TestHandleStart_SourceOpenFailure(t *testing.T) { - srv, factory := newTestServer(t) - factory.openErr = errors.New("open AF_PACKET socket on eth0: operation not permitted") - - rr := doStart(t, srv, "cap-test", startBody("tcp port 8080", 300, 1000000)) - if rr.Code != http.StatusInternalServerError { - t.Fatalf("status = %d, want 500", rr.Code) - } - if !strings.Contains(rr.Body.String(), "operation not permitted") { - t.Fatalf("body = %q; want the underlying error", rr.Body.String()) - } - - srv.mu.Lock() - current := srv.currentCapture - srv.mu.Unlock() - if current != nil { - t.Fatal("a failed start left a capture registered") - } - - // The socket is opened before the file, so a failed start leaves no - // orphan PCAPNG behind. - if _, err := os.Stat(srv.captureFilePath("cap-test")); !os.IsNotExist(err) { - t.Fatalf("stat capture file: %v; want it to be absent", err) - } -} - -func TestHandleStart_Success(t *testing.T) { - srv, factory := newTestServer(t) - rr := doStart(t, srv, "cap-test", startBody("tcp port 8080", 300, 1000000)) - if rr.Code != http.StatusOK { - t.Fatalf("status = %d, body %q", rr.Code, rr.Body.String()) - } - - var resp startResponse - if err := json.NewDecoder(rr.Body).Decode(&resp); err != nil { - t.Fatalf("decode: %v", err) - } - if resp.Status != statusRunning || resp.CaptureID != "cap-test" { - t.Fatalf("resp = %+v", resp) - } - if resp.BytesWritten != 0 || resp.PacketsWritten != 0 { - t.Fatalf("counters = %d/%d, want 0/0", resp.BytesWritten, resp.PacketsWritten) - } - if factory.count() != 1 { - t.Fatalf("opened %d packet sources, want 1", factory.count()) - } -} - -func TestHandleStart_ConcurrentRejected(t *testing.T) { - srv, factory := newTestServer(t) - - if rr := doStart(t, srv, "cap-first", startBody("tcp port 8080", 300, 1000000)); rr.Code != http.StatusOK { - t.Fatalf("first start = %d", rr.Code) - } - rr := doStart(t, srv, "cap-second", startBody("tcp port 8080", 300, 1000000)) - if rr.Code != http.StatusConflict { - t.Fatalf("second start = %d, want 409", rr.Code) - } - // F-192 regression: the 409 must name the capture that is actually - // running (cap-first), not the rejected request's id (cap-second) - - // otherwise the caller sees a capture that never started described as - // "in progress". - if body := rr.Body.String(); !strings.Contains(body, "cap-first") || strings.Contains(body, "cap-second") { - t.Fatalf("409 body = %q; want it to name the running capture cap-first, not the rejected cap-second", body) - } - if factory.count() != 1 { - t.Fatalf("opened %d packet sources; the rejected start must not open one", factory.count()) - } - - srv.mu.Lock() - current := srv.currentCapture - srv.mu.Unlock() - if current == nil || current.id != "cap-first" { - t.Fatal("the first capture was displaced") - } -} - -// --------------------------------------------------------------------------- -// Packet path -// --------------------------------------------------------------------------- - -// TestCapture_WritesPacketsAndReadableFile drives the whole packet path: -// start, feed synthetic frames, stop, then verify the counters and re-read the -// finalized file with gopacket's PCAPNG reader. -func TestCapture_WritesPacketsAndReadableFile(t *testing.T) { - srv, factory := newTestServer(t) - - if rr := doStart(t, srv, "cap-pkt", startBody("tcp port 8080", 300, 10000000)); rr.Code != http.StatusOK { - t.Fatalf("start = %d, body %q", rr.Code, rr.Body.String()) - } - - frames := [][]byte{frame(0x11), frame(0x22), frame(0x33)} - factory.last(t).feed(frames...) - waitForPackets(t, srv, "cap-pkt", int64(len(frames))) - - resp := decodeStop(t, doStop(t, srv, "cap-pkt", `{"reason":"user_requested"}`)) - if resp.Status != statusCompleted { - t.Fatalf("status = %q, want completed (message %q)", resp.Status, resp.Message) - } - if resp.PacketsWritten != int64(len(frames)) { - t.Fatalf("packetsWritten = %d, want %d", resp.PacketsWritten, len(frames)) - } - // At least the captured payload; the writer may additionally account for - // per-packet PCAPNG block overhead. - if want := int64(len(frames) * len(frames[0])); resp.BytesWritten < want { - t.Fatalf("bytesWritten = %d, want at least %d", resp.BytesWritten, want) - } - if resp.StoppingReason != reasonUserRequested { - t.Fatalf("stoppingReason = %q", resp.StoppingReason) - } - - got := readPCAPNG(t, srv.captureFilePath("cap-pkt")) - if len(got) != len(frames) { - t.Fatalf("PCAPNG holds %d packets, want %d", len(got), len(frames)) - } - for i, want := range frames { - if string(got[i]) != string(want) { - t.Fatalf("packet %d differs from what was captured", i) - } - } -} - -// TestCapture_SizeLimitStopsImmediately pins the fix for a size-limited -// capture that used to stay "running" until the next packet arrived - on a -// quiet link, potentially until the duration timer fired. -func TestCapture_SizeLimitStopsImmediately(t *testing.T) { - srv, factory := newTestServer(t) - - if rr := doStart(t, srv, "cap-size", startBody("tcp port 8080", 300, 100)); rr.Code != http.StatusOK { - t.Fatalf("start = %d, body %q", rr.Code, rr.Body.String()) - } - factory.last(t).feed(frame(0x01), frame(0x02)) - - status := waitForTerminal(t, srv, "cap-size") - if status.Status != statusCompleted { - t.Fatalf("status = %q, want completed", status.Status) - } - if status.StoppingReason != "max_size_reached" { - t.Fatalf("stoppingReason = %q, want max_size_reached", status.StoppingReason) - } - // Exactly how many of the two 64-byte frames fit under a 100-byte cap - // depends on whether the writer accounts for PCAPNG block overhead, so pin - // the invariant that matters: it stopped early, and the file is readable and - // holds exactly what the counters claim. - if status.PacketsWritten < 1 || status.PacketsWritten > 2 { - t.Fatalf("packetsWritten = %d, want 1 or 2", status.PacketsWritten) - } - if got := int64(len(readPCAPNG(t, srv.captureFilePath("cap-size")))); got != status.PacketsWritten { - t.Fatalf("PCAPNG holds %d packets but the status reports %d", got, status.PacketsWritten) - } -} - -// TestCapture_MidCaptureReadFailureIsReportedFailed pins that a capture whose -// packet source dies mid-run is reported failed, not completed: the file holds -// real packets but is truncated, and the operator must see the cause. -func TestCapture_MidCaptureReadFailureIsReportedFailed(t *testing.T) { - srv, factory := newTestServer(t) - - if rr := doStart(t, srv, "cap-err", startBody("tcp port 8080", 300, 10000000)); rr.Code != http.StatusOK { - t.Fatalf("start = %d", rr.Code) - } - src := factory.last(t) - src.feed(frame(0x77)) - waitForPackets(t, srv, "cap-err", 1) - src.failWith(errors.New("network is down")) - - status := waitForTerminal(t, srv, "cap-err") - if status.Status != statusFailed { - t.Fatalf("status = %q, want failed", status.Status) - } - if status.StoppingReason != reasonError { - t.Fatalf("stoppingReason = %q, want %q", status.StoppingReason, reasonError) - } - if !strings.Contains(status.Message, "network is down") { - t.Fatalf("message = %q; want the underlying cause", status.Message) - } - if status.PacketsWritten != 1 { - t.Fatalf("packetsWritten = %d, want the packet captured before the failure", status.PacketsWritten) - } - if len(readPCAPNG(t, srv.captureFilePath("cap-err"))) != 1 { - t.Fatal("the truncated capture is not a readable PCAPNG") - } -} - -// --------------------------------------------------------------------------- -// Stop -// --------------------------------------------------------------------------- - -func TestHandleStop_NotFound(t *testing.T) { - srv, _ := newTestServer(t) - rr := doStop(t, srv, "nonexistent", `{"reason":"user_requested"}`) - if rr.Code != http.StatusNotFound { - t.Fatalf("status = %d, want 404", rr.Code) - } -} - -func TestHandleStop_ChunkedBodyIsDecoded(t *testing.T) { - srv, _ := newTestServer(t) - if rr := doStart(t, srv, "cap-chunk", startBody("tcp port 8080", 300, 1000000)); rr.Code != http.StatusOK { - t.Fatalf("start = %d", rr.Code) - } - - // A client that assigns Body after building the request leaves - // ContentLength at 0, and net/http then sends the body chunked, which the - // server sees as ContentLength == -1. The reason must still be decoded. - req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/captures/cap-chunk/stop", strings.NewReader(`{"reason":"pod_restarting"}`)) - req.SetPathValue("id", "cap-chunk") - req.ContentLength = -1 - rr := httptest.NewRecorder() - srv.HandleStop(rr, req) - - if rr.Code != http.StatusOK { - t.Fatalf("status = %d, body %q", rr.Code, rr.Body.String()) - } - if got := decodeStop(t, rr).StoppingReason; got != "pod_restarting" { - t.Fatalf("stoppingReason = %q, want pod_restarting", got) - } -} - -func TestHandleStop_EmptyBodyDefaultsToUserRequested(t *testing.T) { - srv, _ := newTestServer(t) - if rr := doStart(t, srv, "cap-nobody", startBody("tcp port 8080", 300, 1000000)); rr.Code != http.StatusOK { - t.Fatalf("start = %d", rr.Code) - } - rr := doStop(t, srv, "cap-nobody", "") - if rr.Code != http.StatusOK { - t.Fatalf("status = %d, body %q", rr.Code, rr.Body.String()) - } - if got := decodeStop(t, rr).StoppingReason; got != reasonUserRequested { - t.Fatalf("stoppingReason = %q, want %q", got, reasonUserRequested) - } -} - -// TestHandleStop_ReplaysTerminalStateOfAFinishedCapture pins the fix for the -// bug where a finished capture was discarded: a stop that lost the race with -// the duration timer used to 404, destroying the counters and the reason. -func TestHandleStop_ReplaysTerminalStateOfAFinishedCapture(t *testing.T) { - srv, factory := newTestServer(t) - if rr := doStart(t, srv, "cap-twice", startBody("tcp port 8080", 300, 10000000)); rr.Code != http.StatusOK { - t.Fatalf("start = %d", rr.Code) - } - factory.last(t).feed(frame(0x42)) - waitForPackets(t, srv, "cap-twice", 1) - - first := decodeStop(t, doStop(t, srv, "cap-twice", `{"reason":"user_requested"}`)) - - rr := doStop(t, srv, "cap-twice", `{"reason":"user_requested"}`) - if rr.Code != http.StatusOK { - t.Fatalf("second stop = %d, want 200 with the stored result", rr.Code) - } - second := decodeStop(t, rr) - if second.PacketsWritten != first.PacketsWritten || second.StoppingReason != first.StoppingReason { - t.Fatalf("replayed %+v, want %+v", second, first) - } - if second.PacketsWritten != 1 { - t.Fatalf("packetsWritten = %d, want 1", second.PacketsWritten) - } -} - -// --------------------------------------------------------------------------- -// Status -// --------------------------------------------------------------------------- - -func TestHandleStatus_NotFound(t *testing.T) { - srv, _ := newTestServer(t) - if rr := doStatus(t, srv, "nonexistent"); rr.Code != http.StatusNotFound { - t.Fatalf("status = %d, want 404", rr.Code) - } -} - -func TestHandleStatus_Running(t *testing.T) { - srv, _ := newTestServer(t) - if rr := doStart(t, srv, "cap-test", startBody("tcp port 8080", 300, 1000000)); rr.Code != http.StatusOK { - t.Fatalf("start = %d", rr.Code) - } - - rr := doStatus(t, srv, "cap-test") - if rr.Code != http.StatusOK { - t.Fatalf("status = %d", rr.Code) - } - var resp statusResponseRunning - if err := json.NewDecoder(rr.Body).Decode(&resp); err != nil { - t.Fatalf("decode: %v", err) - } - if resp.Status != statusRunning || resp.CaptureID != "cap-test" { - t.Fatalf("resp = %+v", resp) - } - if resp.CompletedAt != nil || resp.StoppingReason != nil { - t.Fatalf("running response must null out completedAt/stoppingReason: %+v", resp) - } - if resp.EstimatedTimeRemainingSeconds <= 0 || resp.EstimatedTimeRemainingSeconds > 300 { - t.Fatalf("estimatedTimeRemainingSeconds = %d", resp.EstimatedTimeRemainingSeconds) - } - // estimatedBytesRemaining must be maxSizeBytes minus the writer's real - // on-disk bytesWritten (which, even before any packet is written, already - // includes the PCAPNG section-header and interface-description blocks — - // see capture.Writer.BytesWritten). Assert that relationship via the - // response's own bytesWritten rather than a byte count copied from a test - // run, which breaks every time block/header overhead changes. - if resp.BytesWritten <= 0 { - t.Fatalf("bytesWritten = %d, want > 0 (PCAPNG header blocks are written up front)", resp.BytesWritten) - } - if want := int64(1000000) - resp.BytesWritten; resp.EstimatedBytesRemaining != want { - t.Fatalf("estimatedBytesRemaining = %d, want %d (maxSizeBytes - bytesWritten=%d)", resp.EstimatedBytesRemaining, want, resp.BytesWritten) - } - if resp.EstimatedBytesRemaining <= 0 || resp.EstimatedBytesRemaining >= 1000000 { - t.Fatalf("estimatedBytesRemaining = %d, want in (0, 1000000)", resp.EstimatedBytesRemaining) - } -} - -// TestHandleStatus_Completed pins the contract's documented completed-status -// response, which used to be unreachable: finishing a capture discarded it, so -// every poll after completion returned 404 and the operator failed the -// NetworkCapture with "sidecar unreachable". -func TestHandleStatus_Completed(t *testing.T) { - srv, factory := newTestServer(t) - if rr := doStart(t, srv, "cap-test", startBody("tcp port 8080", 300, 10000000)); rr.Code != http.StatusOK { - t.Fatalf("start = %d", rr.Code) - } - factory.last(t).feed(frame(0x55), frame(0x56)) - waitForPackets(t, srv, "cap-test", 2) - - if rr := doStop(t, srv, "cap-test", `{"reason":"user_requested"}`); rr.Code != http.StatusOK { - t.Fatalf("stop = %d", rr.Code) - } - - rr := doStatus(t, srv, "cap-test") - if rr.Code != http.StatusOK { - t.Fatalf("status of a completed capture = %d, want 200", rr.Code) - } - resp := decodeCompleted(t, rr) - if resp.Status != statusCompleted { - t.Fatalf("status = %q, want completed", resp.Status) - } - if resp.StoppingReason != reasonUserRequested { - t.Fatalf("stoppingReason = %q", resp.StoppingReason) - } - if resp.PacketsWritten != 2 { - t.Fatalf("packetsWritten = %d, want 2", resp.PacketsWritten) - } - if resp.CompletedAt == "" || resp.File != srv.captureFilePath("cap-test") { - t.Fatalf("resp = %+v", resp) - } -} - -// TestDurationTimeout pins that the hard duration cap finalizes the capture -// and reports it as a normal completion with the right reason, rather than -// dropping it. -func TestDurationTimeout(t *testing.T) { - srv, factory := newTestServer(t) - if rr := doStart(t, srv, "cap-timeout", startBody("tcp port 8080", 1, 10000000)); rr.Code != http.StatusOK { - t.Fatalf("start = %d", rr.Code) - } - factory.last(t).feed(frame(0x09)) - waitForPackets(t, srv, "cap-timeout", 1) - - resp := waitForTerminal(t, srv, "cap-timeout") - if resp.Status != statusCompleted { - t.Fatalf("status = %q, want completed (message %q)", resp.Status, resp.Message) - } - if resp.StoppingReason != reasonMaxDuration { - t.Fatalf("stoppingReason = %q, want %q", resp.StoppingReason, reasonMaxDuration) - } - if resp.PacketsWritten != 1 { - t.Fatalf("packetsWritten = %d, want 1", resp.PacketsWritten) - } - if len(readPCAPNG(t, srv.captureFilePath("cap-timeout"))) != 1 { - t.Fatal("the duration-limited capture did not finalize a readable file") - } - - srv.mu.Lock() - current := srv.currentCapture - srv.mu.Unlock() - if current != nil { - t.Fatal("the capture was not auto-stopped by the duration timer") - } -} - -// TestStatusPollsRaceWithFinish exercises the status path concurrently with a -// capture finishing. It is the -race regression test for reading a capture's -// mutable fields outside its mutex. -func TestStatusPollsRaceWithFinish(t *testing.T) { - srv, _ := newTestServer(t) - if rr := doStart(t, srv, "cap-race", startBody("tcp port 8080", 300, 1000000)); rr.Code != http.StatusOK { - t.Fatalf("start = %d", rr.Code) - } - - stopPolling := make(chan struct{}) - var wg sync.WaitGroup - for i := 0; i < 4; i++ { - wg.Add(1) - go func() { - defer wg.Done() - for { - select { - case <-stopPolling: - return - default: - } - req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/captures/cap-race/status", nil) - req.SetPathValue("id", "cap-race") - srv.HandleStatus(httptest.NewRecorder(), req) - } - }() - } - - time.Sleep(20 * time.Millisecond) - if rr := doStop(t, srv, "cap-race", `{"reason":"user_requested"}`); rr.Code != http.StatusOK { - t.Fatalf("stop = %d", rr.Code) - } - close(stopPolling) - wg.Wait() -} - -// --------------------------------------------------------------------------- -// Download -// --------------------------------------------------------------------------- - -func TestHandleDownload_NotFound(t *testing.T) { - srv, _ := newTestServer(t) - if rr := doDownload(t, srv, "nonexistent", ""); rr.Code != http.StatusNotFound { - t.Fatalf("status = %d, want 404", rr.Code) - } -} - -// TestHandleDownload_GoneOnlyForAKnownCapture pins that 410 means "this -// sidecar ran this capture and its file is gone", not "any open error". -func TestHandleDownload_GoneOnlyForAKnownCapture(t *testing.T) { - srv, _ := newTestServer(t) - if rr := doStart(t, srv, "cap-gone", startBody("tcp port 8080", 300, 1000000)); rr.Code != http.StatusOK { - t.Fatalf("start = %d", rr.Code) - } - if rr := doStop(t, srv, "cap-gone", ""); rr.Code != http.StatusOK { - t.Fatalf("stop = %d", rr.Code) - } - if err := os.Remove(srv.captureFilePath("cap-gone")); err != nil { - t.Fatalf("remove capture file: %v", err) - } - - if rr := doDownload(t, srv, "cap-gone", ""); rr.Code != http.StatusGone { - t.Fatalf("status = %d, want 410", rr.Code) - } - if rr := doDownload(t, srv, "cap-unknown", ""); rr.Code != http.StatusNotFound { - t.Fatalf("status = %d, want 404 for an unknown capture", rr.Code) - } -} - -func TestHandleDownload_StillRunning(t *testing.T) { - srv, _ := newTestServer(t) - if rr := doStart(t, srv, "cap-test", startBody("tcp port 8080", 300, 1000000)); rr.Code != http.StatusOK { - t.Fatalf("start = %d", rr.Code) - } - if rr := doDownload(t, srv, "cap-test", ""); rr.Code != http.StatusConflict { - t.Fatalf("status = %d, want 409", rr.Code) - } -} - -func TestHandleDownload_Success(t *testing.T) { - srv, _ := newTestServer(t) - payload := []byte("PCAPNG test data") - if err := os.WriteFile(srv.captureFilePath("cap-test"), payload, 0o600); err != nil { - t.Fatalf("write capture file: %v", err) - } - - rr := doDownload(t, srv, "cap-test", "") - if rr.Code != http.StatusOK { - t.Fatalf("status = %d", rr.Code) - } - if ct := rr.Header().Get("Content-Type"); ct != "application/vnd.tcpdump.pcap" { - t.Fatalf("Content-Type = %q", ct) - } - if cd := rr.Header().Get("Content-Disposition"); cd != `attachment; filename="capture-cap-test.pcapng"` { - t.Fatalf("Content-Disposition = %q", cd) - } - if rr.Header().Get("Accept-Ranges") != "bytes" { - t.Fatalf("Accept-Ranges = %q", rr.Header().Get("Accept-Ranges")) - } - if rr.Body.String() != string(payload) { - t.Fatalf("body = %q", rr.Body.String()) - } -} - -// TestHandleDownload_HonoursRange pins the fix for advertising Accept-Ranges -// while ignoring Range: a resuming client used to silently receive the file -// from byte 0 and corrupt its download. -func TestHandleDownload_HonoursRange(t *testing.T) { - srv, _ := newTestServer(t) - payload := []byte("0123456789") - if err := os.WriteFile(srv.captureFilePath("cap-range"), payload, 0o600); err != nil { - t.Fatalf("write capture file: %v", err) - } - - rr := doDownload(t, srv, "cap-range", "bytes=4-7") - if rr.Code != http.StatusPartialContent { - t.Fatalf("status = %d, want 206", rr.Code) - } - if rr.Body.String() != "4567" { - t.Fatalf("body = %q, want %q", rr.Body.String(), "4567") - } - if got := rr.Header().Get("Content-Range"); got != "bytes 4-7/10" { - t.Fatalf("Content-Range = %q", got) - } - - rr = doDownload(t, srv, "cap-range", "bytes=99-200") - if rr.Code != http.StatusRequestedRangeNotSatisfiable { - t.Fatalf("status = %d, want 416", rr.Code) - } -} - -func TestHandleDownload_StreamsLargeFile(t *testing.T) { - srv, _ := newTestServer(t) - payload := make([]byte, 1024*1024) - for i := range payload { - payload[i] = byte(i % 256) - } - if err := os.WriteFile(srv.captureFilePath("cap-large"), payload, 0o600); err != nil { - t.Fatalf("write capture file: %v", err) - } - - rr := doDownload(t, srv, "cap-large", "") - if rr.Code != http.StatusOK { - t.Fatalf("status = %d", rr.Code) - } - if rr.Body.Len() != len(payload) { - t.Fatalf("body = %d bytes, want %d", rr.Body.Len(), len(payload)) - } -} - -// --------------------------------------------------------------------------- -// Delete -// --------------------------------------------------------------------------- - -func TestHandleDelete_InvalidID(t *testing.T) { - srv, _ := newTestServer(t) - for _, id := range []string{"", ".", "..", "a/b", `a\b`, "cap test", strings.Repeat("a", 65)} { - req := httptest.NewRequestWithContext(t.Context(), http.MethodDelete, "/captures/x", nil) - req.SetPathValue("id", id) - rr := httptest.NewRecorder() - srv.HandleDelete(rr, req) - if rr.Code != http.StatusBadRequest { - t.Fatalf("id %q: status = %d, want 400", id, rr.Code) - } - } -} - -func TestHandleDelete_Success(t *testing.T) { - srv, _ := newTestServer(t) - filePath := srv.captureFilePath("cap-test") - if err := os.WriteFile(filePath, []byte("test data"), 0o600); err != nil { - t.Fatalf("write capture file: %v", err) - } - - if _, err := os.Stat(filePath); err != nil { - t.Fatalf("stat before delete: %v", err) - } - - rr := doDelete(t, srv, "cap-test") - if rr.Code != http.StatusNoContent { - t.Fatalf("status = %d, want 204", rr.Code) - } - - if _, err := os.Stat(filePath); !os.IsNotExist(err) { - t.Fatalf("stat after delete: %v; want ErrNotExist", err) - } -} - -func TestHandleDelete_Idempotent(t *testing.T) { - srv, _ := newTestServer(t) - filePath := srv.captureFilePath("cap-test") - if err := os.WriteFile(filePath, []byte("test data"), 0o600); err != nil { - t.Fatalf("write capture file: %v", err) - } - - // First delete should succeed. - rr := doDelete(t, srv, "cap-test") - if rr.Code != http.StatusNoContent { - t.Fatalf("first delete status = %d, want 204", rr.Code) - } - - // Second delete (file already gone) should also succeed. - rr = doDelete(t, srv, "cap-test") - if rr.Code != http.StatusNoContent { - t.Fatalf("second delete status = %d, want 204", rr.Code) - } -} - -func TestHandleDelete_RefusesRunningCapture(t *testing.T) { - srv, _ := newTestServer(t) - if rr := doStart(t, srv, "cap-test", startBody("tcp port 8080", 300, 1000000)); rr.Code != http.StatusOK { - t.Fatalf("start = %d", rr.Code) - } - - rr := doDelete(t, srv, "cap-test") - if rr.Code != http.StatusConflict { - t.Fatalf("status = %d, want 409", rr.Code) - } - - // File should still exist. - if _, err := os.Stat(srv.captureFilePath("cap-test")); err != nil { - t.Fatalf("stat capture file: %v; the running capture should protect it", err) - } -} - -func TestHandleDelete_ViaRouterMux(t *testing.T) { - srv, _ := newTestServer(t) - mux := srv.Routes(nil) - filePath := srv.captureFilePath("cap-route-delete") - if err := os.WriteFile(filePath, []byte("test data"), 0o600); err != nil { - t.Fatalf("write capture file: %v", err) - } - - rr := httptest.NewRecorder() - mux.ServeHTTP(rr, httptest.NewRequestWithContext(t.Context(), http.MethodDelete, "/captures/cap-route-delete", nil)) - if rr.Code != http.StatusNoContent { - t.Fatalf("delete via mux = %d, want 204", rr.Code) - } - - if _, err := os.Stat(filePath); !os.IsNotExist(err) { - t.Fatalf("file still exists after delete via mux") - } -} - -// --------------------------------------------------------------------------- -// Lifecycle -// --------------------------------------------------------------------------- - -// TestCaptureGoroutinesDoNotLeak actually counts goroutines, which the test -// that previously carried this name did not. -func TestCaptureGoroutinesDoNotLeak(t *testing.T) { - srv, _ := newTestServer(t) - before := runtime.NumGoroutine() - - for i := 0; i < 5; i++ { - id := fmt.Sprintf("cap-leak-%d", i) - if rr := doStart(t, srv, id, startBody("tcp port 8080", 300, 1000000)); rr.Code != http.StatusOK { - t.Fatalf("iteration %d: start = %d", i, rr.Code) - } - if rr := doStop(t, srv, id, `{"reason":"cleanup"}`); rr.Code != http.StatusOK { - t.Fatalf("iteration %d: stop = %d", i, rr.Code) - } - } - - srv.mu.Lock() - current := srv.currentCapture - srv.mu.Unlock() - if current != nil { - t.Fatal("a capture is still registered after all stops") - } - - deadline := time.Now().Add(5 * time.Second) - for runtime.NumGoroutine() > before+2 && time.Now().Before(deadline) { - time.Sleep(10 * time.Millisecond) - } - if after := runtime.NumGoroutine(); after > before+2 { - t.Fatalf("goroutines: %d before, %d after; the capture goroutines leaked", before, after) - } -} - -// TestStaleDurationTimerCannotKillASuccessor pins that a timer left over from -// a finished capture never terminates a later capture that reuses its id. -func TestStaleDurationTimerCannotKillASuccessor(t *testing.T) { - srv, _ := newTestServer(t) - if rr := doStart(t, srv, "cap-reuse", startBody("tcp port 8080", 1, 1000000)); rr.Code != http.StatusOK { - t.Fatalf("first start = %d", rr.Code) - } - - srv.mu.Lock() - first := srv.currentCapture - srv.mu.Unlock() - if first == nil { - t.Fatal("no capture registered") - } - - if rr := doStop(t, srv, "cap-reuse", `{"reason":"user_requested"}`); rr.Code != http.StatusOK { - t.Fatalf("stop = %d", rr.Code) - } - if rr := doStart(t, srv, "cap-reuse", startBody("tcp port 8080", 300, 1000000)); rr.Code != http.StatusOK { - t.Fatalf("second start = %d", rr.Code) - } - - // Fire the first capture's timer callback by hand: it must be a no-op. - srv.finish("", first, reasonMaxDuration, nil) - - srv.mu.Lock() - current := srv.currentCapture - srv.mu.Unlock() - if current == nil { - t.Fatal("the stale timer terminated the successor capture") - } - - rr := doStatus(t, srv, "cap-reuse") - if rr.Code != http.StatusOK || !strings.Contains(rr.Body.String(), `"status":"running"`) { - t.Fatalf("successor status = %d %q", rr.Code, rr.Body.String()) - } -} - -// TestCaptureENOSPCDuringWritePacketReportsDiskFull pins the fix for -// ENOSPC from WritePacket being reported as a generic "error" instead of -// "disk_full". This happens when bufio flush inside WritePacket fails, -// and is distinguished from other write errors by checking both the -// error chain and the writer's LimitReason. -func TestCaptureENOSPCDuringWritePacketReportsDiskFull(t *testing.T) { - srv, factory := newTestServer(t) - if rr := doStart(t, srv, "cap-enospc", startBody("tcp port 8080", 300, 1000000)); rr.Code != http.StatusOK { - t.Fatalf("start = %d", rr.Code) - } - - // Feed one packet to establish the capture is running. - factory.last(t).feed(frame(0x11)) - waitForPackets(t, srv, "cap-enospc", 1) - - // Replace the writer with a failing one that returns ENOSPC on WritePacket. - srv.mu.Lock() - state := srv.currentCapture - srv.mu.Unlock() - - if state == nil { - t.Fatal("no capture is running") - } - - oldWriter := state.writer - - // Inject a writer that fails on the next WritePacket call. - // We'll do this by swapping the writer with one that wraps the original - // but fails on the next call. - state.mu.Lock() - state.writer = &failingWriter{inner: oldWriter, failWith: syscall.ENOSPC} - state.mu.Unlock() - - // Feed another packet that will trigger the ENOSPC error. - factory.last(t).feed(frame(0x22)) - - // Wait for the capture to reach a terminal state. - resp := waitForTerminal(t, srv, "cap-enospc") - - // Verify the failure was reported as disk_full, not error. - if resp.Status != statusFailed { - t.Fatalf("status = %q, want failed", resp.Status) - } - if resp.StoppingReason != reasonDiskFull { - t.Fatalf("stoppingReason = %q, want %q", resp.StoppingReason, reasonDiskFull) - } - if resp.PacketsWritten < 1 { - t.Fatalf("packetsWritten = %d, want >= 1 (the error occurred during write)", resp.PacketsWritten) - } -} - -// failingWriter wraps a capture.PacketWriter and fails on the next WritePacket call. -type failingWriter struct { - inner capture.PacketWriter - failWith error - failCount int - failAfter int -} - -func (fw *failingWriter) WritePacket(pkt *capture.RawPacket) error { - fw.failCount++ - if fw.failAfter == 0 || fw.failCount > fw.failAfter { - if fw.failWith != nil { - return fmt.Errorf("disk full during capture: %w", fw.failWith) - } - } - return fw.inner.WritePacket(pkt) -} - -func (fw *failingWriter) Close() error { - return fw.inner.Close() -} - -func (fw *failingWriter) BytesWritten() int64 { - return fw.inner.BytesWritten() -} - -func (fw *failingWriter) PacketsWritten() int64 { - return fw.inner.PacketsWritten() -} - -func (fw *failingWriter) IsLimitReached() bool { - return fw.inner.IsLimitReached() -} - -func (fw *failingWriter) LimitReason() string { - return fw.inner.LimitReason() -} - -// --------------------------------------------------------------------------- -// F-187: volume budget (retained + new capture vs. the emptyDir SizeLimit) -// --------------------------------------------------------------------------- - -// newTestServerWithBudget is newTestServer with a non-zero volume budget, for -// the tests below that exercise HandleStart's F-187 admission check. -func newTestServerWithBudget(t *testing.T, budgetBytes int64) (*Server, *sourceFactory) { - t.Helper() - srv := NewServer(context.Background(), t.TempDir(), budgetBytes) - factory := &sourceFactory{} - srv.newSource = factory.open - t.Cleanup(func() { - srv.mu.Lock() - state := srv.currentCapture - srv.mu.Unlock() - if state != nil { - srv.finish("", state, reasonUserRequested, nil) - <-state.done - } - }) - return srv, factory -} - -// writeRetainedFile creates a retained capture's PCAPNG file directly on -// disk (simulating a capture that finished in an earlier pod lifetime and -// is still waiting out its retention window) reporting exactly n bytes via -// os.Stat. The file is created sparse (via Truncate rather than writing n -// actual bytes) so large fixtures used to exercise volume-budget refusals -// don't allocate or physically write gigabytes of real disk/memory in CI. -func writeRetainedFile(t *testing.T, srv *Server, id string, n int64) { - t.Helper() - f, err := os.Create(srv.captureFilePath(id)) - if err != nil { - t.Fatalf("create retained fixture %s: %v", id, err) - } - defer func() { - if err := f.Close(); err != nil { - t.Fatalf("close retained fixture %s: %v", id, err) - } - }() - if err := f.Truncate(n); err != nil { - t.Fatalf("truncate retained fixture %s to %d bytes: %v", id, n, err) - } -} - -// TestHandleStart_VolumeBudget_RefusesWhenRetainedPlusNewExceedsBudget -// covers the core F-187 regression: retained files that the old check never -// looked at must count against the same budget as the new capture's own -// ceiling. -func TestHandleStart_VolumeBudget_RefusesWhenRetainedPlusNewExceedsBudget(t *testing.T) { - const budget = 1000 - srv, factory := newTestServerWithBudget(t, budget) - - writeRetainedFile(t, srv, "cap-old", 700) - - rr := doStart(t, srv, "cap-new", startBody("tcp port 8080", 300, 400)) // 700+400 > 1000 - if rr.Code != http.StatusInsufficientStorage { - t.Fatalf("status = %d, body %q; want 507", rr.Code, rr.Body.String()) - } - if !strings.Contains(rr.Body.String(), "budget") { - t.Fatalf("body = %q; want it to mention the volume budget", rr.Body.String()) - } - if factory.count() != 0 { - t.Fatalf("opened %d packet sources; a refused start must not open one", factory.count()) - } - srv.mu.Lock() - current := srv.currentCapture - srv.mu.Unlock() - if current != nil { - t.Fatal("a refused start left a capture registered") - } -} - -// TestHandleStart_VolumeBudget_AllowsWhenItFits is the mirror case: the same -// retained file plus a new capture that fits under the budget must still be -// admitted. -func TestHandleStart_VolumeBudget_AllowsWhenItFits(t *testing.T) { - const budget = 1000 - srv, _ := newTestServerWithBudget(t, budget) - - writeRetainedFile(t, srv, "cap-old", 700) - - rr := doStart(t, srv, "cap-new", startBody("tcp port 8080", 300, 300)) // 700+300 == 1000, fits - if rr.Code != http.StatusOK { - t.Fatalf("status = %d, body %q; want 200", rr.Code, rr.Body.String()) - } -} - -// TestHandleStart_VolumeBudget_ExpiredFilesNotCounted covers the "expired -// files don't count" half of F-187: a capture file already deleted (expiry, -// in this system, is deletion - see retainedCaptureBytes' doc comment) must -// not be counted against the budget just because it once existed. -func TestHandleStart_VolumeBudget_ExpiredFilesNotCounted(t *testing.T) { - const budget = 1000 - srv, _ := newTestServerWithBudget(t, budget) - - writeRetainedFile(t, srv, "cap-old", 700) - writeRetainedFile(t, srv, "cap-expired", 900) - // Simulate the operator's expiry reconciler deleting the retention-expired - // file (expireCapture -> DeleteCaptureFile -> HandleDelete) before this - // start request arrives. - if err := os.Remove(srv.captureFilePath("cap-expired")); err != nil { - t.Fatalf("remove expired fixture: %v", err) - } - - // Without the deleted file counted, 700(retained)+300(new) fits exactly; - // counting it (700+900+300) would refuse the start. - rr := doStart(t, srv, "cap-new", startBody("tcp port 8080", 300, 300)) - if rr.Code != http.StatusOK { - t.Fatalf("status = %d, body %q; want 200 (expired file must not count)", rr.Code, rr.Body.String()) - } -} - -// TestHandleStart_VolumeBudget_RefusesOnOversizedRequestWithoutOverflow -// covers the overflow regression in the admission check: a maxSizeBytes at -// math.MaxInt64 (what an unclamped NetworkCapture CR applied directly - -// bypassing the API tier's DefaultMaxSizeBytes clamp - can carry through to -// this handler as nc.Spec.MaxSize.Value()) added to any positive retained -// total wraps a signed int64 negative, which would make the naive -// `retained+req.MaxSizeBytes > s.budgetBytes` comparison spuriously false -// and admit a start that should be refused. The check must compare without -// adding. -func TestHandleStart_VolumeBudget_RefusesOnOversizedRequestWithoutOverflow(t *testing.T) { - const budget = 1000 - srv, factory := newTestServerWithBudget(t, budget) - - writeRetainedFile(t, srv, "cap-old", 700) - - rr := doStart(t, srv, "cap-new", startBody("tcp port 8080", 300, math.MaxInt64)) - if rr.Code != http.StatusInsufficientStorage { - t.Fatalf("status = %d, body %q; want 507 (must not overflow into admission)", rr.Code, rr.Body.String()) - } - if !strings.Contains(rr.Body.String(), "budget") { - t.Fatalf("body = %q; want it to mention the volume budget", rr.Body.String()) - } - if factory.count() != 0 { - t.Fatalf("opened %d packet sources; a refused start must not open one", factory.count()) - } -} - -// TestHandleStart_VolumeBudget_ZeroDisablesCheck documents that a zero -// budget (the value every other HandleStart test uses via newTestServer) -// disables the check entirely, regardless of what's on disk. -func TestHandleStart_VolumeBudget_ZeroDisablesCheck(t *testing.T) { - srv, _ := newTestServer(t) - - writeRetainedFile(t, srv, "cap-old", 10*1024*1024*1024) // absurdly large; would refuse if checked - - rr := doStart(t, srv, "cap-new", startBody("tcp port 8080", 300, 1000000)) - if rr.Code != http.StatusOK { - t.Fatalf("status = %d, body %q; want 200 (budget check disabled)", rr.Code, rr.Body.String()) - } -} diff --git a/capture-sidecar/internal/httpserver/identity.go b/capture-sidecar/internal/httpserver/identity.go deleted file mode 100644 index 3cbbcf992..000000000 --- a/capture-sidecar/internal/httpserver/identity.go +++ /dev/null @@ -1,285 +0,0 @@ -package httpserver - -import ( - "encoding/json" - "errors" - "fmt" - "io" - "io/fs" - "net/http" - "os" - "path/filepath" - "regexp" - "strings" - "time" -) - -var captureUIDPattern = regexp.MustCompile(`^[A-Za-z0-9-]{1,128}$`) - -var errCaptureIdentityBudget = errors.New("capture identity retention budget reached") - -type captureIdentity struct { - ServerUID string `json:"serverUID"` - CaptureUID string `json:"captureUID"` -} - -func (s *Server) captureIdentityPath(id string) string { - return filepath.Join(s.captureDataDir, "capture-"+id+".identity.json") -} - -func (s *Server) validStartIdentity(req startRequest) bool { - if req.ServerUID == "" && req.CaptureUID == "" { - return true // Legacy local clients cannot use the bound file routes. - } - return captureUIDPattern.MatchString(req.ServerUID) && captureUIDPattern.MatchString(req.CaptureUID) && req.ServerUID == s.serverUID -} - -// prepareCaptureBinding runs under s.mu before opening the writer. Linking a -// fully written temporary file publishes the identity atomically without ever -// replacing another capture's binding. A retained bound name cannot be reused, -// even by a legacy start, because the writer would truncate its PCAP. -func (s *Server) prepareCaptureBinding(id string, req startRequest) (bool, error) { - if err := s.pruneCaptureTombstones(); err != nil { - return false, err - } - path := s.captureIdentityPath(id) - if _, err := os.Lstat(path); err == nil { - return false, fs.ErrExist - } else if !errors.Is(err, fs.ErrNotExist) { - return false, err - } - if req.CaptureUID == "" { - return false, nil - } - if _, err := os.Lstat(s.captureFilePath(id)); err == nil { - return false, fs.ErrExist - } else if !errors.Is(err, fs.ErrNotExist) { - return false, err - } - raw, err := json.Marshal(captureIdentity{ServerUID: req.ServerUID, CaptureUID: req.CaptureUID}) - if err != nil { - return false, err - } - tmp, err := os.CreateTemp(s.captureDataDir, ".capture-identity-*") - if err != nil { - return false, err - } - defer func() { _ = os.Remove(tmp.Name()) }() - if _, err := tmp.Write(raw); err != nil { - _ = tmp.Close() - return false, err - } - if err := tmp.Sync(); err != nil { - _ = tmp.Close() - return false, err - } - if err := tmp.Close(); err != nil { - return false, err - } - if err := os.Link(tmp.Name(), path); err != nil { - return false, err - } - return true, nil -} - -// openCaptureRegular anchors access to the capture directory, rejecting symlinks -// and replacement between Lstat and Open. Callers supply a validated basename. -func (s *Server) openCaptureRegular(name string) (*os.File, error) { - if name != filepath.Base(name) { - return nil, fs.ErrInvalid - } - root, err := os.OpenRoot(s.captureDataDir) - if err != nil { - return nil, err - } - defer func() { _ = root.Close() }() - before, err := root.Lstat(name) - if err != nil { - return nil, err - } - if !before.Mode().IsRegular() { - return nil, fs.ErrInvalid - } - file, err := root.Open(name) - if err != nil { - return nil, err - } - after, err := file.Stat() - if err != nil || !os.SameFile(before, after) { - _ = file.Close() - return nil, fs.ErrInvalid - } - return file, nil -} - -func (s *Server) validCaptureTarget(r *http.Request) bool { - id, serverUID, captureUID := r.PathValue("id"), r.PathValue("serverUID"), r.PathValue("captureUID") - return validCaptureID(id) && captureUIDPattern.MatchString(serverUID) && captureUIDPattern.MatchString(captureUID) && serverUID == s.serverUID && r.URL.RawQuery == "" && r.URL.RawPath == "" -} - -// matchCaptureIdentity reads durable metadata, not the bounded status cache. -// Old sidecars' unbound files intentionally have no remote download path. -func (s *Server) matchCaptureIdentity(r *http.Request) bool { - if !s.validCaptureTarget(r) { - return false - } - id, serverUID, captureUID := r.PathValue("id"), r.PathValue("serverUID"), r.PathValue("captureUID") - file, err := s.openCaptureRegular("capture-" + id + ".identity.json") - if err != nil { - return false - } - defer func() { _ = file.Close() }() - raw, err := io.ReadAll(io.LimitReader(file, 1025)) - if err != nil || len(raw) > 1024 { - return false - } - var identity captureIdentity - return json.Unmarshal(raw, &identity) == nil && identity.ServerUID == serverUID && identity.CaptureUID == captureUID -} - -// captureDataAbsent runs under s.mu after target validation and the busy check. -// Lstat counts even dangling symlinks as present. An inaccessible directory or -// any error other than a missing entry cannot acknowledge cleanup. -func (s *Server) captureDataAbsent(id string) bool { - root, err := os.OpenRoot(s.captureDataDir) - if err != nil { - return false - } - defer func() { _ = root.Close() }() - for _, suffix := range []string{".identity.json", ".pcapng"} { - if _, err := root.Lstat("capture-" + id + suffix); !errors.Is(err, fs.ErrNotExist) { - return false - } - } - return true -} - -// HandleBoundDownload opens the immutable pair while locked; a later deletion -// cannot switch an existing stream to a same-name replacement. -func (s *Server) HandleBoundDownload(w http.ResponseWriter, r *http.Request) { - s.mu.Lock() - if !s.matchCaptureIdentity(r) { - s.mu.Unlock() - http.NotFound(w, r) - return - } - id := r.PathValue("id") - if s.captureBusyLocked(id) { - s.mu.Unlock() - http.Error(w, "capture is still running", http.StatusConflict) - return - } - file, err := s.openCaptureRegular("capture-" + id + ".pcapng") - s.mu.Unlock() - if err != nil { - if errors.Is(err, fs.ErrNotExist) { - http.Error(w, "capture file has been deleted", http.StatusGone) - } else { - http.Error(w, "capture file unavailable", http.StatusInternalServerError) - } - return - } - defer func() { _ = file.Close() }() - stat, err := file.Stat() - if err != nil { - http.Error(w, "capture file unavailable", http.StatusInternalServerError) - return - } - name := fmt.Sprintf("capture-%s.pcapng", id) - w.Header().Set("Content-Type", "application/vnd.tcpdump.pcap") - w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", name)) - http.ServeContent(w, r, name, stat.ModTime(), file) -} - -// HandleBoundDelete never removes a file whose persisted identities differ. -func (s *Server) HandleBoundDelete(w http.ResponseWriter, r *http.Request) { - s.mu.Lock() - defer s.mu.Unlock() - if !s.validCaptureTarget(r) { - http.NotFound(w, r) - return - } - id := r.PathValue("id") - if s.captureBusyLocked(id) { - http.Error(w, "capture is still running", http.StatusConflict) - return - } - if s.captureDataAbsent(id) { - http.Error(w, "capture data already absent", http.StatusGone) - return - } - if !s.matchCaptureIdentity(r) { - http.NotFound(w, r) - return - } - if err := os.Remove(s.captureFilePath(id)); err != nil && !errors.Is(err, fs.ErrNotExist) { - http.Error(w, "capture file cleanup failed", http.StatusInternalServerError) - return - } - // Keep this exact identity as a tombstone so retries after a lost response - // or failed CR deletion still acknowledge cleanup without trusting a 404. - now := time.Now() - if err := os.Chtimes(s.captureIdentityPath(id), now, now); err != nil { - http.Error(w, "capture cleanup acknowledgement unavailable", http.StatusInternalServerError) - return - } - w.WriteHeader(http.StatusNoContent) -} - -func hasControlIdentity(r *http.Request) bool { - return len(r.Header.Values("X-Gameplane-Server-UID")) > 0 || len(r.Header.Values("X-Gameplane-Capture-UID")) > 0 -} - -func (s *Server) controlIdentityMatches(r *http.Request, state *captureState) bool { - if !hasControlIdentity(r) { - return state != nil - } - serverUID, captureUID := r.Header.Get("X-Gameplane-Server-UID"), r.Header.Get("X-Gameplane-Capture-UID") - return state != nil && captureUIDPattern.MatchString(serverUID) && captureUIDPattern.MatchString(captureUID) && serverUID == s.serverUID && state.serverUID == serverUID && state.captureUID == captureUID -} - -// finish publishes a completed-cache entry before flushing. Its state remains -// running until Close finishes, so it must continue to block file operations. -func (s *Server) captureBusyLocked(id string) bool { - if s.currentCapture != nil && s.currentCapture.id == id { - return true - } - if s.finishingCapture != nil && s.finishingCapture.id == id { - return true - } - state := s.completed[id] - return state != nil && state.snapshot().status == statusRunning -} - -// Seven days is the CRD's maximum retention. Only file-less tombstones older -// than that window are reclaimed; live PCAP bindings remain immutable. Cap the -// tiny metadata files as well, so a long-lived pod cannot exhaust its inodes. -func (s *Server) pruneCaptureTombstones() error { - paths, err := filepath.Glob(filepath.Join(s.captureDataDir, "capture-*.identity.json")) - if err != nil { - return err - } - remaining := 0 - for _, path := range paths { - id := strings.TrimSuffix(strings.TrimPrefix(filepath.Base(path), "capture-"), ".identity.json") - if !validCaptureID(id) { - continue - } - info, err := os.Lstat(path) - if err != nil { - return err - } - _, fileErr := os.Lstat(s.captureFilePath(id)) - if info.Mode().IsRegular() && time.Since(info.ModTime()) > 7*24*time.Hour && errors.Is(fileErr, fs.ErrNotExist) { - if err := os.Remove(path); err != nil { - return err - } - } else { - remaining++ - } - } - if remaining >= 4096 { - return errCaptureIdentityBudget - } - return nil -} diff --git a/capture-sidecar/internal/httpserver/identity_test.go b/capture-sidecar/internal/httpserver/identity_test.go deleted file mode 100644 index 2b9855755..000000000 --- a/capture-sidecar/internal/httpserver/identity_test.go +++ /dev/null @@ -1,273 +0,0 @@ -package httpserver - -import ( - "context" - "errors" - "io/fs" - "net/http" - "net/http/httptest" - "os" - "path/filepath" - "strings" - "testing" - "time" -) - -func seedBoundCapture(t *testing.T, s *Server, id string) { - t.Helper() - if _, err := s.prepareCaptureBinding(id, startRequest{ServerUID: "server-uid", CaptureUID: "capture-uid"}); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(s.captureFilePath(id), []byte("0123456789"), 0o600); err != nil { - t.Fatal(err) - } -} - -func TestBoundCaptureSurvivesRestartAndRejectsReplacement(t *testing.T) { - s, _ := newTestServer(t) - s.serverUID = "server-uid" - seedBoundCapture(t, s, "cap-one") - // A new server has neither active state nor the bounded completed cache. - restarted := NewServer(context.Background(), s.captureDataDir, 0, "server-uid") - path := "/v1/targets/server-uid/captures/cap-one/uids/capture-uid/file" - for _, method := range []string{http.MethodGet, http.MethodDelete} { - for _, wrong := range []string{strings.Replace(path, "server-uid", "new-server", 1), strings.Replace(path, "capture-uid", "new-capture", 1), path + "?url=http://elsewhere"} { - rr := httptest.NewRecorder() - restarted.Routes(nil).ServeHTTP(rr, httptest.NewRequestWithContext(t.Context(), method, wrong, nil)) - if rr.Code != http.StatusNotFound { - t.Fatalf("%s %s: %d", method, wrong, rr.Code) - } - } - } - req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, path, nil) - req.Header.Set("Range", "bytes=2-5") - rr := httptest.NewRecorder() - restarted.Routes(nil).ServeHTTP(rr, req) - if rr.Code != http.StatusPartialContent || rr.Body.String() != "2345" || rr.Header().Get("Content-Range") != "bytes 2-5/10" { - t.Fatalf("range: %d %q %v", rr.Code, rr.Body.String(), rr.Header()) - } - rr = httptest.NewRecorder() - restarted.Routes(nil).ServeHTTP(rr, httptest.NewRequestWithContext(t.Context(), http.MethodDelete, path, nil)) - if rr.Code != http.StatusNoContent { - t.Fatal(rr.Code) - } - if _, err := os.Stat(s.captureFilePath("cap-one")); !errors.Is(err, fs.ErrNotExist) { - t.Fatalf("PCAP retained: %v", err) - } - // Lost-response retry preserves an explicit acknowledgement for the same UID. - rr = httptest.NewRecorder() - restarted.Routes(nil).ServeHTTP(rr, httptest.NewRequestWithContext(t.Context(), http.MethodDelete, path, nil)) - if rr.Code != 204 { - t.Fatal(rr.Code) - } - rr = httptest.NewRecorder() - restarted.Routes(nil).ServeHTTP(rr, httptest.NewRequestWithContext(t.Context(), http.MethodGet, path, nil)) - if rr.Code != 410 { - t.Fatal(rr.Code) - } -} - -func TestBoundCaptureRefusesUnboundAndRetainedNameReuse(t *testing.T) { - s, _ := newTestServer(t) - s.serverUID = "server-uid" - seedBoundCapture(t, s, "cap-bound") - for _, identity := range []startRequest{{}, {ServerUID: "server-uid", CaptureUID: "capture-uid"}, {ServerUID: "server-uid", CaptureUID: "new-uid"}} { - if _, err := s.prepareCaptureBinding("cap-bound", identity); !errors.Is(err, fs.ErrExist) { - t.Fatalf("reused bound name: %v", err) - } - } - if err := os.WriteFile(s.captureFilePath("cap-legacy"), []byte("legacy"), 0o600); err != nil { - t.Fatal(err) - } - for _, method := range []string{http.MethodGet, http.MethodDelete} { - rr := httptest.NewRecorder() - s.Routes(nil).ServeHTTP(rr, httptest.NewRequestWithContext(t.Context(), method, "/v1/targets/server-uid/captures/cap-legacy/uids/capture-uid/file", nil)) - if rr.Code != http.StatusNotFound { - t.Fatalf("legacy %s: %d", method, rr.Code) - } - } - rr := httptest.NewRecorder() - s.Routes(nil).ServeHTTP(rr, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/captures/cap-legacy/file", nil)) - if rr.Code != http.StatusOK || rr.Body.String() != "legacy" { - t.Fatalf("legacy local download: %d %q", rr.Code, rr.Body.String()) - } -} - -func TestCaptureStartIdentityAndAuthenticatedBoundRoutes(t *testing.T) { - s, factory := newTestServer(t) - s.serverUID = "server-uid" - for _, identity := range []string{`"serverUID":"other","captureUID":"capture-uid"`, `"serverUID":"server-uid"`, `"captureUID":"../escape"`} { - body := `{` + identity + `,"filter":"tcp port 12345","maxDurationSeconds":60,"maxSizeBytes":4096}` - rr := httptest.NewRecorder() - s.Routes(nil).ServeHTTP(rr, httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/captures/cap-start/start", strings.NewReader(body))) - if rr.Code != http.StatusBadRequest || factory.count() != 0 { - t.Fatalf("identity opened capture: %d sources=%d", rr.Code, factory.count()) - } - } - seedBoundCapture(t, s, "cap-auth") - wrapped := s.Routes(func(_ http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { http.Error(w, "unauthorized", http.StatusUnauthorized) }) - }) - for _, method := range []string{http.MethodGet, http.MethodDelete} { - rr := httptest.NewRecorder() - wrapped.ServeHTTP(rr, httptest.NewRequestWithContext(t.Context(), method, "/v1/targets/server-uid/captures/cap-auth/uids/capture-uid/file", nil)) - if rr.Code != http.StatusUnauthorized { - t.Fatalf("unwrapped route: %d", rr.Code) - } - } -} - -func TestControlIdentityCannotAdoptOrStopNamesake(t *testing.T) { - s, _ := newTestServer(t) - s.serverUID = "server-uid" - body := `{"serverUID":"server-uid","captureUID":"capture-uid","filter":"tcp port 12345","maxDurationSeconds":60,"maxSizeBytes":4096}` - router := s.Routes(nil) - rr := httptest.NewRecorder() - router.ServeHTTP(rr, httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/captures/cap-one/start", strings.NewReader(body))) - if rr.Code != 200 { - t.Fatalf("start: %d %s", rr.Code, rr.Body) - } - for _, op := range []struct{ method, path string }{{http.MethodGet, "/captures/cap-one/status"}, {http.MethodPost, "/captures/cap-one/stop"}, {http.MethodDelete, "/captures/cap-one"}} { - req := httptest.NewRequestWithContext(t.Context(), op.method, op.path, nil) - req.Header.Set("X-Gameplane-Server-UID", "server-uid") - req.Header.Set("X-Gameplane-Capture-UID", "replacement") - rr = httptest.NewRecorder() - router.ServeHTTP(rr, req) - if rr.Code != 404 { - t.Fatalf("replacement %s: %d", op.path, rr.Code) - } - } - req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/captures/cap-one/stop", nil) - req.Header.Set("X-Gameplane-Server-UID", "server-uid") - req.Header.Set("X-Gameplane-Capture-UID", "capture-uid") - rr = httptest.NewRecorder() - router.ServeHTTP(rr, req) - if rr.Code != 200 { - t.Fatalf("bound stop: %d %s", rr.Code, rr.Body) - } - rr = httptest.NewRecorder() - router.ServeHTTP(rr, httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/captures/cap-one/start", strings.NewReader(strings.Replace(body, "capture-uid", "new-uid", 1)))) - if rr.Code != 409 { - t.Fatalf("reused retained name: %d", rr.Code) - } -} - -func TestCaptureTombstoneRetentionAndFinalization(t *testing.T) { - s, _ := newTestServer(t) - s.serverUID = "server-uid" - seedBoundCapture(t, s, "cap-one") - s.finishingCapture = &captureState{id: "cap-one", status: statusRunning} - for _, method := range []string{http.MethodGet, http.MethodDelete} { - rr := httptest.NewRecorder() - s.Routes(nil).ServeHTTP(rr, httptest.NewRequestWithContext(t.Context(), method, "/v1/targets/server-uid/captures/cap-one/uids/capture-uid/file", nil)) - if rr.Code != 409 { - t.Fatalf("finalizing %s: %d", method, rr.Code) - } - } - s.finishingCapture = nil - if err := os.Remove(s.captureFilePath("cap-one")); err != nil { - t.Fatal(err) - } - old := time.Now().Add(-8 * 24 * time.Hour) - if err := os.Chtimes(s.captureIdentityPath("cap-one"), old, old); err != nil { - t.Fatal(err) - } - if _, err := s.prepareCaptureBinding("cap-one", startRequest{ServerUID: "server-uid", CaptureUID: "replacement"}); err != nil { - t.Fatalf("expired tombstone was not reclaimed: %v", err) - } - rr := httptest.NewRecorder() - s.Routes(nil).ServeHTTP(rr, httptest.NewRequestWithContext(t.Context(), http.MethodDelete, "/v1/targets/server-uid/captures/cap-one/uids/capture-uid/file", nil)) - if rr.Code != 404 { - t.Fatalf("stale UID after reuse: %d", rr.Code) - } -} - -func TestCaptureFileOpenCannotEscapeRoot(t *testing.T) { - s, _ := newTestServer(t) - for _, name := range []string{"../outside", filepath.Join(t.TempDir(), "outside")} { - if file, err := s.openCaptureRegular(name); err == nil { - _ = file.Close() - t.Fatalf("accepted outside path %q", name) - } - } - outside := filepath.Join(t.TempDir(), "private") - if err := os.WriteFile(outside, []byte("outside"), 0o600); err != nil { - t.Fatal(err) - } - if err := os.Symlink(outside, filepath.Join(s.captureDataDir, "capture-link.pcapng")); err != nil { - t.Skipf("symlinks unavailable: %v", err) - } - if file, err := s.openCaptureRegular("capture-link.pcapng"); err == nil { - _ = file.Close() - t.Fatal("followed capture symlink") - } -} - -func TestBoundDeleteAcknowledgesAbsentCapture(t *testing.T) { - for _, scenario := range []string{"absent", "wrong server", "query", "invalid UID", "corrupt identity", "wrong identity", "unbound PCAP", "identity symlink", "PCAP symlink", "unavailable directory", "active", "finishing", "flushing"} { - t.Run(scenario, func(t *testing.T) { - s, _ := newTestServer(t) - s.serverUID = "server-uid" - path := "/v1/targets/server-uid/captures/cap-one/uids/capture-uid/file" - want := http.StatusNotFound - t.Cleanup(func() { - s.currentCapture, s.finishingCapture = nil, nil - delete(s.completed, "cap-one") - }) - write := func(path, data string) { - t.Helper() - if err := os.WriteFile(path, []byte(data), 0o600); err != nil { - t.Fatal(err) - } - } - switch scenario { - case "absent": - want = http.StatusGone - case "wrong server": - path = strings.Replace(path, "server-uid", "replacement", 1) - case "query": - path += "?extra=true" - case "invalid UID": - path = strings.Replace(path, "capture-uid", "bad_uid", 1) - case "corrupt identity": - write(s.captureIdentityPath("cap-one"), "{") - case "wrong identity": - write(s.captureIdentityPath("cap-one"), `{"serverUID":"server-uid","captureUID":"replacement"}`) - case "unbound PCAP": - write(s.captureFilePath("cap-one"), "legacy") - case "identity symlink", "PCAP symlink": - link := s.captureIdentityPath("cap-one") - if scenario == "PCAP symlink" { - link = s.captureFilePath("cap-one") - } - // A dangling symlink is not positive evidence of an absent entry. - if err := os.Symlink(filepath.Join(t.TempDir(), "missing"), link); err != nil { - t.Fatal(err) - } - case "unavailable directory": - s.captureDataDir = filepath.Join(s.captureDataDir, "missing") - case "active": - s.currentCapture = &captureState{id: "cap-one", status: statusRunning} - want = http.StatusConflict - case "finishing": - s.finishingCapture = &captureState{id: "cap-one", status: statusRunning} - want = http.StatusConflict - case "flushing": - s.completed["cap-one"] = &captureState{id: "cap-one", status: statusRunning} - want = http.StatusConflict - } - rr := httptest.NewRecorder() - s.Routes(nil).ServeHTTP(rr, httptest.NewRequestWithContext(t.Context(), http.MethodDelete, path, nil)) - if rr.Code != want { - t.Fatalf("delete=%d %s; want=%d", rr.Code, rr.Body, want) - } - if scenario == "absent" { - rr = httptest.NewRecorder() - s.Routes(nil).ServeHTTP(rr, httptest.NewRequestWithContext(t.Context(), http.MethodGet, path, nil)) - if rr.Code != http.StatusNotFound { - t.Fatalf("unbound download=%d", rr.Code) - } - } - }) - } -} diff --git a/capture-sidecar/internal/nodecapture/worker.go b/capture-sidecar/internal/nodecapture/worker.go deleted file mode 100644 index 4a8e8acaf..000000000 --- a/capture-sidecar/internal/nodecapture/worker.go +++ /dev/null @@ -1,277 +0,0 @@ -// Package nodecapture runs one bounded capture against an operator-selected -// containerd game process. It never accepts a host PID or filesystem path. -package nodecapture - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "os" - "path/filepath" - "regexp" - "runtime" - "strconv" - "strings" - "time" - - "github.com/GameplanePanel/gameplane/capture-sidecar/internal/capture" - "golang.org/x/sys/unix" -) - -var identityPattern = regexp.MustCompile(`^[A-Za-z0-9-]{1,128}$`) -var podPattern = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`) -var containerPattern = regexp.MustCompile(`^containerd://[0-9a-f]{64}$`) -var capturePattern = regexp.MustCompile(`^[A-Za-z0-9_-]{1,64}$`) - -// The separate artifact server reads finalized files through the dedicated PVC group. -const artifactMode os.FileMode = 0o640 - -// Config contains immutable identities copied from live Kubernetes objects. -type Config struct { - ServerUID string `json:"serverUID"` - CaptureUID string `json:"captureUID"` - CaptureID string `json:"captureID"` - PodUID string `json:"podUID"` - ContainerID string `json:"containerID"` - Node string `json:"node"` - Filter string `json:"filter"` - DurationSeconds int64 `json:"durationSeconds"` - MaxSizeBytes int64 `json:"maxSizeBytes"` -} - -// Validate rejects unsupported runtimes, unconstrained captures and paths. -func (c Config) Validate() error { - if !identityPattern.MatchString(c.ServerUID) || !identityPattern.MatchString(c.CaptureUID) || !capturePattern.MatchString(c.CaptureID) || !podPattern.MatchString(c.PodUID) || !containerPattern.MatchString(c.ContainerID) || c.Node == "" || c.Filter == "" || len(c.Filter) > 1024 || c.DurationSeconds < 1 || c.DurationSeconds > 3600 || c.MaxSizeBytes < 1 || c.MaxSizeBytes > 900*1024*1024 { - return errors.New("invalid node capture identity, runtime, filter or limits") - } - return nil -} - -// Result is written atomically only after the PCAP has been closed. -type Result struct { - ServerUID string `json:"serverUID"` - CaptureUID string `json:"captureUID"` - CaptureID string `json:"captureId"` - Status string `json:"status"` - PacketsWritten int64 `json:"packetsWritten"` - BytesWritten int64 `json:"bytesWritten"` - Message string `json:"message"` -} - -func matchesCgroup(body, pod, id string) bool { - for _, line := range strings.Split(body, "\n") { - parts := strings.SplitN(line, ":", 3) - if len(parts) != 3 { - continue - } - p := parts[2] - podMatch := strings.Contains(p, "/pod"+pod+"/") || strings.Contains(p, "-pod"+strings.ReplaceAll(pod, "-", "_")+".slice/") - containerMatch := strings.HasSuffix(p, "/"+id) || strings.HasSuffix(p, "/cri-containerd-"+id+".scope") - if podMatch && containerMatch { - return true - } - } - return false -} - -type targetProcess struct { - root *os.Root - namespace *os.File - pod, id string -} - -func (t *targetProcess) close() { _ = t.namespace.Close(); _ = t.root.Close() } -func (t *targetProcess) verify() error { - body, err := t.root.ReadFile("cgroup") - if err != nil || !matchesCgroup(string(body), t.pod, t.id) { - return errors.New("target container identity changed") - } - return nil -} - -func findTarget(c Config) (*targetProcess, error) { - entries, err := os.ReadDir("/proc") - if err != nil { - return nil, fmt.Errorf("read host processes: %w", err) - } - id := strings.TrimPrefix(c.ContainerID, "containerd://") - for _, entry := range entries { - if !entry.IsDir() { - continue - } - if _, err := strconv.Atoi(entry.Name()); err != nil { - continue - } - root, err := os.OpenRoot(filepath.Join("/proc", entry.Name())) - if err != nil { - continue - } - body, err := root.ReadFile("cgroup") - if err != nil || !matchesCgroup(string(body), c.PodUID, id) { - _ = root.Close() - continue - } - // /proc namespace descriptors are magic symlinks, so os.Root correctly - // refuses Open on them. Open through this already-verified numeric PID, - // then verify the pinned proc directory again before and after setns. - ns, err := os.Open(filepath.Join("/proc", entry.Name(), "ns/net")) - if err != nil { - _ = root.Close() - return nil, fmt.Errorf("open target network namespace: %w", err) - } - t := &targetProcess{root: root, namespace: ns, pod: c.PodUID, id: id} - if err := t.verify(); err != nil { - t.close() - return nil, err - } - return t, nil - } - return nil, errors.New("containerd target process not found on selected node") -} - -func (t *targetProcess) source(filter string) (capture.PacketSource, error) { - type opened struct { - s capture.PacketSource - err error - } - done := make(chan opened, 1) - go func() { - // Never return a thread in the target netns to Go's thread pool. - // A goroutine exiting with its OS thread locked terminates that thread; - // the AF_PACKET descriptor remains bound to the original target netns. - runtime.LockOSThread() - if err := t.verify(); err != nil { - done <- opened{err: err} - return - } - if err := unix.Setns(int(t.namespace.Fd()), unix.CLONE_NEWNET); err != nil { - done <- opened{err: fmt.Errorf("enter target network namespace: %w", err)} - return - } - if err := t.verify(); err != nil { - done <- opened{err: err} - return - } - s, err := capture.NewAFPacketSource("eth0", 0, filter) - done <- opened{s: s, err: err} - }() - r := <-done - return r.s, r.err -} - -// Run captures once and exits. SIGTERM cancels ctx and finalizes the file; -// controller completion waits for worker Pods to disappear before publishing. -func Run(ctx context.Context, c Config, dir string) error { - if err := c.Validate(); err != nil { - return err - } - target, err := findTarget(c) - if err != nil { - return err - } - defer target.close() - source, err := target.source(c.Filter) - if err != nil { - return err - } - defer func() { _ = source.Close() }() - return runCapture(ctx, c, dir, source, target.verify) -} - -func runCapture(ctx context.Context, c Config, dir string, source capture.PacketSource, verify func() error) error { - identity, err := json.Marshal(map[string]string{"serverUID": c.ServerUID, "captureUID": c.CaptureUID}) - if err != nil { - return err - } - output, err := os.OpenRoot(dir) - if err != nil { - return fmt.Errorf("open capture output directory: %w", err) - } - defer func() { _ = output.Close() }() - identityName := "capture-" + c.CaptureID + ".identity.json" - f, err := output.OpenFile(identityName, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600) - if err != nil { - return fmt.Errorf("reserve capture identity: %w", err) - } - if _, err = f.Write(identity); err != nil { - _ = f.Close() - return err - } - if err = f.Close(); err != nil { - return err - } - // fsGroup grants the nonroot artifact server access after the worker exits. - if err = output.Chmod(identityName, artifactMode); err != nil { - return err - } - writer, err := capture.NewWriter(filepath.Join(dir, "capture-"+c.CaptureID+".pcapng"), c.DurationSeconds, c.MaxSizeBytes, 0, c.Filter) - if err != nil { - return err - } - ctx, cancel := context.WithTimeout(ctx, time.Duration(c.DurationSeconds)*time.Second) - defer cancel() - identityChanged := make(chan struct{}, 1) - go func() { - ticker := time.NewTicker(250 * time.Millisecond) - defer ticker.Stop() - for { - select { - case <-ctx.Done(): - return - case <-ticker.C: - if verify() != nil { - identityChanged <- struct{}{} - cancel() - return - } - } - } - }() - result := Result{ServerUID: c.ServerUID, CaptureUID: c.CaptureUID, CaptureID: c.CaptureID, Status: "completed"} - for { - packet, err := source.ReadPacket(ctx) - if err != nil { - if ctx.Err() == nil { - result.Status = "failed" - result.Message = "packet source failed" - } - break - } - if err := writer.WritePacket(packet); err != nil { - if !errors.Is(err, capture.ErrLimitReached) { - result.Status = "failed" - result.Message = "capture write failed" - } - break - } - } - select { - case <-identityChanged: - result.Status = "failed" - result.Message = "target container identity changed" - default: - } - if verify() != nil { - result.Status = "failed" - result.Message = "target container identity changed" - } - if err := writer.Close(); err != nil { - result.Status = "failed" - result.Message = "capture finalization failed" - } - result.PacketsWritten = writer.PacketsWritten() - result.BytesWritten = writer.BytesWritten() - if err := output.Chmod("capture-"+c.CaptureID+".pcapng", artifactMode); err != nil { - return err - } - raw, err := json.Marshal(result) - if err != nil { - return err - } - path := "capture-" + c.CaptureID + ".result.json" - if err := output.WriteFile(path+".tmp", raw, artifactMode); err != nil { - return err - } - return output.Rename(path+".tmp", path) -} diff --git a/capture-sidecar/internal/nodecapture/worker_test.go b/capture-sidecar/internal/nodecapture/worker_test.go deleted file mode 100644 index ccb349f13..000000000 --- a/capture-sidecar/internal/nodecapture/worker_test.go +++ /dev/null @@ -1,97 +0,0 @@ -package nodecapture - -import ( - "context" - "encoding/json" - "errors" - "os" - "path/filepath" - "strings" - "testing" - - "github.com/GameplanePanel/gameplane/capture-sidecar/internal/capture" -) - -func TestCgroupIdentityMatchesExactPodAndContainer(t *testing.T) { - pod := "11111111-2222-3333-4444-555555555555" - id := strings.Repeat("a", 64) - for _, test := range []struct { - name, cgroup string - want bool - }{ - {"systemd", "0::/kubepods.slice/kubepods-burstable-pod" + strings.ReplaceAll(pod, "-", "_") + ".slice/cri-containerd-" + id + ".scope\n", true}, - {"cgroupfs", "0::/kubepods/burstable/pod" + pod + "/" + id + "\n", true}, - {"other-pod", "0::/kubepods/pod99999999-2222-3333-4444-555555555555/" + id + "\n", false}, - {"container-prefix", "0::/kubepods/pod" + pod + "/" + id + "a\n", false}, - {"host", "0::/system.slice/containerd.service\n", false}, - } { - t.Run(test.name, func(t *testing.T) { - if got := matchesCgroup(test.cgroup, pod, id); got != test.want { - t.Fatalf("identity match=%t want %t", got, test.want) - } - }) - } -} - -type endingSource struct{ err error } - -func (s endingSource) ReadPacket(context.Context) (*capture.RawPacket, error) { return nil, s.err } -func (endingSource) Close() error { return nil } - -func TestRunCapturePublishesOnlyFinalizedIdentityBoundResult(t *testing.T) { - for _, changed := range []bool{false, true} { - t.Run(map[bool]string{false: "canceled", true: "identity-changed"}[changed], func(t *testing.T) { - dir := t.TempDir() - ctx, cancel := context.WithCancel(t.Context()) - cancel() - c := Config{ServerUID: "server", CaptureUID: "capture", CaptureID: "cap", DurationSeconds: 1, MaxSizeBytes: 4096, Filter: "tcp port 25565"} - verify := func() error { - if changed { - return errors.New("replaced") - } - return nil - } - if err := runCapture(ctx, c, dir, endingSource{context.Canceled}, verify); err != nil { - t.Fatal(err) - } - raw, err := os.ReadFile(filepath.Join(dir, "capture-cap.result.json")) - if err != nil { - t.Fatal(err) - } - var result Result - if err := json.Unmarshal(raw, &result); err != nil { - t.Fatal(err) - } - want := "completed" - if changed { - want = "failed" - } - if result.Status != want || result.ServerUID != "server" || result.CaptureUID != "capture" || result.BytesWritten <= 0 { - t.Fatalf("invalid result: %+v", result) - } - for _, name := range []string{"capture-cap.identity.json", "capture-cap.pcapng", "capture-cap.result.json"} { - stat, err := os.Stat(filepath.Join(dir, name)) - if err != nil || stat.Mode().Perm() != 0o640 { - t.Fatalf("artifact %s mode: %v %v", name, stat, err) - } - } - if err := runCapture(ctx, c, dir, endingSource{context.Canceled}, verify); err == nil { - t.Fatal("reused existing capture identity") - } - }) - } -} - -func TestWorkerRejectsUnsafeConfiguration(t *testing.T) { - c := Config{ServerUID: "server-uid", CaptureUID: "capture-uid", CaptureID: "cap-test", PodUID: "11111111-2222-3333-4444-555555555555", ContainerID: "containerd://" + strings.Repeat("a", 64), Node: "node", Filter: "tcp port 25565", DurationSeconds: 60, MaxSizeBytes: 1024} - if err := c.Validate(); err != nil { - t.Fatal(err) - } - for _, mutate := range []func(*Config){func(c *Config) { c.ContainerID = "docker://" + strings.Repeat("a", 64) }, func(c *Config) { c.CaptureID = "../../host" }, func(c *Config) { c.PodUID = "" }, func(c *Config) { c.DurationSeconds = 3601 }, func(c *Config) { c.MaxSizeBytes = 1 << 30 }, func(c *Config) { c.Filter = "" }} { - bad := c - mutate(&bad) - if bad.Validate() == nil { - t.Fatalf("accepted unsafe config: %+v", bad) - } - } -} diff --git a/capture-sidecar/specs.md b/capture-sidecar/specs.md deleted file mode 100644 index b6bb81ace..000000000 --- a/capture-sidecar/specs.md +++ /dev/null @@ -1,345 +0,0 @@ -# capture-sidecar — Specification - -**Status:** pre-v1 (v0.4.0), Phase 2 Foundational (implementation complete) -**Module / command:** `github.com/GameplanePanel/gameplane/capture-sidecar` -**Dependencies (current):** stdlib + external libraries for packet capture and filtering (github.com/gopacket/gopacket v1.7.2, github.com/packetcap/go-pcap, golang.org/x/net) - -## Purpose - -### Separate node diagnostic worker (#714) - -The image also contains `/capture-tool` without file capabilities. Its -`--node-worker` mode accepts only an operator-generated JSON identity tuple -(GameServer/NetworkCapture/Pod UIDs, node, exact containerd ID), filter and -bounded limits. It discovers a process through exact Pod/container cgroup -matching, pins proc/network namespace descriptors, verifies cgroups immediately -before/after setns on a dedicated locked OS thread, then opens an eth0 AF_PACKET -socket. The locked thread exits; it is never returned to the thread pool. -Ongoing identity checks cancel capture, including idle packet streams. No host -PID/path, socket, mount or Kubernetes token is supplied. Linux/containerd, -systemd/cgroupfs paths are supported; other runtimes and host networking fail. - -PCAP, identity and atomically published result files are group-readable only -after finalization. A separate nonroot `--artifacts-only` process exposes -UID-bound download/delete and header-bound status, never start/stop/raw socket -operations. The controller removes the privileged Job/Pods before publishing -completion. SIGTERM finalizes a partial capture; changed identity publishes a -failed result. Host capability blast radius remains node-wide despite the -per-server authorization and exact target selection. - -Optional packet capture sidecar injected into game pods to record network traffic for protocol reverse-engineering. The sidecar will use AF_PACKET live capture to collect packets matching a BPF filter expression, write them to a PCAPNG file on a pre-provisioned emptyDir volume, and expose a mTLS-authenticated HTTP control endpoint (`:9091`) for the operator and API to start/stop/monitor captures and download the resulting files. - -> **Current state:** Full implementation with AF_PACKET socket handling, PCAPNG writing, BPF filter compilation, mTLS authentication, and HTTP control endpoint. Real dependencies (gopacket, go-pcap) are pinned in go.mod. Unit tests for capture, filter, writer, and handlers are co-located with their implementations. TTL-based expiry reconciliation (`NetworkCaptureReconciler.expireCapture`, `operator/internal/controller/networkcapture_controller.go`) and the dashboard UI (`web/src/components/CaptureWidget.tsx`, `web/src/routes/tabs/settings/NetworkCapture.tsx`) are both implemented — see "Planned" below for the one remaining gap (F-190). - -## Responsibilities (Design) - -### Remote capture identity - -Remote gateway downloads and cleanup require the GameServer UID and -NetworkCapture UID, in addition to the capture name. The operator supplies these -identities when starting a capture and injects the GameServer UID into the -sidecar. The sidecar persists the capture's identity beside its data so a -restart or bounded in-memory history eviction cannot lose the binding. A reused -name, different server identity or legacy unbound capture cannot use the remote -route. Existing local control routes remain compatible; mTLS, path validation, -completion checks and file lifetime rules still apply. The gateway exposes only -the explicit download and cleanup operations, never arbitrary sidecar proxying. -Bound cleanup retains an identity tombstone after removing the PCAP, so a retry -for the same UIDs can confirm deletion while another UID remains rejected. -DELETE returns 204 for this matching binding, including tombstone retries. It -returns 410 only after validating the route and current server UID, ruling out -active or flushing writers, and confirming that both identity and PCAP entries -are absent in the capture directory. Dangling symlinks, inaccessible storage, -unbound PCAPs and mismatched identities do not count as absence. Downloads keep -their existing identity requirement; a generic 404 is never cleanup proof. - -These are the design responsibilities for the completed sidecar (Phase 2+): - -1. Bind an AF_PACKET socket to the pod's primary network interface and enter live capture mode. -2. Accept a compiled BPF filter expression and apply it in the kernel and again before a frame can reach the capture writer. -3. Write captured packets to a PCAPNG file on `/tmp/captures` using standard `gopacket/pcapgo.NgWriter` format, readable by `tcpdump`, Wireshark, and other third-party tools. -4. Enforce hard duration and size limits: stop capturing when `(now - startTime) >= maxDurationSeconds` or `bytesWritten >= maxSizeBytes`, whichever comes first. -5. Serve an mTLS-authenticated HTTP control endpoint on `0.0.0.0:9091` with six operations: start a capture (`POST /captures/{id}/start`), stop a capture (`POST /captures/{id}/stop`), poll status (`GET /captures/{id}/status`), download the completed file (`GET /captures/{id}/file`), delete a finished capture's file (`DELETE /captures/{id}`), and an unauthenticated-at-the-mux-level liveness check (`GET /healthz`, see Security Considerations #1 and F-193). -6. Validate mTLS certificates against the cluster CA and reject unauthenticated requests. -7. Prevent multiple simultaneous captures on the same sidecar instance (409 Conflict if a duplicate capture ID arrives while one is running). -8. Monitor disk space and gracefully stop a capture if the emptyDir volume fills (`ENOSPC` handling). -8a. Refuse to *start* a capture that would push the volume's retained (not-yet-expired) files plus the new capture's own `maxSizeBytes` past a configured budget (507 Insufficient Storage), so retained files alone can never accumulate past the emptyDir's `SizeLimit` and trigger a kubelet eviction of the pod (F-187). - - **Deleting a capture through the API frees its budget (F-261).** Local cleanup calls `DELETE /captures/{id}` directly over mTLS and retains its best-effort behavior if the sidecar is unreachable. Remote cleanup uses the gateway's server/capture UID-bound route. It must confirm sidecar cleanup before removing the CR; a failure retains the CR for retry. In either case the volume-budget check still counts any retained PCAP bytes and prevents new captures from exceeding the volume limit. -9. Keep capture identity metadata beside the PCAP on the Pod's emptyDir. It survives a sidecar process restart, but not Pod deletion. In-memory status history is bounded and does not replace the durable identity check; the sidecar does not automatically retry captures after restarting. - -## Non-goals / boundaries - -- Does **not** run the game server itself — that is the operator's and the game container's job. -- Does **not** authenticate operators or enforce access control — that is the API's job (RBAC applies to the API tier, not the sidecar). -- Does **not** modify game traffic or the game container — it captures passively via the shared pod network namespace. -- Does **not** rewrite completed captures — kernel filtering and the matching BPF output guard run before any packet is written. -- Does **not** persist or replicate captures across pod restarts — files live on emptyDir and are lost when the pod is deleted. -- Does **not** implement protocol parsing or protocol-specific logic — it is protocol-agnostic; filtering is done via generic BPF expressions. -- Does **not** implement a general proxy — it serves its own files over mTLS; the optional per-cluster gateway exposes only its explicit bound file operations. - -## Current Implementation (Phase 2 Foundational) - -### Directory & package layout - -``` -capture-sidecar/ -├── cmd/main.go # Entry point; mTLS server setup on :9091; HTTP handler dispatch -├── internal/ -│ ├── capture/ -│ │ ├── afpacket.go # AF_PACKET socket setup; live packet capture loop; MMap'd TPacket buffers -│ │ ├── afpacket_test.go # Unit tests for AF_PACKET socket behavior -│ │ ├── filter.go # BPF filter compilation and validation via go-pcap -│ │ ├── filter_test.go # Unit tests for filter compilation and validation -│ │ ├── writer.go # PCAPNG file writing via pcapgo.NgWriter; size/duration limit enforcement -│ │ └── writer_test.go # Unit tests for PCAPNG writing and limit enforcement -│ ├── httpserver/ -│ │ ├── handlers.go # HTTP handlers for start/stop/status/file/delete/healthz (see Endpoints below) -│ │ └── handlers_test.go # Unit tests for HTTP handlers and response shapes -│ └── auth/ -│ ├── tls.go # mTLS certificate validation; TLS listener setup -│ └── tls_test.go # Unit tests for mTLS validation -├── go.mod # Dependencies: gopacket/afpacket, gopacket/pcapgo, packetcap/go-pcap -├── go.sum -├── Dockerfile # distroless/static:nonroot base; setcap cap_net_raw+ep on the built binary -├── .testcoverage.yml # 70% coverage gate -└── specs.md # This file -``` - -Single Go module; packages organized by responsibility (capture, httpserver, auth). All packages have co-located test files exercising their behavior without root/CAP_NET_RAW/NIC dependencies. - -### Phase 2 Foundational Packages - -**`internal/capture/afpacket.go`**: Establishes AF_PACKET socket via gopacket/afpacket.TPacket with MMap'd kernel buffers. Compiles the filter and prepares its BPF VM before opening the socket, retains kernel filtering, and checks every received frame against the same program before snaplen truncation or output. Reads packets via blocking poll (respecting context cancellation) and writes to PCAPNG writer. Manages socket lifecycle (Create, Start, Stop, Close) and enforces hard size/duration limits. - -**`internal/capture/filter.go`**: Compiles BPF filter expressions via github.com/packetcap/go-pcap/filter into bytecode instructions. Validates filter syntax before capture starts (defense-in-depth, complementing API-tier validation). - -**`internal/capture/writer.go`**: Writes captured packets to PCAPNG files via gopacket/pcapgo.NgWriter. Enforces hard size and duration limits (stops immediately when either is reached). Detects disk-full conditions (`ENOSPC`) and stops the capture, marking it `failed`/`disk_full` — the partial file is kept, not deleted, and stays downloadable (see "Edge Cases" below for the verified behavior; this line described intended, not implemented, behavior). Produces valid PCAPNG files readable by `tcpdump`, Wireshark, and other third-party tools. - -**`internal/httpserver/handlers.go`**: Implements six HTTP endpoints exposed on `:9091`: `POST /captures/{id}/start`, `POST /captures/{id}/stop`, `GET /captures/{id}/status`, `GET /captures/{id}/file`, `DELETE /captures/{id}`, and `GET /healthz` (see Endpoints below for the full table). Validates requests, marshals capture state, and streams completed files to authenticated clients. `HandleStart` also enforces the volume budget (F-187): before opening a packet source, it sums the bytes of every retained `capture-*.pcapng` file already on `captureDataDir` (`retainedCaptureBytes`) and refuses the start with `507 Insufficient Storage` if that total plus the requested `maxSizeBytes` would exceed `Server.budgetBytes`. A file already deleted (expired, in this system, means deleted by the operator's retention reconciler, or removed by `HandleDelete` when the API deletes its CR — F-261) is simply absent from that sum. `budgetBytes` of `0` disables the check. - -**`internal/auth/tls.go`**: Validates mTLS certificates against the cluster CA certificate. Sets up TLS listener with enforced client certificate authentication. - -**`cmd/main.go`**: Entry point; parses environment variables for certificate paths (TLS_CERT_FILE, TLS_KEY_FILE, TLS_CA_FILE); constructs mTLS server; wires HTTP handlers and starts listening on `0.0.0.0:9091`. - -### External Dependencies (Phase 2 Foundational) - -The module declares the following external dependencies in `go.mod`: - -- `github.com/gopacket/gopacket v1.7.2` — AF_PACKET socket setup (afpacket package) and PCAPNG file writing (pcapgo package). This is the module `go.mod` actually requires; `github.com/google/gopacket` is a different module path and is not used here (F-191). -- `github.com/packetcap/go-pcap v0.0.0-20260731105150-c86974bbfbcd` — BPF filter compilation and validation -- `golang.org/x/net` — Networking utilities (bundled by gopacket) - -This module does not depend on `svcutil`: its control server is served over mTLS via `ListenAndServeTLS` with client-certificate verification, and `RunHTTP` only serves plain HTTP (`ListenAndServe`) — a plaintext listener would remove the sidecar's only authentication boundary (see the comment at `cmd/main.go:80-86`). - -## External Interface / Configuration (Phase 2 Design) - -### Environment Variables - -- **`TLS_CERT_FILE`** (required): Path to the sidecar's mTLS server certificate (e.g., `/etc/tls/tls.crt`). Comes from the `agent-tls` Secret volume. -- **`TLS_KEY_FILE`** (required): Path to the sidecar's mTLS server private key (e.g., `/etc/tls/tls.key`). -- **`TLS_CA_FILE`** (required): Path to the cluster CA certificate for validating client mTLS certificates (e.g., `/etc/tls/ca.crt`). - -All three paths are mounted from the pre-existing `agent-tls` Secret that every game pod carries (no new Secret is created for capture). - -- **`CAPTURE_VOLUME_BUDGET_BYTES`** (optional): Maximum total bytes of retained capture files plus a new capture's own `maxSizeBytes` that `HandleStart` will admit (F-187). Set by the operator's `buildCaptureEphemeralContainer` (`operator/internal/controller/gameserver_controller.go`), derived from the `captures` emptyDir's own `SizeLimit` with a 10% safety margin (`captureVolumeBudgetBytes`), so it can never drift from the volume the kubelet actually enforces. Unset or unparsable falls back to the same 1Gi-minus-10%-margin default hardcoded in `cmd/main.go` (matches `charts/gameplane/values.yaml`'s documented 1 GiB volume limit). `cmd/main.go` also exposes this as the `--capture-volume-budget-bytes` flag for standalone runs; `0` disables the check. - -### HTTP Server Configuration - -**Listen Address**: `0.0.0.0:9091` (all pod network interfaces). - -**Transport**: TLS with mTLS. All endpoints require both the sidecar's server certificate and the client's certificate (API server connecting with its own certificate). The sidecar validates the client certificate against the cluster CA. - -**Port**: The existing `-agent` Kubernetes Service exposes this port numerically as target port 9091 (alongside the existing agent port). No separate Service or port declaration is needed. - -### Endpoints - -`contracts/capture-sidecar.md` (the original design contract) describes these routes with a `:start`/`:stop` colon-suffix form, matching the chi-style convention used elsewhere in this codebase. `net/http.ServeMux` (what `Routes` in `handlers.go` actually registers on) does not accept that form — a wildcard segment must be exactly `{name}` — so the routes below are the real, implemented paths (see the doc comment on `Server.Routes` for why this had to diverge from the contract): - -| Endpoint | Method | Purpose | -|----------|--------|---------| -| `/captures/{id}/start` | POST | Start a capture with filter, duration/size limits | -| `/captures/{id}/stop` | POST | Stop a running capture; finalize and close the file | -| `/captures/{id}/status` | GET | Poll capture status (running or completed) and stats | -| `/captures/{id}/file` | GET | Download the completed PCAPNG file | -| `/captures/{id}` | DELETE | Delete a finished capture's backing file (204 on success or if already absent, 409 if the capture is still running); called by the API's `captureDelete` handler (F-261) and by the operator's retention reconciler | -| `/healthz` | GET | Liveness check; not wrapped in the mTLS middleware at the mux level, but unreachable without a client certificate regardless — see `HandleHealthz`'s doc comment (F-193). Nothing calls this route today, since ephemeral containers cannot be probed. | - -**Error responses** are plain text (e.g., `invalid filter: `, `capture 'cap-...' not found`), matching the codebase convention in `api/internal/httperr/httperr.go`. - -## Capture File Format and Guarantees (Phase 2 Design) - -### File Location - -**Path**: `/tmp/captures/capture-.pcapng` - -**Format**: PCAPNG (Pcap Next Generation), will be produced by `github.com/google/gopacket/pcapgo.NgWriter`. - -**Snaplen**: Full capture (65535 bytes per packet; no truncation). - -**Timestamp Precision**: Nanosecond precision. - -**Interfaces**: PCAPNG will include interface metadata (eth0, snaplen, filter expression recorded in the interface block). - -### Filtering Guarantee (FR-011) - -**At-Capture Filtering (Phase 2)**: The BPF filter is applied by `gopacket/afpacket.TPacket` at the kernel level. Its socket starts receiving before `SetBPF` can attach the filter, so the same compiled program also evaluates every original frame before snaplen truncation or delivery to the writer. This rejects non-matching frames already queued during socket startup. VM construction or evaluation errors fail closed; rejected frames never reach the PCAP writer. This guarantees: -- 100% of packets in the file match the filter. -- 0% of non-matching packets are included. -- No post-processing or offline filtering. - -**Filter Compilation (Phase 2)**: The sidecar will compile filter expressions locally using `github.com/packetcap/go-pcap/filter.Compile`. If compilation fails (defense-in-depth), the start request will return HTTP 400 with the syntax error. - -### Limits and Enforcement (Phase 2) - -**Duration**: Capture stops when `(now - startTime) >= maxDurationSeconds`. Hard limit; enforced by a timer. - -**Size**: Capture stops when `bytesWritten >= maxSizeBytes` (checked before each packet write; the final file size may exceed the limit by one packet, typically < 64KB overrun). Hard limit. - -**Either-Or Semantics**: Capture stops when either limit is reached first. The `stoppingReason` field in status indicates which: `max_duration_reached` or `max_size_reached`. - -## Packet Capture Pipeline (Phase 2 Design) - -### Startup Flow - -1. Receive a start request with `{filter, maxDurationSeconds, maxSizeBytes}`. -2. Compile the BPF filter using `go-pcap/filter.Compile`; reject on syntax error. -3. Set up an AF_PACKET socket with MMap'd TPacket buffers and apply the compiled filter. -4. Create and open the PCAPNG file at `/tmp/captures/capture-.pcapng`. -5. Start the capture loop: read packets from the kernel buffer, decode them via `gopacket`, write to the PCAPNG file. -6. Start a timer for the max-duration limit. -7. Return HTTP 200 with status `running`. - -### Packet Processing - -1. For each packet received: - - Check if max-size limit is reached; if so, stop and finalize. - - Check if max-duration timer expired; if so, stop and finalize. - - Write the packet to the PCAPNG file. -2. On size or duration limit: finalize and close the PCAPNG file cleanly, marking the capture `completed`. -3. On explicit stop request: finalize and close immediately. - -### Shutdown - -- On a graceful stop (explicit `:stop` or limit reached): finalize the PCAPNG file (all headers, interface blocks, packet blocks written), close the file handle, and mark status `completed`. -- On disk full (`ENOSPC` during write): stop the capture, delete the partial file, and mark status `failed`. -- On sidecar crash: the partial file is left on disk; the operator detects the missing sidecar and marks the capture `failed`. - -## Key Invariants (Design) - -1. **Filter validation before capture**. The filter is compiled and its kernel instructions and userspace VM prepared before any AF_PACKET socket is opened. An invalid filter expression is rejected with HTTP 400 before any state is created. Every received frame must pass the same BPF program before output, including frames queued before the kernel filter was installed. This is defense-in-depth; the API tier also validates filters before creating a NetworkCapture CRD. - -2. **Hard duration and size limits**. Both are enforced strictly: the capture stops as soon as either limit is reached and no further packets are accepted afterward. For the size limit specifically, the check runs *after* each packet is written (see "Edge Cases" → "Max-size auto-stop and on-disk accounting" below), so the single packet that crosses `maxSizeBytes` is included in the file — every packet after that one is rejected. The PCAPNG file is valid and complete even on a limit-triggered stop. - -3. **File capabilities grant it, not `securityContext.capabilities.add` alone**. Raw-packet access (`CAP_NET_RAW`) is granted via a file capability on the sidecar's own binary (`setcap cap_net_raw+ep`), not via Kubernetes' `securityContext.capabilities.add`. Kubernetes does not set ambient capabilities; under a non-root `runAsUser`, `add: ["NET_RAW"]` by itself grants nothing (the effective set is cleared on `execve`). The container's `securityContext.capabilities` does list `Drop: ["ALL"], Add: ["NET_RAW"]`, but the `Add` exists only to keep NET_RAW in the process's *bounding* set — `Drop: ["ALL"]` alone would empty the bounding set too, and the kernel refuses to grant a file capability at `execve` that isn't in the bounding set (EPERM). The process's effective set is still empty at start; the actual grant comes from the setcap'd binary at exec. The file capability is ignored under `no_new_privs`, which is set when `allowPrivilegeEscalation: false`; therefore, `allowPrivilegeEscalation: true` is mandatory for this container, trading off that one flag to preserve `runAsNonRoot: true`. - -4. **No capability on the game container**. The game container's `securityContext` is never modified. It retains its existing security posture and does not gain raw-packet capabilities. Elevated privileges are scoped to the capture container's own binary only. - -5. **Cannot be removed once injected**. Ephemeral containers, once injected into a running pod, cannot be removed via the Kubernetes API — the `pods/ephemeralcontainers` subresource does not support deletion. When capture is disabled on a GameServer, the sidecar container persists in `pod.status.ephemeralContainerStatuses` until the pod is next recreated (e.g., via a new StatefulSet rollout). This asymmetry is accepted and documented as a constraint. - -6. **One capture per sidecar instance**. Multiple simultaneous captures on the same sidecar are rejected with HTTP 409 (`capture '{id}' already in progress`, naming the capture that is actually running, not the rejected request's id — F-192). This is enforced in-memory; the authoritative per-GameServer concurrency lock lives in the operator's NetworkCaptureReconciler. - -7. **Exact handshake byte preservation**. The sidecar does not modify or interpret captured packets beyond filtering. The PCAPNG file preserves the exact bytes received from the kernel. - -8. **Stateless and ephemeral**. The sidecar holds no persistent state. Each sidecar instance is independent; captures are not replicated or synchronized across multiple instances. Partial files left by a crashed sidecar are cleaned up by the pod's deletion or an explicit operator action. - -## Edge Cases (US5 — implemented, verified against source) - -The "Phase 2 Design" language above (in "Packet Processing", "Shutdown", and "Security Considerations" #5) predates the actual implementation and is stale on a few points, called out below. This section describes verified behavior in `internal/capture/writer.go` and `internal/httpserver/handlers.go`. - -### Max-size auto-stop and on-disk accounting - -`Writer.WritePacket` tracks `bytesWritten` against real on-disk cost, not payload size: each packet's fixed Enhanced Packet Block overhead (28-byte header + 4-byte trailer = `epbFixedOverheadBytes`, 32 bytes) plus its snaplen-truncated payload plus 4-byte alignment padding. The check runs *after* the packet is written, so the packet that crosses `maxSizeBytes` **is** written to the file — the limit means "stop now that we've reached it", not "reject the packet that would exceed it". Every `WritePacket` call after the limit is reached returns an error wrapping `ErrLimitReached` without writing anything further. `LimitReason()` reports `max_size_reached`. - -### ENOSPC / disk-full handling - -`pcapgo.NgWriter` buffers writes through an internal 4096-byte `bufio.Writer` (verified against `github.com/gopacket/gopacket@v1.7.2` `pcapgo/ngwrite.go` — the version `go.mod` actually requires: `NewNgWriterInterface` calls `bufio.NewWriter(w)`). This means a full disk usually does **not** surface from `WritePacket` — small packets accumulate in that buffer, and a write to the real underlying file only happens once the buffer fills or `Flush`/`Close` runs. `Writer.Close` calls the PCAPNG writer's `Flush()`; if that fails with an error wrapping `syscall.ENOSPC` (checked with `errors.Is`, so it matches whether the error arrives bare or wrapped the way real file-write errors are, e.g. inside `*fs.PathError`), `Close` sets `limitReached = true` and `limitReason = LimitReasonDiskFull` (`"disk_full"`) before returning the error. `WritePacket`'s own write path performs the identical ENOSPC check, covering the case where a packet's write happens to trigger the bufio buffer's internal flush. - -**A disk-full capture is never reported as a clean "completed".** In `httpserver.Server.finish`, a non-nil error from `state.writer.Close()` always sets `status = statusFailed`, and if `errors.Is(err, syscall.ENOSPC)` it also sets `reason = reasonDiskFull` — regardless of what reason originally triggered the stop. So a duration- or size-triggered stop that *also* hits ENOSPC during its finalizing flush is still reported `failed` / `disk_full`, overriding the triggering reason. - -**The partial file is kept, not deleted.** This corrects the "will... delete the partial file" language elsewhere in this document (see "Shutdown" and "Security Considerations" #5 above): the implemented behavior deliberately retains the file. `finish`'s doc comment in handlers.go states the file "already holds real packets and stays downloadable" after any failure, disk-full included, because a partial capture is still useful for the protocol-reverse-engineering use case this feature exists for. `HandleDownload` continues to serve the file once the capture reaches a terminal state. This is an intentional design decision, not an unimplemented gap — do not add file deletion on ENOSPC to "match" the older language. - -### Max-duration auto-stop lifecycle - -`HandleStart` arms `time.AfterFunc(time.Duration(maxDurationSeconds)*time.Second, ...)` immediately after publishing the capture as `s.currentCapture`, closing over that specific `*captureState` by pointer identity. On expiry it calls `s.finish("", state, reasonMaxDuration, nil)` — the same finalization path an explicit `POST /captures/{id}/stop` uses: cancel the capture's context (stopping the AF_PACKET read loop), close the writer (flushing and finalizing the PCAPNG file), and publish the terminal status under the capture's mutex. No caller-issued `:stop` is required; `GET /captures/{id}/status` reflects the stopped state and final counters as soon as the timer's `finish` call completes. Because the match is by pointer rather than by id, a stale timer belonging to an earlier capture can never terminate a later capture that happens to reuse the same id (see `TestStaleDurationTimerCannotKillASuccessor`). `Writer.WritePacket` also independently checks `elapsed >= maxDurationSeconds` on every packet it's asked to write (`LimitReasonDurationReached`), so an actively-receiving capture stops just as promptly on the packet path without waiting for the timer. - -### Terminal states and stopping reasons - -Every capture that reaches a terminal state reports `status` (`completed` or `failed`) and `stoppingReason` via `GET /captures/{id}/status` and the `:stop` response: - -| `stoppingReason` | Meaning | `status` | -|---|---|---| -| `user_requested` | An explicit `POST /captures/{id}/stop` (or one with an empty/omitted `reason`) ended the capture. | `completed` | -| `max_duration_reached` | The `maxDurationSeconds` timer, or the writer's own per-packet duration check, fired. | `completed` | -| `max_size_reached` | `bytesWritten >= maxSizeBytes` was reached; the packet that crossed the limit is included in the file. | `completed` | -| `disk_full` | The PCAPNG writer's flush hit `syscall.ENOSPC`, discovered at `Close` (the common case) or occasionally at `WritePacket`. | `failed` | -| `error` | A non-ENOSPC I/O failure mid-capture (kernel-side read error, socket closed, etc.). | `failed` | - -`completed` vs. `failed` is decided solely by whether `Writer.Close()` (or the packet-read loop) returned a non-nil error — not by which condition triggered the stop — so a duration- or size-triggered stop that also hits a disk-full flush at `Close` is still reported `failed` / `disk_full`, overriding the reason that started the stop. In every case `Close` runs, and its result is folded into `status`/`stoppingReason`, before the terminal state is published — so any observer that sees a non-`running` status is guaranteed a fully flushed, closed file: `completed` means the file is complete and valid up to the interrupted limit; `failed` / `disk_full` means the file is valid up to whatever was durably flushed before the disk filled, which is not necessarily every packet the capture logically accepted. - -## Security Considerations (Phase 2 Design) - -1. **mTLS-only communication**: All endpoints require mTLS. The sidecar validates the client certificate against the cluster CA. No bearer tokens or API keys are used. Only authenticated clients (the API server, the operator) can reach the sidecar's control endpoints. Serving certificates, keys, and client CA bundles reload on each new TLS handshake after Kubernetes updates the mounted Secret. Each handshake pins one projected Secret generation; invalid or unreadable replacements fail closed and recover after valid material returns. Every certificate in the CA bundle must parse successfully. Session tickets are disabled so resumed sessions cannot bypass current client CA validation; established connections remain open. - -2. **File capability isolation**: `CAP_NET_RAW` is granted to the sidecar's binary only, via file capabilities. The game container retains no elevated privileges. This is a structural boundary, not a runtime check. - -3. **No privilege escalation in the game container**: The game container's `securityContext` is left unchanged. It cannot escape to gain raw-packet access or any other elevated privileges from the sidecar's presence. - -4. **Minimal file access**: The sidecar writes only to `/tmp/captures` and reads only `/etc/tls` for certificates. No other container mounts the capture volume; the captured files are inaccessible within the pod except via the sidecar's own HTTP endpoint. - -5. **Disk full handling**: The sidecar detects `ENOSPC` during a PCAPNG flush and stops gracefully, marking the capture `failed` with reason `disk_full` and keeping the partial file downloadable (see "Edge Cases" above). The emptyDir's `sizeLimit` enforces a hard disk bound; the sidecar respects it. - -6. **No unbounded resource consumption**: Duration and size limits prevent captures from running forever or consuming unlimited disk. The sidecar's own implementation must use bounded buffers (the AF_PACKET MMap'd buffer is sized by the kernel and the configuration, not unlimited). - -7. **Sensitive data in captures**: Captured packets may contain player IP addresses, network timing, game commands, and in-band credentials (session tokens, server passwords). Access control (mTLS + RBAC at the API tier) and time-limited retention (the operator's TTL reconciliation) are the primary mitigations, not redaction or sanitization. - -## Implemented since Phase 2 Foundational (F-190) - -Both items previously listed here as "planned" are implemented; kept as a section (rather than deleted) so a reader following an older link still lands somewhere useful. - -### TTL-based Expiry - -`NetworkCaptureReconciler` (`operator/internal/controller/networkcapture_controller.go`) reconciles the full Pending → Running → Completed/Failed → Expired lifecycle, including retention: `expireCapture` deletes the sidecar's backing file (best-effort) and the CR once `spec.ttlSecondsAfterFinished` elapses after completion. The API tier still validates and clamps TTL at CRD creation time, as before. - -### Dashboard UI - -`web/src/components/CaptureWidget.tsx` (a GameServer's Capture tab) and `web/src/routes/tabs/settings/NetworkCapture.tsx` (cluster-wide settings) implement starting, stopping, browsing, downloading, and deleting network captures. - -### Testing & Coverage (Phase 2 Foundational, COMPLETE) - -### Coverage Gate - -- **Threshold**: 70% (from `.testcoverage.yml`). -- **Measured against**: package-level aggregate (not per-file). -- **What's covered**: AF_PACKET socket lifecycle, BPF filter compilation, PCAPNG writing with limit enforcement, mTLS validation, HTTP handler routing and response shapes, edge cases (disk full, concurrent captures, invalid filters). -- **Uncovered**: main() process wiring, signal handling, graceful shutdown (not unit-testable in isolation). - -### Test Commands (Phase 2) - -Run via the workspace root Makefile or isolated: - -```sh -make test-go # Runs all Go tests, including capture-sidecar -cd capture-sidecar && go test ./... # Isolated run -``` - -### Key Test Cases (Phase 2) - -- **AF_PACKET**: socket setup, filter application, packet reception, MMap'd buffer semantics. -- **Filter Compilation**: valid filter acceptance, invalid filter rejection with syntax error. An empty filter is rejected with HTTP 400 (`filter is required: the control plane must supply the default port filter`) — the sidecar has no empty-filter fallback and never defaults to "no filter"; only the API tier materializes the default port-based filter before calling here (see "Packet Processing" note under Startup Flow and FR-003). -- **PCAPNG Writer**: valid file creation and closure, size-limit auto-stop with clean finalization, duration-limit auto-stop, max-size enforcement (final file <= limit + one packet). -- **mTLS**: valid certificate acceptance, invalid/expired certificate rejection, CA validation. -- **HTTP Handlers**: start/stop/status/file happy paths, 400 on invalid filter, 409 on concurrent capture with same ID, 404 on nonexistent capture, file download with correct headers. -- **Disk Full**: `ENOSPC` detection on the PCAPNG flush, capture marked `failed` with reason `disk_full`, partial file kept downloadable (see "Edge Cases"). -- **Concurrent Captures**: second start request on a running capture is rejected 409; only one running capture per sidecar at a time. - -## References - -- **`contracts/capture-sidecar.md`** — HTTP endpoint contracts (request/response shapes, status codes, error messages). -- **`specs/done_003-network-capture-sidecar/spec.md`** — Feature specification (User Stories US1–US5, Functional Requirements FR-001–FR-012, Success Criteria SC-001–SC-008). -- **`specs/done_003-network-capture-sidecar/data-model.md`** — NetworkCapture CRD design, status shape, lifecycle phases. -- **`operator/internal/controller/gameserver_controller.go`** — pod template injection and ephemeral-container mechanics. -- **`api/internal/handlers/capture.go`** — API-tier start/stop/download/enable/disable handlers that call the sidecar. -- **`gopacket` documentation** — AF_PACKET and PCAPNG format specs. -- **BPF filter syntax** — `man 7 pcap-filter` for the filter expression grammar. -- **PCAPNG format spec** — RFC 7468 (note: PCAPNG is not an RFC; the canonical spec is in the libpcap/tcpdump source). diff --git a/capture-sidecar/system-deps.toml b/capture-sidecar/system-deps.toml deleted file mode 100644 index 6399a6aab..000000000 --- a/capture-sidecar/system-deps.toml +++ /dev/null @@ -1,15 +0,0 @@ -# System dependencies for capture-sidecar (spec 026). Language libraries stay in go.mod/package.json. - -component = "capture-sidecar" - -[[dep]] -name = "go" -kind = "toolchain" -version = "go" -reason = "Compiles and tests the capture-sidecar module (go.work:3-21; inventory 2.1)." - -[[dep]] -name = "golangci-lint" -kind = "cli" -version = "golangci_lint" -reason = "make lint-go runs golangci-lint in this module (Makefile:302-305; GO_MODULES at Makefile:43)." diff --git a/deploy/kind/e2e.sh b/deploy/kind/e2e.sh index 8316ca70f..0cc72d89c 100755 --- a/deploy/kind/e2e.sh +++ b/deploy/kind/e2e.sh @@ -238,16 +238,8 @@ EOF if [ "${img}" = tunnel-frp ]; then dockerfile="${REPO}/tunnel/Dockerfile.frp" fi - if [ "${img}" = mcp-server ] && [ ! -f "${dockerfile}" ]; then - echo " mcp-server submodule not initialised — running git submodule update --init mcp-server" - git -C "${REPO}" submodule update --init mcp-server - elif [ "${img}" = mcp-server ]; then - expected=$(git -C "${REPO}" rev-parse "HEAD:mcp-server") - actual=$(git -C "${REPO}/mcp-server" rev-parse HEAD) - if [ "${expected}" != "${actual}" ]; then - echo " warning: mcp-server checkout ${actual} differs from the recorded gitlink ${expected}; run git submodule update mcp-server" >&2 - fi - fi + # Component images build from a submodule (hack/submodules.sh). + "${REPO}/hack/submodules.sh" ensure "$(basename "$(dirname "${dockerfile}")")" docker build -t "gameplane-test/${img}:${TAG}" -f "${dockerfile}" "${REPO}" fi kind load docker-image "gameplane-test/${img}:${TAG}" --name "${CLUSTER}" diff --git a/go.work b/go.work index 20f469025..51fda1fe2 100644 --- a/go.work +++ b/go.work @@ -3,8 +3,6 @@ go 1.27.3 use ( ./agent ./api - ./audit-syslog-bridge - ./capture-sidecar ./gameaction ./gameproto ./gp-module @@ -12,9 +10,7 @@ use ( ./netguard ./operator ./sentinel - ./svcutil ./telemetryschema ./telemetry-receiver ./test/e2e - ./tunnel ) diff --git a/go.work.sum b/go.work.sum index 4261cef8c..cd7b0069b 100644 --- a/go.work.sum +++ b/go.work.sum @@ -1010,6 +1010,7 @@ golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGb golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio= golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk= golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis= +golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20230515195305-f3d0a9c9a5cc/go.mod h1:V1LtkGg67GoY2N1AnLN78QLrzxkLyJw7RJb1gzOOz9w= golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842/go.mod h1:XtvwrStGgqGPLc4cjQfWqZHG1YFdYs6swckp8vpsjnc= diff --git a/hack/check-doc-versions.sh b/hack/check-doc-versions.sh index 0989fe6f1..5fa3a9176 100755 --- a/hack/check-doc-versions.sh +++ b/hack/check-doc-versions.sh @@ -7,12 +7,11 @@ # Gameplane version matches the current appVersion from charts/gameplane/Chart.yaml, # or is explicitly marked as an example version or historical reference. # -# Audited Files (18): +# Audited Files (17): # README.md, docs/architecture.md, docs/contributing.md, docs/dependencies.md, # docs/game-coverage.md, docs/install.md, docs/key-rotation.md, # docs/module-authoring.md, docs/networking.md, docs/notifications.md, # docs/oidc.md, docs/roadmap.md, docs/security.md, docs/tunnels.md, -# audit-syslog-bridge/README.md, # telemetry-receiver/README.md, docs/comparison-sources.md, # FEATURES.md # @@ -30,7 +29,7 @@ # # Test overrides: # DOC_VERSIONS_CHART: path to test Chart.yaml (default: charts/gameplane/Chart.yaml) -# DOC_VERSIONS_FILES: space-separated list of files to audit (default: 18 files below) +# DOC_VERSIONS_FILES: space-separated list of files to audit (default: 17 files below) # # Exit codes: # 0 = all version strings match current appVersion or are allowlisted @@ -65,7 +64,7 @@ fi # We'll accept matches with or without leading 'v' current_version_pattern="(v)?${current_version//./\\.}" -# List of 18 audited files +# List of 17 audited files if [[ -n "${DOC_VERSIONS_FILES:-}" ]]; then read -r -a audited_files <<< "$DOC_VERSIONS_FILES" else @@ -84,7 +83,6 @@ else "docs/roadmap.md" "docs/security.md" "docs/tunnels.md" - "audit-syslog-bridge/README.md" "telemetry-receiver/README.md" "docs/comparison-sources.md" "FEATURES.md" diff --git a/hack/check-links.sh b/hack/check-links.sh index 0f5b55363..2928dcf6c 100755 --- a/hack/check-links.sh +++ b/hack/check-links.sh @@ -1,21 +1,20 @@ #!/usr/bin/env bash # check-links.sh: Validate internal markdown links and anchors across the -# documentation audit's 18 files. +# documentation audit's 17 files. # # Purpose: # Ensures compliance with SC-006 (Internal Link Audit Standard) from feature 012 # (docs-refresh-and-outreach), contracts/docs-audit.md "Standard FR-010: Internal # Links" and "Link Checking (OD-2)". Validates that every markdown link and image -# target `[text](target)` / `![alt](target)` in the 18 audited files resolves to +# target `[text](target)` / `![alt](target)` in the 17 audited files resolves to # an existing file, and that any `#anchor` fragment resolves to an existing # heading slug or explicit HTML anchor in the target file. # -# Audited Files (18) — same fixed list as hack/check-doc-versions.sh: +# Audited Files (17) — same fixed list as hack/check-doc-versions.sh: # README.md, docs/architecture.md, docs/contributing.md, docs/dependencies.md, # docs/game-coverage.md, docs/install.md, docs/key-rotation.md, # docs/module-authoring.md, docs/networking.md, docs/notifications.md, # docs/oidc.md, docs/roadmap.md, docs/security.md, docs/tunnels.md, -# audit-syslog-bridge/README.md, # telemetry-receiver/README.md, docs/comparison-sources.md, # FEATURES.md # @@ -74,7 +73,7 @@ # section 9) uses explicit `` anchors instead. # # Exit codes: -# 0 = all 18 audited files exist and every internal link/anchor resolves +# 0 = all 17 audited files exist and every internal link/anchor resolves # 1 = an audited file is missing, or one or more links/anchors are broken # # No network access. Pure bash + grep/sed/tr, plus perl (present on Ubuntu @@ -88,7 +87,7 @@ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" REPO_ROOT="$(dirname "$SCRIPT_DIR")" cd "$REPO_ROOT" -# Same fixed list of 18 audited files as hack/check-doc-versions.sh. +# Same fixed list of 17 audited files as hack/check-doc-versions.sh. audited_files=( "README.md" "docs/architecture.md" @@ -104,7 +103,6 @@ audited_files=( "docs/roadmap.md" "docs/security.md" "docs/tunnels.md" - "audit-syslog-bridge/README.md" "telemetry-receiver/README.md" "docs/comparison-sources.md" "FEATURES.md" @@ -399,7 +397,7 @@ if [[ "${1:-}" == "--self-test" ]]; then fi # --------------------------------------------------------------------------- -# Main: verify all 18 audited files exist, then link-check every one that +# Main: verify all 17 audited files exist, then link-check every one that # does (a missing file is itself a failure, but does not stop the rest of # the audit from running). # --------------------------------------------------------------------------- diff --git a/hack/check-submodule-freshness.sh b/hack/check-submodule-freshness.sh index 443e1b2ef..0366c96d1 100755 --- a/hack/check-submodule-freshness.sh +++ b/hack/check-submodule-freshness.sh @@ -7,14 +7,13 @@ # Such a pointer references a commit that exists only on a feature branch, # so a fresh clone of the superproject cannot fetch it. Spec 013 G6 / OD-1. # -# Checked submodules (path -> upstream URL, overridable through env): -# modules -> ${SUBMODULE_URL_MODULES:-https://github.com/GameplanePanel/module} -# website -> ${SUBMODULE_URL_WEBSITE:-https://github.com/GameplanePanel/website} -# mcp-server -> ${SUBMODULE_URL_MCP:-https://github.com/GameplanePanel/mcp} -# (checked only when .gitmodules declares it, so the fixture -# superproject in check-submodule-freshness_test.sh, which has -# no .gitmodules, still checks just modules and website) -# Upstream branch: ${SUBMODULE_BRANCH:-main} +# Checked submodules: every gitlink at HEAD plus every path .gitmodules declares +# (a declared path with no gitlink fails). For each one: +# upstream URL: ${SUBMODULE_URL_} (path upper-cased, '-' -> '_', e.g. +# SUBMODULE_URL_MCP_SERVER), else its .gitmodules url +# branch: ${SUBMODULE_BRANCH}, else its .gitmodules branch, else main +# The fixture superproject in check-submodule-freshness_test.sh has no +# .gitmodules, so it relies on the gitlinks and the URL overrides. # # Environment: # SUBMODULE_FRESHNESS_REPO superproject to check (default: this repo root). @@ -31,19 +30,26 @@ else cd "${SCRIPT_DIR}/.." fi -BRANCH="${SUBMODULE_BRANCH:-main}" -URL_MODULES="${SUBMODULE_URL_MODULES:-https://github.com/GameplanePanel/module}" -URL_WEBSITE="${SUBMODULE_URL_WEBSITE:-https://github.com/GameplanePanel/website}" -URL_MCP="${SUBMODULE_URL_MCP:-https://github.com/GameplanePanel/mcp}" - -PAIRS=( - "modules ${URL_MODULES}" - "website ${URL_WEBSITE}" +# Union of HEAD gitlinks and .gitmodules paths, in a stable order. +mapfile -t PATHS < <( + { + git ls-tree -r HEAD | awk '$2=="commit"{print $4}' + if [[ -f .gitmodules ]]; then + git config -f .gitmodules --get-regexp '^submodule\..*\.path$' | awk '{print $2}' + fi + } | sort -u ) -# Declared in .gitmodules means required: a missing gitlink then fails below. -if git config -f .gitmodules --get submodule.mcp-server.path >/dev/null 2>&1; then - PAIRS+=("mcp-server ${URL_MCP}") -fi + +# gitmodules_value : the .gitmodules value for the entry at . +gitmodules_value() { + [[ -f .gitmodules ]] || return 0 + local key name + key="$(git config -f .gitmodules --get-regexp '^submodule\..*\.path$' | + awk -v p="$1" '$2==p{print $1; exit}')" + [[ -n "${key}" ]] || return 0 + name="${key%.path}" + git config -f .gitmodules --get "${name}.$2" || true +} TMP="$(mktemp -d)" cleanup() { @@ -53,9 +59,16 @@ trap cleanup EXIT failures=0 -for pair in "${PAIRS[@]}"; do - path="${pair%% *}" - url="${pair#* }" +for path in "${PATHS[@]}"; do + override="SUBMODULE_URL_$(tr '[:lower:]-' '[:upper:]_' <<<"${path}")" + url="${!override:-$(gitmodules_value "${path}" url)}" + branch="${SUBMODULE_BRANCH:-$(gitmodules_value "${path}" branch)}" + BRANCH="${branch:-main}" + if [[ -z "${url}" ]]; then + echo "✗ ${path}: no upstream URL (.gitmodules url or ${override})" + failures=$((failures + 1)) + continue + fi sha="$(git ls-tree HEAD "${path}" | awk '$2=="commit"{print $3}')" if [[ -z "${sha}" ]]; then diff --git a/hack/ci_scope.py b/hack/ci_scope.py index 71918842b..ffabe4ed4 100644 --- a/hack/ci_scope.py +++ b/hack/ci_scope.py @@ -44,10 +44,29 @@ ".githooks", ".jules", ".specify", "deploy/standalone", "test/e2e/testdata") # The dashboard live run drives these components through a real cluster. WEB_LIVE_COMPONENTS = {"web", "api", "operator", "agent"} + + +def component_submodules(root): + """Return the paths of .gitmodules entries marked `component = true` (hack/submodules.sh).""" + try: + text = (root / ".gitmodules").read_text(encoding="utf-8") + except FileNotFoundError: + return () + paths = [] + for section in re.split(r"^\[submodule ", text, flags=re.MULTILINE)[1:]: + values = dict(re.findall(r"^\s*(\w+)\s*=\s*(\S+)\s*$", section, re.MULTILINE)) + if values.get("component") == "true" and values.get("path"): + paths.append(values["path"]) + return tuple(paths) + + +# Split Go services checked out as submodules at their old paths; each is its own component. +SUBMODULE_COMPONENTS = component_submodules(ROOT) # Component ids beside the go.work modules (data-model.md Component). -EXTRA_COMPONENTS = ("web", "charts", "deploy-kind", "modules", "mcp-server", "e2e-harness") +EXTRA_COMPONENTS = ("web", "charts", "deploy-kind", "modules", "e2e-harness") + SUBMODULE_COMPONENTS # Top-level areas a selection rule knows; any other path is unmapped and forces full scope. -KNOWN_DIRS = ("charts", "containers", "deploy/kind", "signing", "test/e2e", "web", "modules", "mcp-server") +KNOWN_DIRS = ("charts", "containers", "deploy/kind", "signing", "test/e2e", "web", + "modules") + SUBMODULE_COMPONENTS # A change to one of these files in a module root reruns that whole module (research R4). GO_MODULE_WIDE = {"go.mod", "go.sum", ".testcoverage.yml"} # Tests that read files outside their package directory. A changed path under a key also @@ -471,8 +490,8 @@ def pick(names, path): components.setdefault("web", []).append(path) elif under(path, "modules"): components.setdefault("modules", []).append(path) - elif under(path, "mcp-server"): - components.setdefault("mcp-server", []).append(path) + elif submodule := next((sub for sub in SUBMODULE_COMPONENTS if under(path, sub)), None): + components.setdefault(submodule, []).append(path) else: unmapped.append(path) if unmapped: diff --git a/hack/submodules.sh b/hack/submodules.sh new file mode 100755 index 000000000..6a31d741c --- /dev/null +++ b/hack/submodules.sh @@ -0,0 +1,106 @@ +#!/usr/bin/env bash +# submodules.sh: the one reader of .gitmodules for the split Gameplane components. +# +# A component is a Go service that lives in its own GameplanePanel repository +# and is checked out here as a submodule at its old path, so the Dockerfiles, +# bake file and chart keep their paths. It is a .gitmodules entry with +# `component = true` (modules/ and website/ are submodules but not components). +# Adding a split is one .gitmodules entry; every consumer below reads it: +# CI init steps, Makefile image rules, deploy/kind/e2e.sh, hack/ci_scope.py +# and hack/check-submodule-freshness.sh (which checks every gitlink). +# +# Usage: +# hack/submodules.sh components print each component path, one per line +# hack/submodules.sh init check out every component submodule +# hack/submodules.sh ensure check out if it is a component that +# is not checked out yet; warn when the +# checkout differs from the recorded gitlink +# hack/submodules.sh check fail when a component is missing from the +# static workflow path filters that must +# name it (GitHub cannot read .gitmodules) +set -euo pipefail + +cd "$(dirname "${BASH_SOURCE[0]}")/.." + +components() { + [[ -f .gitmodules ]] || return 0 + local key value name + while read -r key value; do + [[ "${value}" == true ]] || continue + name="${key#submodule.}" + name="${name%.component}" + git config -f .gitmodules --get "submodule.${name}.path" + done < <(git config -f .gitmodules --get-regexp '^submodule\..*\.component$' || true) +} + +is_component() { + local path + while read -r path; do + [[ "${path}" == "$1" ]] && return 0 + done < <(components) + return 1 +} + +ensure() { + local path="$1" expected actual + is_component "${path}" || return 0 + if [[ ! -e "${path}/.git" ]]; then + echo "${path} submodule not checked out; running git submodule update --init ${path}" >&2 + git submodule update --init -- "${path}" + return 0 + fi + expected="$(git rev-parse "HEAD:${path}")" + actual="$(git -C "${path}" rev-parse HEAD)" + if [[ "${expected}" != "${actual}" ]]; then + echo "warning: ${path} checkout ${actual} differs from the recorded gitlink ${expected}; run git submodule update ${path}" >&2 + fi +} + +# Each component path must appear as a bare list item (the gitlink itself, so a +# pointer bump matches) in these filters. ci.yaml: e2etree (images the e2e loads), +# submodules (freshness gate) and github (workflow-lint reads the Dockerfiles). +check() { + local failures=0 path filter + local ci=.github/workflows/ci.yaml + while read -r path; do + for filter in e2etree submodules github; do + if ! awk -v f="${filter}" -v p="${path}" ' + /^ [a-z0-9_]+:[[:space:]]*$/ { cur = $1; sub(/:$/, "", cur); next } + cur == f && $0 ~ "^ - .?" p ".?[[:space:]]*$" { found = 1 } + END { exit found ? 0 : 1 }' "${ci}"; then + echo "✗ ${path}: missing from the '${filter}' path filter in ${ci}" + failures=$((failures + 1)) + fi + done + for wf in .github/workflows/publish-edge.yaml .github/workflows/devcontainers.yaml; do + if ! grep -Eq "^[[:space:]]+- [\"']?${path}[\"']?[[:space:]]*$" "${wf}"; then + echo "✗ ${path}: missing from the path filters in ${wf}" + failures=$((failures + 1)) + fi + done + done < <(components) + if ((failures > 0)); then + echo "add each component submodule path to the filters above (see hack/submodules.sh)" >&2 + return 1 + fi + echo "✓ every component submodule is in the workflow path filters" +} + +case "${1:-}" in +components) components ;; +init) + mapfile -t paths < <(components) + if ((${#paths[@]} > 0)); then + git submodule update --init -- "${paths[@]}" + fi + ;; +ensure) + [[ $# -eq 2 ]] || { echo "usage: $0 ensure " >&2; exit 2; } + ensure "$2" + ;; +check) check ;; +*) + echo "usage: $0 components|init|ensure |check" >&2 + exit 2 + ;; +esac diff --git a/svcutil/.testcoverage.yml b/svcutil/.testcoverage.yml deleted file mode 100644 index 982ff2458..000000000 --- a/svcutil/.testcoverage.yml +++ /dev/null @@ -1,14 +0,0 @@ -# Coverage threshold gate for the shared svcutil module. -# Enforced by `make cover-go-check` via go-test-coverage/v2. -# -# svcutil holds shared env and graceful-shutdown helpers used across multiple -# binaries. It is pure stdlib with thorough table tests for env parsing and -# server lifecycle; gate at 90%. The small gap is in edge cases of the shutdown -# path (context timeout races that are difficult to trigger reliably in tests). -profile: coverage/unit.out -github-action-output: false - -threshold: - file: 0 - package: 0 - total: 90 diff --git a/svcutil/env.go b/svcutil/env.go deleted file mode 100644 index ad6f97c17..000000000 --- a/svcutil/env.go +++ /dev/null @@ -1,52 +0,0 @@ -// Package svcutil provides shared stdlib-only service helpers for environment -// parsing (Or, OrInt, ParseLogLevel) and graceful HTTP server shutdown (RunHTTP), -// intended to reduce code duplication and enforce consistent startup and -// shutdown behavior across the Go binaries in this repo. It has no active -// consumers yet; see svcutil/specs.md for adoption status. -package svcutil - -import ( - "log/slog" - "os" - "strconv" - "strings" -) - -// Or returns the value of the environment variable key if it is set (even to -// an empty string), otherwise returns the fallback. This matches the semantics -// of os.LookupEnv: an empty-but-set var is distinguishable from an unset one. -func Or(key, fallback string) string { - if v, ok := os.LookupEnv(key); ok { - return v - } - return fallback -} - -// OrInt returns the value of the environment variable key parsed as an integer, -// or the default value def if the key is unset or the value is not a valid -// integer. Unparseable values degrade to the safe default rather than crashing -// startup — a typo in a manifest shouldn't take the service down. -func OrInt(key string, def int) int { - if v, ok := os.LookupEnv(key); ok { - if n, err := strconv.Atoi(v); err == nil { - return n - } - } - return def -} - -// ParseLogLevel maps a log level string to a slog.Level. The following values -// are recognized (case-insensitive): debug, warn, error. Unknown values -// degrade to info — a typo in a manifest shouldn't crash the service. -func ParseLogLevel(s string) slog.Level { - switch strings.ToLower(s) { - case "debug": - return slog.LevelDebug - case "warn": - return slog.LevelWarn - case "error": - return slog.LevelError - default: - return slog.LevelInfo - } -} diff --git a/svcutil/env_test.go b/svcutil/env_test.go deleted file mode 100644 index 152f1ddfa..000000000 --- a/svcutil/env_test.go +++ /dev/null @@ -1,208 +0,0 @@ -package svcutil - -import ( - "log/slog" - "os" - "testing" -) - -func TestOr(t *testing.T) { - tests := []struct { - name string - key string - fallback string - setup func() - want string - }{ - { - name: "unset key returns fallback", - key: "TEST_OR_UNSET", - fallback: "default_value", - setup: func() { os.Unsetenv("TEST_OR_UNSET") }, - want: "default_value", - }, - { - name: "set key returns value", - key: "TEST_OR_SET", - fallback: "default_value", - setup: func() { - os.Setenv("TEST_OR_SET", "actual_value") - }, - want: "actual_value", - }, - { - name: "empty but set key returns empty string", - key: "TEST_OR_EMPTY", - fallback: "default_value", - setup: func() { - os.Setenv("TEST_OR_EMPTY", "") - }, - want: "", - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - tt.setup() - defer os.Unsetenv(tt.key) - - got := Or(tt.key, tt.fallback) - if got != tt.want { - t.Errorf("Or(%q, %q) = %q; want %q", tt.key, tt.fallback, got, tt.want) - } - }) - } -} - -func TestOrInt(t *testing.T) { - tests := []struct { - name string - key string - def int - setup func() - want int - }{ - { - name: "unset key returns default", - key: "TEST_OR_INT_UNSET", - def: 42, - setup: func() { os.Unsetenv("TEST_OR_INT_UNSET") }, - want: 42, - }, - { - name: "valid integer returns parsed value", - key: "TEST_OR_INT_VALID", - def: 42, - setup: func() { - os.Setenv("TEST_OR_INT_VALID", "123") - }, - want: 123, - }, - { - name: "negative integer returns parsed value", - key: "TEST_OR_INT_NEGATIVE", - def: 42, - setup: func() { - os.Setenv("TEST_OR_INT_NEGATIVE", "-999") - }, - want: -999, - }, - { - name: "zero returns parsed value", - key: "TEST_OR_INT_ZERO", - def: 42, - setup: func() { - os.Setenv("TEST_OR_INT_ZERO", "0") - }, - want: 0, - }, - { - name: "invalid integer returns default", - key: "TEST_OR_INT_INVALID", - def: 42, - setup: func() { - os.Setenv("TEST_OR_INT_INVALID", "not_a_number") - }, - want: 42, - }, - { - name: "empty string returns default", - key: "TEST_OR_INT_EMPTY", - def: 42, - setup: func() { - os.Setenv("TEST_OR_INT_EMPTY", "") - }, - want: 42, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - tt.setup() - defer os.Unsetenv(tt.key) - - got := OrInt(tt.key, tt.def) - if got != tt.want { - t.Errorf("OrInt(%q, %d) = %d; want %d", tt.key, tt.def, got, tt.want) - } - }) - } -} - -func TestParseLogLevel(t *testing.T) { - tests := []struct { - name string - s string - want slog.Level - }{ - { - name: "debug returns LevelDebug", - s: "debug", - want: slog.LevelDebug, - }, - { - name: "DEBUG (uppercase) returns LevelDebug", - s: "DEBUG", - want: slog.LevelDebug, - }, - { - name: "Debug (mixed case) returns LevelDebug", - s: "Debug", - want: slog.LevelDebug, - }, - { - name: "warn returns LevelWarn", - s: "warn", - want: slog.LevelWarn, - }, - { - name: "WARN (uppercase) returns LevelWarn", - s: "WARN", - want: slog.LevelWarn, - }, - { - name: "error returns LevelError", - s: "error", - want: slog.LevelError, - }, - { - name: "ERROR (uppercase) returns LevelError", - s: "ERROR", - want: slog.LevelError, - }, - { - name: "info returns LevelInfo", - s: "info", - want: slog.LevelInfo, - }, - { - name: "INFO (uppercase) returns LevelInfo", - s: "INFO", - want: slog.LevelInfo, - }, - { - name: "empty string returns LevelInfo (default)", - s: "", - want: slog.LevelInfo, - }, - { - name: "unknown value returns LevelInfo (default)", - s: "unknown", - want: slog.LevelInfo, - }, - { - name: "typo value returns LevelInfo (default)", - s: "debugg", - want: slog.LevelInfo, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got := ParseLogLevel(tt.s) - if got != tt.want { - t.Errorf("ParseLogLevel(%q) = %v; want %v", tt.s, got, tt.want) - } - }) - } -} diff --git a/svcutil/go.mod b/svcutil/go.mod deleted file mode 100644 index 9f3c5cd5c..000000000 --- a/svcutil/go.mod +++ /dev/null @@ -1,3 +0,0 @@ -module github.com/GameplanePanel/gameplane/svcutil - -go 1.27.0 diff --git a/svcutil/server.go b/svcutil/server.go deleted file mode 100644 index 1b79cecbf..000000000 --- a/svcutil/server.go +++ /dev/null @@ -1,37 +0,0 @@ -package svcutil - -import ( - "context" - "errors" - "net/http" - "time" -) - -// RunHTTP runs an HTTP server until the context is cancelled, then performs a -// graceful shutdown. It returns nil on clean shutdown and the listen error -// otherwise. -// -// The function starts the server's ListenAndServe in a goroutine and selects -// on either a listen error (returned immediately) or context cancellation. -// On context cancellation, it calls srv.Shutdown with a deadline-bounded -// context derived from the provided shutdownTimeout. The http.ErrServerClosed -// error (which occurs after successful shutdown) is mapped to nil. -func RunHTTP(ctx context.Context, srv *http.Server, shutdownTimeout time.Duration) error { - errCh := make(chan error, 1) - go func() { - err := srv.ListenAndServe() - if err != nil && !errors.Is(err, http.ErrServerClosed) { - errCh <- err - } - close(errCh) - }() - - select { - case err := <-errCh: - return err - case <-ctx.Done(): - shutCtx, shutCancel := context.WithTimeout(context.WithoutCancel(ctx), shutdownTimeout) - defer shutCancel() - return srv.Shutdown(shutCtx) - } -} diff --git a/svcutil/server_test.go b/svcutil/server_test.go deleted file mode 100644 index 3e61a7010..000000000 --- a/svcutil/server_test.go +++ /dev/null @@ -1,193 +0,0 @@ -package svcutil - -import ( - "context" - "errors" - "net" - "net/http" - "testing" - "time" -) - -func TestRunHTTPCleanShutdown(t *testing.T) { - // Create a test listener on localhost with port 0 (OS picks an available port). - var lc net.ListenConfig - listener, err := lc.Listen(context.Background(), "tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("failed to listen: %v", err) - } - addr := listener.Addr().String() - listener.Close() - - srv := &http.Server{ - Addr: addr, - Handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(http.StatusOK) - }), - ReadHeaderTimeout: 10 * time.Second, - } - - ctx, cancel := context.WithCancel(context.Background()) - - // Run the server in a goroutine. - done := make(chan error) - go func() { - done <- RunHTTP(ctx, srv, 5*time.Second) - }() - - // Give the server time to start. - time.Sleep(100 * time.Millisecond) - - // Cancel the context to trigger graceful shutdown. - cancel() - - // Wait for RunHTTP to return. - err = <-done - if err != nil { - t.Errorf("RunHTTP returned error on clean shutdown: %v", err) - } -} - -func TestRunHTTPListenError(t *testing.T) { - // Create a server bound to an invalid address to trigger a listen error. - srv := &http.Server{ - Addr: "invalid-address-that-cannot-be-used:99999", - Handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(http.StatusOK) - }), - ReadHeaderTimeout: 10 * time.Second, - } - - ctx := context.Background() - - // RunHTTP should return the listen error. - err := RunHTTP(ctx, srv, 5*time.Second) - if err == nil { - t.Errorf("RunHTTP should return a listen error for an invalid address; got nil") - } - if errors.Is(err, http.ErrServerClosed) { - t.Errorf("RunHTTP should not return ErrServerClosed on listen error; got %v", err) - } -} - -func TestRunHTTPContextCancelledBeforeListen(t *testing.T) { - // Create a context that is already cancelled. - ctx, cancel := context.WithCancel(context.Background()) - cancel() - - var lc net.ListenConfig - listener, err := lc.Listen(context.Background(), "tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("failed to listen: %v", err) - } - addr := listener.Addr().String() - listener.Close() - - srv := &http.Server{ - Addr: addr, - Handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(http.StatusOK) - }), - ReadHeaderTimeout: 10 * time.Second, - } - - // RunHTTP should attempt shutdown and return nil or a shutdown result. - // Since the context is already cancelled, the select will immediately pick - // the context.Done() case. - err = RunHTTP(ctx, srv, 5*time.Second) - if err != nil && !errors.Is(err, context.Canceled) { - // It's acceptable to return context.Canceled during srv.Shutdown, or nil on success. - t.Logf("RunHTTP returned: %v (acceptable for pre-cancelled context)", err) - } -} - -func TestRunHTTPServerClosedError(t *testing.T) { - // This test verifies that http.ErrServerClosed is not returned. - // The server is started and then shut down via context cancellation. - // The select will pick the context done case and call srv.Shutdown, - // which should return nil (since it's a normal shutdown). - - var lc net.ListenConfig - listener, err := lc.Listen(context.Background(), "tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("failed to listen: %v", err) - } - addr := listener.Addr().String() - listener.Close() - - srv := &http.Server{ - Addr: addr, - Handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(http.StatusOK) - }), - ReadHeaderTimeout: 10 * time.Second, - } - - ctx, cancel := context.WithCancel(context.Background()) - - // Run the server. - done := make(chan error) - go func() { - done <- RunHTTP(ctx, srv, 5*time.Second) - }() - - // Give the server time to start. - time.Sleep(100 * time.Millisecond) - - // Cancel the context to trigger shutdown. - cancel() - - // Wait for RunHTTP to return. - err = <-done - if errors.Is(err, http.ErrServerClosed) { - t.Errorf("RunHTTP should not return ErrServerClosed on normal shutdown; got %v", err) - } - // Shutdown should return nil or possibly context.Canceled, but not ErrServerClosed. -} - -func TestRunHTTPShutdownTimeout(t *testing.T) { - // Create a server with a long-running handler. - var lc net.ListenConfig - listener, err := lc.Listen(context.Background(), "tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("failed to listen: %v", err) - } - addr := listener.Addr().String() - listener.Close() - - // Handler that takes a long time. - blockingHandler := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - time.Sleep(30 * time.Second) - w.WriteHeader(http.StatusOK) - }) - - srv := &http.Server{ - Addr: addr, - Handler: blockingHandler, - ReadHeaderTimeout: 10 * time.Second, - } - - ctx, cancel := context.WithCancel(context.Background()) - - // Run the server. - done := make(chan error) - go func() { - done <- RunHTTP(ctx, srv, 100*time.Millisecond) // Very short timeout - }() - - // Give the server time to start. - time.Sleep(100 * time.Millisecond) - - // Cancel the context. - cancel() - - // Wait for RunHTTP to return. With the short timeout, shutdown should - // return quickly (possibly with a context.Canceled error from the timeout). - select { - case err := <-done: - // This is expected. err might be nil, context.Canceled, or a shutdown error. - t.Logf("RunHTTP returned after timeout: %v", err) - case <-time.After(2 * time.Second): - t.Errorf("RunHTTP did not return within expected time; shutdown timeout may not be working") - } -} diff --git a/svcutil/specs.md b/svcutil/specs.md deleted file mode 100644 index 50b186cd6..000000000 --- a/svcutil/specs.md +++ /dev/null @@ -1,105 +0,0 @@ -# svcutil — Specification - -**Status:** Stable -**Module / command:** `github.com/GameplanePanel/gameplane/svcutil` -**Dependencies:** stdlib only (Go 1.27+) - -## Purpose - -Shared stdlib-only service helpers for environment parsing and graceful HTTP server shutdown, intended to reduce code duplication and enforce consistent startup and shutdown behavior across the Go binaries in this repo. All functions degrade gracefully on invalid inputs; no startup crashes from bad configuration. - -**Adoption status:** `svcutil` has no active consumers yet. No binary in the workspace currently imports it; `operator`, `api`, `agent`, `audit-syslog-bridge`, and `telemetry-receiver` each keep their own local `envOr`/`parseLogLevel`-style helpers. `capture-sidecar` does not import it either — `RunHTTP` only serves plain HTTP (`ListenAndServe`), while the sidecar's control server needs a TLS listener with client-certificate verification (see `capture-sidecar/cmd/main.go:80-86`). - -## Responsibilities - -- Parse environment variables with fallback semantics, distinguishing unset from empty-but-set. -- Parse log-level strings to `slog.Level` enums with case-insensitive recognition and graceful default on unknown values. -- Parse integer-valued environment variables with non-crashing fallback to defaults. -- Start HTTP servers and manage graceful shutdown on context cancellation with bounded timeout. -- Map shutdown success (`http.ErrServerClosed`) to nil so callers see clean completion. - -## Non-goals / boundaries - -- Does not provide configuration file parsing or command-line flag parsing; only environment-variable inputs. -- Does not enforce configuration schema or validation; callers own business-logic constraints. -- Does not handle signal forwarding; callers that need signal → context.Done bridging use `signal.NotifyContext`. -- Does not manage connection pooling or middleware; `RunHTTP` runs a stock `http.Server` as-is. - -## Directory & package layout - -``` -svcutil/ -├── env.go # Or, OrInt, ParseLogLevel environment helpers -├── env_test.go # Unit tests for environment parsing (21 subtests) -├── server.go # RunHTTP graceful shutdown helper -├── server_test.go # Unit tests for server lifecycle (5 functions) -├── go.mod # Module declaration (stdlib-only) -└── .testcoverage.yml # 90% coverage gate -``` - -Single package; no subdirectories or internal structure. - -## External interface / contracts - -### Exported Functions - -| Function | Signature | Behavior | -|---|---|---| -| **`Or`** | `Or(key, fallback string) string` | Returns environment variable `key` if set (via `os.LookupEnv`); otherwise returns `fallback`. Distinguishes unset from empty-but-set: empty string in env returns `""`, not `fallback`. | -| **`OrInt`** | `OrInt(key string, def int) int` | Parses environment variable `key` as int via `strconv.Atoi`; returns `def` if unset or unparseable. Non-crashing: invalid values degrade to default rather than panicking. | -| **`ParseLogLevel`** | `ParseLogLevel(s string) slog.Level` | Maps case-insensitive log-level string to `slog.Level`. Recognized case-insensitively: debug, warn, error; anything else (including "info" or empty) defaults to `slog.LevelInfo`. Non-crashing fallback semantics. | -| **`RunHTTP`** | `RunHTTP(ctx context.Context, srv *http.Server, shutdownTimeout time.Duration) error` | Starts HTTP server; on context cancellation, performs graceful shutdown with deadline bounded by `shutdownTimeout`. Maps `http.ErrServerClosed` to `nil`. Returns listen error immediately or shutdown result on cancellation. | - -## Key invariants - -1. **Graceful fallback.** `OrInt` and `ParseLogLevel` never panic on invalid input; they degrade to sensible defaults (`def` for OrInt, `slog.LevelInfo` for ParseLogLevel). This is a guarantee: invalid manifest values must not crash the service at startup. - -2. **Empty-string semantics.** `Or` distinguishes unset (`os.LookupEnv` returns `ok=false`) from empty-but-set (`os.LookupEnv` returns `v=""` with `ok=true`). Unset uses fallback; empty-but-set returns empty string (no fallback). This preserves user intent when an env var is intentionally cleared. - -3. **Bounded shutdown.** `RunHTTP` calls `srv.Shutdown` with a deadline-bounded context derived from `shutdownTimeout`. If the timeout expires before all connections close, `srv.Shutdown` returns with a deadline-exceeded error and `RunHTTP` exits promptly. However, in-flight handlers continue running until they naturally complete or the process exits; the timeout bounds only how long `RunHTTP` waits, not handler execution. This prevents indefinite hangs in `RunHTTP` itself while preserving handler cleanup. - -4. **Success mapping.** `RunHTTP` explicitly maps `http.ErrServerClosed` (the success path from `srv.Shutdown`) to `nil`, so callers see nil on clean shutdown and a non-nil error only on failure. - -5. **Context propagation.** `RunHTTP` selects on both listen errors (returned immediately) and context cancellation (triggers shutdown). If the context is pre-cancelled or becomes cancelled before the server listens, shutdown proceeds normally. - -## Dependencies - -**Internal:** None. -**External:** stdlib only (`context`, `errors`, `log/slog`, `net/http`, `os`, `strconv`, `strings`, `time`). No external modules in `go.mod`. - -## Security considerations - -- **No secrets in env vars.** This package reads environment variables for configuration only; credentials or sensitive values must be injected via files or mounts, not environment variables (which are visible in process listings and pod describe). -- **Graceful defaults prevent misconfiguration crashes.** Services that fail to start due to invalid log levels or port numbers in the environment are difficult to debug in containerized environments. Non-crashing fallbacks reduce incident severity (service starts, logs at info level, operator can adjust). -- **Bounded shutdown prevents hanging.** A service hung in shutdown — with `RunHTTP` waiting indefinitely for in-flight requests to close — can leave resources locked or cause deployment failures. `shutdownTimeout` bounds how long `RunHTTP` waits; Kubernetes `terminationGracePeriodSeconds` (usually 30 seconds) provides the outermost bound. Handlers themselves are not force-terminated by this timeout and may continue running after `RunHTTP` returns. - -## Testing & coverage - -**Test structure:** -- Unit tests in `env_test.go` cover `Or`, `OrInt`, `ParseLogLevel` with table-driven cases for set/unset/invalid/empty/default scenarios. -- Unit tests in `server_test.go` cover `RunHTTP` lifecycle: - - `TestRunHTTPCleanShutdown`: clean context cancellation and graceful shutdown. - - `TestRunHTTPListenError`: immediate return on listen errors. - - `TestRunHTTPContextCancelledBeforeListen`: pre-cancelled context triggers shutdown. - - `TestRunHTTPServerClosedError`: verification that `http.ErrServerClosed` is not returned to callers. - - `TestRunHTTPShutdownTimeout`: confirms `RunHTTP` returns promptly after context cancellation with a short `shutdownTimeout`; it does not hold a request open across shutdown, so it does not exercise the timeout actually cutting off a slow handler. - -**Coverage gate:** 90% (`.testcoverage.yml`, total threshold). - -**Uncovered paths:** The small 10% gap accounts for the following shutdown edge case: -- Shutdown returning context.DeadlineExceeded because a handler is still active past the deadline: no test currently holds a request open past the timeout to verify that `RunHTTP` returns the deadline error while the handler continues running. This path is difficult to test reliably without introducing flaky timing assumptions. - -These edge cases are acceptable because: -1. They occur only during service shutdown/restart, not during steady-state operation. -2. The outer Kubernetes `terminationGracePeriodSeconds` ensures eventual termination even if shutdown races occur. -3. Triggering them in a test would require flaky timing assumptions or mocking system calls. - -**Key test cases:** -- **Environment parsing:** Unset, set, empty, invalid values; fallback semantics; case-insensitivity. -- **Server lifecycle:** Clean shutdown, listen error, pre-cancelled context, shutdown timeout, ErrServerClosed mapping. - -## References - -- **Consumers:** None currently. `svcutil` is linked into the workspace (`go.work`) but no binary imports it yet; see "Adoption status" above. -- **Architecture:** `docs/architecture.md` does not currently describe `svcutil`; there is no dedicated section to cross-reference. -- **Go workspace:** `go.work` — svcutil is listed as a workspace module so it builds and vets alongside the other components, independent of whether anything imports it. diff --git a/svcutil/system-deps.toml b/svcutil/system-deps.toml deleted file mode 100644 index c2bdeba27..000000000 --- a/svcutil/system-deps.toml +++ /dev/null @@ -1,15 +0,0 @@ -# System dependencies for svcutil (spec 026). Language libraries stay in go.mod/package.json. - -component = "svcutil" - -[[dep]] -name = "go" -kind = "toolchain" -version = "go" -reason = "Compiles and tests the svcutil module (go.work:3-21; inventory 2.1)." - -[[dep]] -name = "golangci-lint" -kind = "cli" -version = "golangci_lint" -reason = "make lint-go runs golangci-lint in this module (Makefile:302-305; GO_MODULES at Makefile:43)." diff --git a/test/e2e/suite-components.json b/test/e2e/suite-components.json index ae35f835c..aeed0edc7 100644 --- a/test/e2e/suite-components.json +++ b/test/e2e/suite-components.json @@ -70,7 +70,6 @@ "paths": ["hack/ci_scope.py", ".github/workflows/ci.yaml", "test/e2e/buckets.sh", "test/e2e/suite-components.json"] } ], "unexercised": [ - { "component": "svcutil", "reason": "library only; the suites of every service that imports it run through the module closure" }, { "component": "test/e2e", "reason": "the e2e suite itself; a changed test file selects its own tests and the tests that use its helpers" }, { "component": "web", "reason": "dashboard; exercised by e2e web live (Playwright), not by a Go e2e test" } ] diff --git a/tunnel b/tunnel new file mode 160000 index 000000000..e8dcb5c45 --- /dev/null +++ b/tunnel @@ -0,0 +1 @@ +Subproject commit e8dcb5c45495ae948261d50db7cf0b5e82db93a6 diff --git a/tunnel/.gitignore b/tunnel/.gitignore deleted file mode 100644 index 8d34fd293..000000000 --- a/tunnel/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/tunnel diff --git a/tunnel/.testcoverage.yml b/tunnel/.testcoverage.yml deleted file mode 100644 index 591d11c29..000000000 --- a/tunnel/.testcoverage.yml +++ /dev/null @@ -1,15 +0,0 @@ -# Coverage threshold gate for the tunnel module. -# Enforced by `make cover-go-check` via go-test-coverage/v2. -# -# The tunnel supervisor configures and supervises a third-party relay process -# (frp, Tailscale, or playit). Tests cover env parsing, credential reading, -# config file rendering per provider, backoff behavior, and context shutdown. -# Child process spawning and relay operation are not unit-testable. Gate below -# measured; ratchet up as coverage grows. -profile: coverage/unit.out -github-action-output: false - -threshold: - file: 0 - package: 0 - total: 70 diff --git a/tunnel/Dockerfile.frp b/tunnel/Dockerfile.frp deleted file mode 100644 index 3b5ca2220..000000000 --- a/tunnel/Dockerfile.frp +++ /dev/null @@ -1,52 +0,0 @@ -FROM --platform=$BUILDPLATFORM golang:1.27.3-alpine AS build -WORKDIR /src - -# tunnel's go.mod currently has no gameaction requirement (no local -# replace directive), so this COPY is a no-op for the build. It is kept -# only for structural parity with sentinel/Dockerfile, api/Dockerfile, and -# agent/Dockerfile, which do depend on gameaction. -COPY gameaction/ ./gameaction/ -COPY tunnel/go.mod tunnel/go.sum* ./tunnel/ -WORKDIR /src/tunnel -RUN go mod download - -WORKDIR /src -COPY tunnel/ ./tunnel/ -WORKDIR /src/tunnel - -ARG VERSION=dev -# Cross-compile on the build host ($BUILDPLATFORM above) rather than under -# QEMU emulation: multi-arch release builds of the arm64 image were slow -# enough to hit the release job timeout. -ARG TARGETARCH -RUN CGO_ENABLED=0 GOOS=linux GOARCH=${TARGETARCH} go build \ - -trimpath \ - -ldflags="-s -w -X main.Version=${VERSION}" \ - -o /out/tunnel . - -# Build frpc from source instead of using the upstream release binary: the -# release binaries ship an older Go toolchain, golang.org/x/net and -# golang.org/x/crypto with fixed HIGH CVEs that the image scan rejects -# (spec 013 G2, T031). tunnel/frpc/go.mod pins frp and the newer x/net and -# x/crypto; go.sum makes the download checksum-verified. The noweb tag leaves -# out frpc's static admin web UI. The loopback-only authenticated JSON status -# API remains available for the supervisor's provider readiness checks. -FROM --platform=$BUILDPLATFORM golang:1.27-alpine AS frp-stage -WORKDIR /src/frpc -COPY tunnel/frpc/go.mod tunnel/frpc/go.sum ./ -RUN go mod download -ARG TARGETARCH -RUN CGO_ENABLED=0 GOOS=linux GOARCH=${TARGETARCH} GOFLAGS=-mod=readonly go build \ - -trimpath \ - -ldflags="-s -w" \ - -tags frpc,noweb \ - -o /out/frpc github.com/fatedier/frp/cmd/frpc - -FROM gcr.io/distroless/static:nonroot -WORKDIR / -COPY --from=build /out/tunnel /tunnel -COPY --from=frp-stage /out/frpc /usr/local/bin/frpc -USER 65532:65532 -EXPOSE 25565/tcp 25565/udp -EXPOSE 8091/tcp -ENTRYPOINT ["/tunnel"] diff --git a/tunnel/Dockerfile.playit b/tunnel/Dockerfile.playit deleted file mode 100644 index 44879392f..000000000 --- a/tunnel/Dockerfile.playit +++ /dev/null @@ -1,59 +0,0 @@ -FROM --platform=$BUILDPLATFORM golang:1.27.3-alpine AS build -WORKDIR /src - -# tunnel's go.mod currently has no gameaction requirement (no local -# replace directive), so this COPY is a no-op for the build. It is kept -# only for structural parity with sentinel/Dockerfile, api/Dockerfile, and -# agent/Dockerfile, which do depend on gameaction. -COPY gameaction/ ./gameaction/ -COPY tunnel/go.mod tunnel/go.sum* ./tunnel/ -WORKDIR /src/tunnel -RUN go mod download - -WORKDIR /src -COPY tunnel/ ./tunnel/ -WORKDIR /src/tunnel - -ARG VERSION=dev -# Cross-compile on the build host ($BUILDPLATFORM above) rather than under -# QEMU emulation: multi-arch release builds of the arm64 image were slow -# enough to hit the release job timeout. -ARG TARGETARCH -RUN CGO_ENABLED=0 GOOS=linux GOARCH=${TARGETARCH} go build \ - -trimpath \ - -ldflags="-s -w -X main.Version=${VERSION}" \ - -o /out/tunnel . - -# Build stage to download and verify playit binary -FROM alpine:3.24@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf AS playit-stage -ARG PLAYIT_VERSION=1.0.10 -ARG TARGETARCH -ARG PLAYIT_SHA256_amd64=2df7d9f10227ab312b1ad341853db4e8a8243df5cfcdbae58713a4271711c339 -ARG PLAYIT_SHA256_aarch64=4c0db3e7b3a8158e249441c2f0b73f54e83429395890c7b1ca45fd7a6303d763 - -RUN apk add --no-cache curl~=8.23.0 -WORKDIR /tmp -# DL4006: fail the RUN if any command in a pipe fails. -SHELL ["/bin/ash", "-o", "pipefail", "-c"] -RUN mkdir -p /out && \ - if [ "$TARGETARCH" = "arm64" ]; then \ - PLAYIT_ARCH="aarch64"; \ - PLAYIT_SHA256="$PLAYIT_SHA256_aarch64"; \ - else \ - PLAYIT_ARCH="amd64"; \ - PLAYIT_SHA256="$PLAYIT_SHA256_amd64"; \ - fi && \ - curl -fsSL "https://github.com/playit-cloud/playit-agent/releases/download/v${PLAYIT_VERSION}/playit-linux-${PLAYIT_ARCH}" \ - -o playit && \ - echo "${PLAYIT_SHA256} playit" | sha256sum -c - && \ - mv playit /out/playitd && \ - chmod +x /out/playitd - -FROM gcr.io/distroless/static:nonroot -WORKDIR / -COPY --from=build /out/tunnel /tunnel -COPY --from=playit-stage /out/playitd /usr/local/bin/playitd -USER 65532:65532 -EXPOSE 25565/tcp 25565/udp -EXPOSE 8091/tcp -ENTRYPOINT ["/tunnel"] diff --git a/tunnel/Dockerfile.tailscale b/tunnel/Dockerfile.tailscale deleted file mode 100644 index fc74b830b..000000000 --- a/tunnel/Dockerfile.tailscale +++ /dev/null @@ -1,33 +0,0 @@ -FROM --platform=$BUILDPLATFORM golang:1.27.3-alpine AS build -WORKDIR /src - -# tunnel's go.mod currently has no gameaction requirement (no local -# replace directive), so this COPY is a no-op for the build. It is kept -# only for structural parity with sentinel/Dockerfile, api/Dockerfile, and -# agent/Dockerfile, which do depend on gameaction. -COPY gameaction/ ./gameaction/ -COPY tunnel/go.mod tunnel/go.sum* ./tunnel/ -WORKDIR /src/tunnel -RUN go mod download - -WORKDIR /src -COPY tunnel/ ./tunnel/ -WORKDIR /src/tunnel - -ARG VERSION=dev -# Cross-compile on the build host ($BUILDPLATFORM above) rather than under -# QEMU emulation: multi-arch release builds of the arm64 image were slow -# enough to hit the release job timeout. -ARG TARGETARCH -RUN CGO_ENABLED=0 GOOS=linux GOARCH=${TARGETARCH} go build \ - -trimpath \ - -ldflags="-s -w -X main.Version=${VERSION}" \ - -o /out/tunnel . - -FROM gcr.io/distroless/static:nonroot -WORKDIR / -COPY --from=build /out/tunnel /tunnel -USER 65532:65532 -EXPOSE 25565/tcp 25565/udp -EXPOSE 8091/tcp -ENTRYPOINT ["/tunnel"] diff --git a/tunnel/bench/frp_udp.py b/tunnel/bench/frp_udp.py deleted file mode 100644 index d16a301c2..000000000 --- a/tunnel/bench/frp_udp.py +++ /dev/null @@ -1,135 +0,0 @@ -#!/usr/bin/env python3 -"""Compare UDP echo with a real frpc/frps on an isolated Linux runner.""" - -import argparse -import base64 -import contextlib -import hashlib -import json -import os -from pathlib import Path -import secrets -import socket -import subprocess -import tempfile -import time -import urllib.request - - -def port(sock_type): - with socket.socket(socket.AF_INET, sock_type) as listener: - listener.bind(("127.0.0.1", 0)) - return listener.getsockname()[1] - - -@contextlib.contextmanager -def child(args, cpu, logfile): - with open(logfile, "wb") as log: - proc = subprocess.Popen(["taskset", "-c", str(cpu), *args], stdout=log, stderr=log) - try: - yield proc - finally: - proc.terminate() - try: - proc.wait(5) - except subprocess.TimeoutExpired: - proc.kill() - proc.wait() - - -def cpu_seconds(proc): - # The command field may contain spaces. The remainder starts at field 3. - fields = Path(f"/proc/{proc.pid}/stat").read_text().rsplit(")", 1)[1].split() - return (int(fields[11]) + int(fields[12])) / os.sysconf("SC_CLK_TCK") - - -def proxy_bytes(request): - with urllib.request.urlopen(request, timeout=3) as response: - stats = json.load(response) - return stats["todayTrafficIn"], stats["todayTrafficOut"] - - -def ready(port_number, processes): - deadline = time.monotonic() + 15 - marker = secrets.token_bytes(16) - with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as probe: - probe.settimeout(0.15) - while time.monotonic() < deadline: - if any(p.poll() is not None for p in processes): - break - probe.sendto(marker, ("127.0.0.1", port_number)) - try: - if probe.recv(64) == marker: - return - except TimeoutError: - continue - raise RuntimeError("FRP did not return the UDP readiness echo") - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - for binary in ("relay-load", "frpc", "frps"): - parser.add_argument("--" + binary, type=Path, required=True) - parser.add_argument("--clients", type=int, nargs="+", default=[8, 32, 128]) - parser.add_argument("--hz", type=int, default=128) - parser.add_argument("--bytes", type=int, default=256) - parser.add_argument("--seconds", type=int, default=10) - options = parser.parse_args() - cpus = sorted(os.sched_getaffinity(0)) - if len(cpus) < 3: - parser.error("requires three available logical CPUs for the driver, echo and FRP") - client_cpu, echo_cpu, relay_cpu = cpus[:3] - binaries = {name: getattr(options, name).resolve() for name in ("relay_load", "frpc", "frps")} - digests = {} - for name, path in binaries.items(): - with path.open("rb") as stream: - digests[name] = hashlib.file_digest(stream, "sha256").hexdigest() - print(json.dumps({"kernel": os.uname().release, "affinity": [client_cpu, echo_cpu, relay_cpu], - "sha256": digests}), flush=True) - echo, remote, control = port(socket.SOCK_DGRAM), port(socket.SOCK_DGRAM), port(socket.SOCK_STREAM) - while remote == echo: - remote = port(socket.SOCK_DGRAM) - dashboard = port(socket.SOCK_STREAM) - while dashboard == control: - dashboard = port(socket.SOCK_STREAM) - token = secrets.token_hex(24) - request = urllib.request.Request(f"http://127.0.0.1:{dashboard}/api/proxy/udp/udp") - auth = base64.b64encode(f"bench:{token}".encode()).decode() - request.add_header("Authorization", "Basic " + auth) - with tempfile.TemporaryDirectory() as tmp, contextlib.ExitStack() as stack: - root = Path(tmp) - server_config, client_config = root / "frps.toml", root / "frpc.toml" - server_config.write_text(f'bindAddr = "127.0.0.1"\nbindPort = {control}\n' - f'proxyBindAddr = "127.0.0.1"\nauth.token = "{token}"\n' - f'webServer.addr = "127.0.0.1"\nwebServer.port = {dashboard}\n' - f'webServer.user = "bench"\nwebServer.password = "{token}"\n') - client_config.write_text(f'serverAddr = "127.0.0.1"\nserverPort = {control}\n' - f'auth.token = "{token}"\nloginFailExit = false\n' - f'[[proxies]]\nname = "udp"\ntype = "udp"\nlocalIP = "127.0.0.1"\n' - f'localPort = {echo}\nremotePort = {remote}\n') - backend = stack.enter_context(child([binaries["relay_load"], "-echo", f"127.0.0.1:{echo}"], echo_cpu, root / "echo.log")) - frps = stack.enter_context(child([binaries["frps"], "-c", server_config], relay_cpu, root / "frps.log")) - frpc = stack.enter_context(child([binaries["frpc"], "-c", client_config], relay_cpu, root / "frpc.log")) - ready(remote, [backend, frpc, frps]) - routes = [("direct", echo), ("frp", remote)] - for count in options.clients: - for iteration in range(2): - for route, target in (routes if iteration == 0 else reversed(routes)): - before = [cpu_seconds(p) for p in (backend, frpc, frps)] - traffic_before = proxy_bytes(request) - output = subprocess.check_output(["taskset", "-c", str(client_cpu), binaries["relay_load"], - "-clients", str(count), "-hz", str(options.hz), "-bytes", str(options.bytes), - "-seconds", str(options.seconds), f"127.0.0.1:{target}"], text=True) - after = [cpu_seconds(p) for p in (backend, frpc, frps)] - traffic_after = proxy_bytes(request) - sample = json.loads(output) - sample.update(route=route, iteration=iteration+1, - frps_payload_bytes={key: end-start for key, start, end in - zip(("in", "out"), traffic_before, traffic_after)}, - cpu_seconds={name: round(end-start, 3) for name, start, end in - zip(("echo", "frpc", "frps"), before, after)}) - print(json.dumps(sample), flush=True) - - -if __name__ == "__main__": - main() diff --git a/tunnel/bench/results/frp-loopback-series-1.jsonl b/tunnel/bench/results/frp-loopback-series-1.jsonl deleted file mode 100644 index ab6e70dc9..000000000 --- a/tunnel/bench/results/frp-loopback-series-1.jsonl +++ /dev/null @@ -1,17 +0,0 @@ -{"kernel": "6.18.54.1-microsoft-standard-WSL2", "affinity": [0, 1, 2], "sha256": {"relay_load": "3da9611f467f588a8628fa1100ffd1d0e7188fa2031d6602f8c43ec1a5bbf45a", "frpc": "1bdd67aa32d2e2e816486476e88086d265c17943243dc0d4d3cfeca3c871fcb7", "frps": "b95dee2bf29a021c562565cdf2116376b9fa7590361bd36ef57041a04d0e6654"}} -{"Endpoint": "127.0.0.1:56534", "Profile": {"Clients": 8, "Hz": 128, "Bytes": 256, "Seconds": 10}, "Scheduled": 10240, "Sent": 10240, "Received": 10240, "LateTicks": 0, "SentPerSecond": 1024, "LossPercent": 0, "RTTP95ms": 0.100232, "RTTP99ms": 0.137382, "JitterP95ms": 0.054514, "JitterP99ms": 0.103178, "route": "direct", "iteration": 1, "cpu_seconds": {"echo": 0.34, "frpc": 0.0, "frps": 0.0}} -{"Endpoint": "127.0.0.1:53361", "Profile": {"Clients": 8, "Hz": 128, "Bytes": 256, "Seconds": 10}, "Scheduled": 10240, "Sent": 10240, "Received": 10240, "LateTicks": 0, "SentPerSecond": 1024, "LossPercent": 0, "RTTP95ms": 0.283548, "RTTP99ms": 0.403424, "JitterP95ms": 0.130693, "JitterP99ms": 0.232676, "route": "frp", "iteration": 1, "cpu_seconds": {"echo": 0.3, "frpc": 0.73, "frps": 0.8}} -{"Endpoint": "127.0.0.1:53361", "Profile": {"Clients": 8, "Hz": 128, "Bytes": 256, "Seconds": 10}, "Scheduled": 10240, "Sent": 10240, "Received": 10240, "LateTicks": 0, "SentPerSecond": 1024, "LossPercent": 0, "RTTP95ms": 0.511848, "RTTP99ms": 0.649029, "JitterP95ms": 0.243634, "JitterP99ms": 0.400503, "route": "frp", "iteration": 2, "cpu_seconds": {"echo": 0.42, "frpc": 1.08, "frps": 1.13}} -{"Endpoint": "127.0.0.1:56534", "Profile": {"Clients": 8, "Hz": 128, "Bytes": 256, "Seconds": 10}, "Scheduled": 10240, "Sent": 10240, "Received": 10240, "LateTicks": 0, "SentPerSecond": 1024, "LossPercent": 0, "RTTP95ms": 0.109978, "RTTP99ms": 0.148238, "JitterP95ms": 0.06323, "JitterP99ms": 0.102043, "route": "direct", "iteration": 2, "cpu_seconds": {"echo": 0.38, "frpc": 0.0, "frps": 0.0}} -{"Endpoint": "127.0.0.1:56534", "Profile": {"Clients": 32, "Hz": 128, "Bytes": 256, "Seconds": 10}, "Scheduled": 40960, "Sent": 40508, "Received": 40508, "LateTicks": 452, "SentPerSecond": 4050.8, "LossPercent": 0, "RTTP95ms": 0.1047, "RTTP99ms": 0.153992, "JitterP95ms": 0.082942, "JitterP99ms": 0.133522, "route": "direct", "iteration": 1, "cpu_seconds": {"echo": 0.48, "frpc": 0.0, "frps": 0.0}} -{"Endpoint": "127.0.0.1:53361", "Profile": {"Clients": 32, "Hz": 128, "Bytes": 256, "Seconds": 10}, "Scheduled": 40960, "Sent": 40960, "Received": 40960, "LateTicks": 0, "SentPerSecond": 4096, "LossPercent": 0, "RTTP95ms": 0.476411, "RTTP99ms": 0.718606, "JitterP95ms": 0.307407, "JitterP99ms": 0.567035, "route": "frp", "iteration": 1, "cpu_seconds": {"echo": 0.65, "frpc": 1.81, "frps": 1.82}} -{"Endpoint": "127.0.0.1:53361", "Profile": {"Clients": 32, "Hz": 128, "Bytes": 256, "Seconds": 10}, "Scheduled": 40960, "Sent": 40960, "Received": 40960, "LateTicks": 0, "SentPerSecond": 4096, "LossPercent": 0, "RTTP95ms": 0.690579, "RTTP99ms": 1.46848, "JitterP95ms": 0.538819, "JitterP99ms": 1.554246, "route": "frp", "iteration": 2, "cpu_seconds": {"echo": 0.84, "frpc": 2.36, "frps": 2.32}} -{"Endpoint": "127.0.0.1:56534", "Profile": {"Clients": 32, "Hz": 128, "Bytes": 256, "Seconds": 10}, "Scheduled": 40960, "Sent": 40960, "Received": 40960, "LateTicks": 0, "SentPerSecond": 4096, "LossPercent": 0, "RTTP95ms": 0.126839, "RTTP99ms": 0.184476, "JitterP95ms": 0.102636, "JitterP99ms": 0.167214, "route": "direct", "iteration": 2, "cpu_seconds": {"echo": 0.59, "frpc": 0.0, "frps": 0.0}} -{"Endpoint": "127.0.0.1:56534", "Profile": {"Clients": 64, "Hz": 128, "Bytes": 256, "Seconds": 10}, "Scheduled": 81920, "Sent": 81920, "Received": 81920, "LateTicks": 0, "SentPerSecond": 8192, "LossPercent": 0, "RTTP95ms": 0.107584, "RTTP99ms": 0.170026, "JitterP95ms": 0.094993, "JitterP99ms": 0.166411, "route": "direct", "iteration": 1, "cpu_seconds": {"echo": 0.52, "frpc": 0.01, "frps": 0.0}} -{"Endpoint": "127.0.0.1:53361", "Profile": {"Clients": 64, "Hz": 128, "Bytes": 256, "Seconds": 10}, "Scheduled": 81920, "Sent": 81890, "Received": 81890, "LateTicks": 30, "SentPerSecond": 8189, "LossPercent": 0, "RTTP95ms": 0.569803, "RTTP99ms": 2.637348, "JitterP95ms": 0.502069, "JitterP99ms": 3.936536, "route": "frp", "iteration": 1, "cpu_seconds": {"echo": 1.11, "frpc": 3.16, "frps": 3.17}} -{"Endpoint": "127.0.0.1:53361", "Profile": {"Clients": 64, "Hz": 128, "Bytes": 256, "Seconds": 10}, "Scheduled": 81920, "Sent": 81920, "Received": 81920, "LateTicks": 0, "SentPerSecond": 8192, "LossPercent": 0, "RTTP95ms": 0.583034, "RTTP99ms": 1.743043, "JitterP95ms": 0.516584, "JitterP99ms": 3.292195, "route": "frp", "iteration": 2, "cpu_seconds": {"echo": 1.13, "frpc": 3.16, "frps": 3.1}} -{"Endpoint": "127.0.0.1:56534", "Profile": {"Clients": 64, "Hz": 128, "Bytes": 256, "Seconds": 10}, "Scheduled": 81920, "Sent": 81920, "Received": 81920, "LateTicks": 0, "SentPerSecond": 8192, "LossPercent": 0, "RTTP95ms": 0.109303, "RTTP99ms": 0.179286, "JitterP95ms": 0.094423, "JitterP99ms": 0.170029, "route": "direct", "iteration": 2, "cpu_seconds": {"echo": 0.52, "frpc": 0.0, "frps": 0.0}} -{"Endpoint": "127.0.0.1:56534", "Profile": {"Clients": 128, "Hz": 128, "Bytes": 256, "Seconds": 10}, "Scheduled": 163840, "Sent": 163840, "Received": 163840, "LateTicks": 0, "SentPerSecond": 16384, "LossPercent": 0, "RTTP95ms": 0.100862, "RTTP99ms": 0.207802, "JitterP95ms": 0.097609, "JitterP99ms": 0.210869, "route": "direct", "iteration": 1, "cpu_seconds": {"echo": 0.65, "frpc": 0.0, "frps": 0.0}} -{"Endpoint": "127.0.0.1:53361", "Profile": {"Clients": 128, "Hz": 128, "Bytes": 256, "Seconds": 10}, "Scheduled": 163840, "Sent": 163840, "Received": 163840, "LateTicks": 0, "SentPerSecond": 16384, "LossPercent": 0, "RTTP95ms": 0.517039, "RTTP99ms": 1.019293, "JitterP95ms": 0.435234, "JitterP99ms": 0.931959, "route": "frp", "iteration": 1, "cpu_seconds": {"echo": 1.64, "frpc": 4.9, "frps": 4.82}} -{"Endpoint": "127.0.0.1:53361", "Profile": {"Clients": 128, "Hz": 128, "Bytes": 256, "Seconds": 10}, "Scheduled": 163840, "Sent": 163645, "Received": 162711, "LateTicks": 195, "SentPerSecond": 16364.5, "LossPercent": 0.5707476549848758, "RTTP95ms": 32.389324, "RTTP99ms": 98.872337, "JitterP95ms": 7.483018, "JitterP99ms": 14.11685, "route": "frp", "iteration": 2, "cpu_seconds": {"echo": 1.57, "frpc": 5.07, "frps": 4.9}} -{"Endpoint": "127.0.0.1:56534", "Profile": {"Clients": 128, "Hz": 128, "Bytes": 256, "Seconds": 10}, "Scheduled": 163840, "Sent": 163840, "Received": 163840, "LateTicks": 0, "SentPerSecond": 16384, "LossPercent": 0, "RTTP95ms": 0.102153, "RTTP99ms": 0.198906, "JitterP95ms": 0.098885, "JitterP99ms": 0.204652, "route": "direct", "iteration": 2, "cpu_seconds": {"echo": 0.65, "frpc": 0.0, "frps": 0.0}} diff --git a/tunnel/bench/results/frp-loopback-series-2.jsonl b/tunnel/bench/results/frp-loopback-series-2.jsonl deleted file mode 100644 index cb9243234..000000000 --- a/tunnel/bench/results/frp-loopback-series-2.jsonl +++ /dev/null @@ -1,17 +0,0 @@ -{"kernel": "6.18.54.1-microsoft-standard-WSL2", "affinity": [0, 1, 2], "sha256": {"relay_load": "3da9611f467f588a8628fa1100ffd1d0e7188fa2031d6602f8c43ec1a5bbf45a", "frpc": "1bdd67aa32d2e2e816486476e88086d265c17943243dc0d4d3cfeca3c871fcb7", "frps": "b95dee2bf29a021c562565cdf2116376b9fa7590361bd36ef57041a04d0e6654"}} -{"Endpoint": "127.0.0.1:52067", "Profile": {"Clients": 8, "Hz": 128, "Bytes": 256, "Seconds": 10}, "Scheduled": 10240, "Sent": 10240, "Received": 10240, "LateTicks": 0, "SentPerSecond": 1024, "LossPercent": 0, "RTTP95ms": 0.143408, "RTTP99ms": 0.190281, "JitterP95ms": 0.074101, "JitterP99ms": 0.125843, "route": "direct", "iteration": 1, "frps_payload_bytes": {"in": 0, "out": 0}, "cpu_seconds": {"echo": 0.41, "frpc": 0.0, "frps": 0.0}} -{"Endpoint": "127.0.0.1:42557", "Profile": {"Clients": 8, "Hz": 128, "Bytes": 256, "Seconds": 10}, "Scheduled": 10240, "Sent": 10240, "Received": 10240, "LateTicks": 0, "SentPerSecond": 1024, "LossPercent": 0, "RTTP95ms": 0.557066, "RTTP99ms": 0.729997, "JitterP95ms": 0.279398, "JitterP99ms": 0.54059, "route": "frp", "iteration": 1, "frps_payload_bytes": {"in": 2621440, "out": 2621440}, "cpu_seconds": {"echo": 0.4, "frpc": 1.18, "frps": 1.23}} -{"Endpoint": "127.0.0.1:42557", "Profile": {"Clients": 8, "Hz": 128, "Bytes": 256, "Seconds": 10}, "Scheduled": 10240, "Sent": 10217, "Received": 10217, "LateTicks": 23, "SentPerSecond": 1021.7, "LossPercent": 0, "RTTP95ms": 0.609225, "RTTP99ms": 1.134632, "JitterP95ms": 0.324751, "JitterP99ms": 1.203781, "route": "frp", "iteration": 2, "frps_payload_bytes": {"in": 2615552, "out": 2615552}, "cpu_seconds": {"echo": 0.44, "frpc": 1.3, "frps": 1.41}} -{"Endpoint": "127.0.0.1:52067", "Profile": {"Clients": 8, "Hz": 128, "Bytes": 256, "Seconds": 10}, "Scheduled": 10240, "Sent": 10240, "Received": 10240, "LateTicks": 0, "SentPerSecond": 1024, "LossPercent": 0, "RTTP95ms": 0.097317, "RTTP99ms": 0.132451, "JitterP95ms": 0.053547, "JitterP99ms": 0.090909, "route": "direct", "iteration": 2, "frps_payload_bytes": {"in": 0, "out": 0}, "cpu_seconds": {"echo": 0.39, "frpc": 0.0, "frps": 0.0}} -{"Endpoint": "127.0.0.1:52067", "Profile": {"Clients": 32, "Hz": 128, "Bytes": 256, "Seconds": 10}, "Scheduled": 40960, "Sent": 40960, "Received": 40960, "LateTicks": 0, "SentPerSecond": 4096, "LossPercent": 0, "RTTP95ms": 0.094839, "RTTP99ms": 0.139368, "JitterP95ms": 0.072693, "JitterP99ms": 0.120781, "route": "direct", "iteration": 1, "frps_payload_bytes": {"in": 0, "out": 0}, "cpu_seconds": {"echo": 0.46, "frpc": 0.0, "frps": 0.0}} -{"Endpoint": "127.0.0.1:42557", "Profile": {"Clients": 32, "Hz": 128, "Bytes": 256, "Seconds": 10}, "Scheduled": 40960, "Sent": 40960, "Received": 40960, "LateTicks": 0, "SentPerSecond": 4096, "LossPercent": 0, "RTTP95ms": 0.502623, "RTTP99ms": 0.766653, "JitterP95ms": 0.333782, "JitterP99ms": 0.632525, "route": "frp", "iteration": 1, "frps_payload_bytes": {"in": 10485760, "out": 10485760}, "cpu_seconds": {"echo": 0.64, "frpc": 1.95, "frps": 1.96}} -{"Endpoint": "127.0.0.1:42557", "Profile": {"Clients": 32, "Hz": 128, "Bytes": 256, "Seconds": 10}, "Scheduled": 40960, "Sent": 40934, "Received": 40934, "LateTicks": 26, "SentPerSecond": 4093.4, "LossPercent": 0, "RTTP95ms": 0.956398, "RTTP99ms": 4.793461, "JitterP95ms": 1.241522, "JitterP99ms": 6.137561, "route": "frp", "iteration": 2, "frps_payload_bytes": {"in": 10479104, "out": 10479104}, "cpu_seconds": {"echo": 1.0, "frpc": 2.84, "frps": 2.86}} -{"Endpoint": "127.0.0.1:52067", "Profile": {"Clients": 32, "Hz": 128, "Bytes": 256, "Seconds": 10}, "Scheduled": 40960, "Sent": 40960, "Received": 40960, "LateTicks": 0, "SentPerSecond": 4096, "LossPercent": 0, "RTTP95ms": 0.12282, "RTTP99ms": 0.175106, "JitterP95ms": 0.096947, "JitterP99ms": 0.149704, "route": "direct", "iteration": 2, "frps_payload_bytes": {"in": 0, "out": 0}, "cpu_seconds": {"echo": 0.52, "frpc": 0.0, "frps": 0.0}} -{"Endpoint": "127.0.0.1:52067", "Profile": {"Clients": 64, "Hz": 128, "Bytes": 256, "Seconds": 10}, "Scheduled": 81920, "Sent": 81920, "Received": 81920, "LateTicks": 0, "SentPerSecond": 8192, "LossPercent": 0, "RTTP95ms": 0.10994, "RTTP99ms": 0.172769, "JitterP95ms": 0.103985, "JitterP99ms": 0.166513, "route": "direct", "iteration": 1, "frps_payload_bytes": {"in": 0, "out": 0}, "cpu_seconds": {"echo": 0.54, "frpc": 0.0, "frps": 0.0}} -{"Endpoint": "127.0.0.1:42557", "Profile": {"Clients": 64, "Hz": 128, "Bytes": 256, "Seconds": 10}, "Scheduled": 81920, "Sent": 81920, "Received": 81920, "LateTicks": 0, "SentPerSecond": 8192, "LossPercent": 0, "RTTP95ms": 1.060188, "RTTP99ms": 8.976369, "JitterP95ms": 1.414827, "JitterP99ms": 7.880654, "route": "frp", "iteration": 1, "frps_payload_bytes": {"in": 20971520, "out": 20971520}, "cpu_seconds": {"echo": 1.61, "frpc": 4.53, "frps": 4.63}} -{"Endpoint": "127.0.0.1:42557", "Profile": {"Clients": 64, "Hz": 128, "Bytes": 256, "Seconds": 10}, "Scheduled": 81920, "Sent": 81920, "Received": 81738, "LateTicks": 0, "SentPerSecond": 8192, "LossPercent": 0.22216796875, "RTTP95ms": 0.694952, "RTTP99ms": 1.331755, "JitterP95ms": 0.547313, "JitterP99ms": 1.397594, "route": "frp", "iteration": 2, "frps_payload_bytes": {"in": 20924928, "out": 20924928}, "cpu_seconds": {"echo": 1.53, "frpc": 4.37, "frps": 4.42}} -{"Endpoint": "127.0.0.1:52067", "Profile": {"Clients": 64, "Hz": 128, "Bytes": 256, "Seconds": 10}, "Scheduled": 81920, "Sent": 80455, "Received": 80455, "LateTicks": 1465, "SentPerSecond": 8045.5, "LossPercent": 0, "RTTP95ms": 0.182709, "RTTP99ms": 3.002783, "JitterP95ms": 0.209929, "JitterP99ms": 3.615604, "route": "direct", "iteration": 2, "frps_payload_bytes": {"in": 0, "out": 0}, "cpu_seconds": {"echo": 0.7, "frpc": 0.0, "frps": 0.0}} -{"Endpoint": "127.0.0.1:52067", "Profile": {"Clients": 128, "Hz": 128, "Bytes": 256, "Seconds": 10}, "Scheduled": 163840, "Sent": 163840, "Received": 161682, "LateTicks": 0, "SentPerSecond": 16384, "LossPercent": 1.317138671875, "RTTP95ms": 0.126521, "RTTP99ms": 0.277819, "JitterP95ms": 0.13044, "JitterP99ms": 0.304902, "route": "direct", "iteration": 1, "frps_payload_bytes": {"in": 0, "out": 0}, "cpu_seconds": {"echo": 0.69, "frpc": 0.01, "frps": 0.0}} -{"Endpoint": "127.0.0.1:42557", "Profile": {"Clients": 128, "Hz": 128, "Bytes": 256, "Seconds": 10}, "Scheduled": 163840, "Sent": 163840, "Received": 163840, "LateTicks": 0, "SentPerSecond": 16384, "LossPercent": 0, "RTTP95ms": 0.805736, "RTTP99ms": 1.865622, "JitterP95ms": 0.705019, "JitterP99ms": 2.058404, "route": "frp", "iteration": 1, "frps_payload_bytes": {"in": 41943040, "out": 41943040}, "cpu_seconds": {"echo": 1.58, "frpc": 4.87, "frps": 4.81}} -{"Endpoint": "127.0.0.1:42557", "Profile": {"Clients": 128, "Hz": 128, "Bytes": 256, "Seconds": 10}, "Scheduled": 163840, "Sent": 163840, "Received": 163840, "LateTicks": 0, "SentPerSecond": 16384, "LossPercent": 0, "RTTP95ms": 0.668417, "RTTP99ms": 1.360786, "JitterP95ms": 0.591355, "JitterP99ms": 1.391672, "route": "frp", "iteration": 2, "frps_payload_bytes": {"in": 41943040, "out": 41943040}, "cpu_seconds": {"echo": 1.64, "frpc": 5.05, "frps": 4.96}} -{"Endpoint": "127.0.0.1:52067", "Profile": {"Clients": 128, "Hz": 128, "Bytes": 256, "Seconds": 10}, "Scheduled": 163840, "Sent": 163840, "Received": 163840, "LateTicks": 0, "SentPerSecond": 16384, "LossPercent": 0, "RTTP95ms": 0.121325, "RTTP99ms": 0.224976, "JitterP95ms": 0.119238, "JitterP99ms": 0.221695, "route": "direct", "iteration": 2, "frps_payload_bytes": {"in": 0, "out": 0}, "cpu_seconds": {"echo": 0.72, "frpc": 0.0, "frps": 0.0}} diff --git a/tunnel/cmd/relay-load/main.go b/tunnel/cmd/relay-load/main.go deleted file mode 100644 index 32259e121..000000000 --- a/tunnel/cmd/relay-load/main.go +++ /dev/null @@ -1,80 +0,0 @@ -// Command relay-load measures the same open-loop UDP profile on each target. -package main - -import ( - "context" - "encoding/json" - "errors" - "flag" - "fmt" - "io" - "net" - "os" - "os/signal" - "syscall" - - "github.com/GameplanePanel/gameplane/tunnel/internal/relayload" -) - -func main() { - var profile relayload.Profile - flag.IntVar(&profile.Clients, "clients", 32, "UDP sockets per target") - flag.IntVar(&profile.Hz, "hz", 128, "packets per second per socket") - flag.IntVar(&profile.Bytes, "bytes", 256, "bytes per packet") - flag.IntVar(&profile.Seconds, "seconds", 10, "offered load duration per target") - echo := flag.String("echo", "", "listen for UDP echo on this host:port instead of measuring") - flag.Parse() - ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) - defer stop() - err := run(ctx, *echo, profile, flag.Args(), os.Stdout) - if err != nil && !errors.Is(err, context.Canceled) { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } -} - -func run(ctx context.Context, echo string, p relayload.Profile, endpoints []string, output io.Writer) error { - if echo != "" { - conn, err := (&net.ListenConfig{}).ListenPacket(ctx, "udp", echo) - if err != nil { - return fmt.Errorf("listen: %w", err) - } - defer func() { _ = conn.Close() }() - return serveEcho(ctx, conn) - } - if len(endpoints) == 0 { - return errors.New("specify a direct host:port followed by the relay targets, or use -echo host:port") - } - enc := json.NewEncoder(output) - for _, endpoint := range endpoints { - result, err := relayload.Measure(ctx, endpoint, p) - if err != nil { - return err - } - if err := enc.Encode(result); err != nil { - return fmt.Errorf("encode result: %w", err) - } - } - return nil -} - -func serveEcho(ctx context.Context, conn net.PacketConn) error { - stop := context.AfterFunc(ctx, func() { _ = conn.Close() }) - defer stop() - buf := make([]byte, 1401) - for ctx.Err() == nil { - n, peer, err := conn.ReadFrom(buf) - if err != nil { - if ctx.Err() != nil { - return ctx.Err() - } - return fmt.Errorf("read echo: %w", err) - } - if n >= 16 && n <= 1400 { - if _, err := conn.WriteTo(buf[:n], peer); err != nil { - return fmt.Errorf("write echo: %w", err) - } - } - } - return ctx.Err() -} diff --git a/tunnel/cmd/relay-load/main_test.go b/tunnel/cmd/relay-load/main_test.go deleted file mode 100644 index 952049b6d..000000000 --- a/tunnel/cmd/relay-load/main_test.go +++ /dev/null @@ -1,46 +0,0 @@ -package main - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "net" - "testing" - - "github.com/GameplanePanel/gameplane/tunnel/internal/relayload" -) - -func TestMeasureEcho(t *testing.T) { - ctx, cancel := context.WithCancel(t.Context()) - defer cancel() - conn, err := (&net.ListenConfig{}).ListenPacket(ctx, "udp", "127.0.0.1:0") - if err != nil { - t.Fatal(err) - } - defer conn.Close() - done := make(chan error, 1) - go func() { done <- serveEcho(ctx, conn) }() - var output bytes.Buffer - p := relayload.Profile{Clients: 2, Hz: 16, Bytes: 64, Seconds: 1} - if err := run(ctx, "", p, []string{conn.LocalAddr().String()}, &output); err != nil { - t.Fatal(err) - } - cancel() - if err := <-done; !errors.Is(err, context.Canceled) { - t.Fatalf("echo shutdown: %v", err) - } - var result relayload.Result - if err := json.Unmarshal(output.Bytes(), &result); err != nil { - t.Fatal(err) - } - if result.Scheduled != 32 || result.Received < 2 || result.Received > result.Sent || result.RTTP99ms == nil || result.JitterP95ms == nil { - t.Fatalf("unexpected direct profile: %+v", result) - } - if err := run(ctx, "", p, nil, &output); err == nil { - t.Fatal("accepted no target") - } - if err := run(ctx, "", relayload.Profile{}, []string{"127.0.0.1:1"}, &output); err == nil { - t.Fatal("accepted invalid profile") - } -} diff --git a/tunnel/forward_metrics.go b/tunnel/forward_metrics.go deleted file mode 100644 index 1d32817a6..000000000 --- a/tunnel/forward_metrics.go +++ /dev/null @@ -1,77 +0,0 @@ -package main - -import ( - "fmt" - "io" - "sync/atomic" - "time" -) - -// One instance per Tailscale supervisor, shared by every listener and retry. -type forwardTelemetry struct { - limits forwardLimits - tcp, udp flowCounts - queueDrops atomic.Uint64 - toBackend, toClient forwardLatency -} - -type flowCounts struct { - active atomic.Int64 - rejected atomic.Uint64 -} - -var latencyBounds = [...]time.Duration{100 * time.Microsecond, 500 * time.Microsecond, time.Millisecond, 5 * time.Millisecond, 10 * time.Millisecond, 50 * time.Millisecond, 100 * time.Millisecond} - -type forwardLatency struct { - bins [len(latencyBounds) + 1]atomic.Uint64 - nanos atomic.Int64 -} - -func (h *forwardLatency) observe(delay time.Duration) { - i := 0 - for i < len(latencyBounds) && delay > latencyBounds[i] { - i++ - } - h.bins[i].Add(1) - h.nanos.Add(int64(delay)) -} - -func (m *forwardTelemetry) writeMetrics(w io.Writer) { - const prefix = "gameplane_tunnel_" - protocols := [...]struct { - name string - f *flowCounts - }{{"tcp", &m.tcp}, {"udp", &m.udp}} - _, _ = fmt.Fprintln(w, "# TYPE "+prefix+"active_flows gauge") - for _, p := range protocols { - _, _ = fmt.Fprintf(w, "%sactive_flows{protocol=%q} %d\n", prefix, p.name, p.f.active.Load()) - } - _, _ = fmt.Fprintln(w, "# TYPE "+prefix+"flow_rejections_total counter") - for _, p := range protocols { - _, _ = fmt.Fprintf(w, "%sflow_rejections_total{protocol=%q} %d\n", prefix, p.name, p.f.rejected.Load()) - } - _, _ = fmt.Fprintf(w, "# TYPE %sudp_queue_drops_total counter\n%sudp_queue_drops_total %d\n", prefix, prefix, m.queueDrops.Load()) - const hist = prefix + "udp_forward_duration_seconds" - _, _ = fmt.Fprintln(w, "# TYPE "+hist+" histogram") - dirs := [...]struct { - name string - h *forwardLatency - }{{"to_backend", &m.toBackend}, {"to_client", &m.toClient}} - var packets [len(dirs)]uint64 - for i, d := range dirs { - var total uint64 - for b, limit := range latencyBounds { - total += d.h.bins[b].Load() - _, _ = fmt.Fprintf(w, "%s_bucket{direction=%q,le=\"%g\"} %d\n", hist, d.name, limit.Seconds(), total) - } - total += d.h.bins[len(latencyBounds)].Load() - packets[i] = total - _, _ = fmt.Fprintf(w, "%s_bucket{direction=%q,le=\"+Inf\"} %d\n", hist, d.name, total) - _, _ = fmt.Fprintf(w, "%s_count{direction=%q} %d\n", hist, d.name, total) - _, _ = fmt.Fprintf(w, "%s_sum{direction=%q} %g\n", hist, d.name, float64(d.h.nanos.Load())/1e9) - } - _, _ = fmt.Fprintln(w, "# TYPE "+prefix+"udp_forwarded_packets_total counter") - for i, d := range dirs { - _, _ = fmt.Fprintf(w, "%sudp_forwarded_packets_total{direction=%q} %d\n", prefix, d.name, packets[i]) - } -} diff --git a/tunnel/frpc/go.mod b/tunnel/frpc/go.mod deleted file mode 100644 index b7319cbd0..000000000 --- a/tunnel/frpc/go.mod +++ /dev/null @@ -1,55 +0,0 @@ -// Builds frpc from the pinned upstream frp release with newer -// golang.org/x/net and golang.org/x/crypto than the upstream binaries ship -// (spec 013 G2, T031). Not part of go.work; tunnel/Dockerfile.frp builds it. -module github.com/GameplanePanel/Gameplane/tunnel/frpc - -go 1.27.0 - -// Mirrors the replace in frp v0.71.0's own go.mod, which does not apply to -// dependents. -replace github.com/hashicorp/yamux => github.com/fatedier/yamux v0.0.0-20250825093530-d0154be01cd6 - -require ( - github.com/Azure/go-ntlmssp v0.1.1 // indirect - github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 // indirect - github.com/coreos/go-oidc/v3 v3.18.0 // indirect - github.com/fatedier/frp v0.71.0 // indirect - github.com/fatedier/golib v0.8.2 // indirect - github.com/go-jose/go-jose/v4 v4.1.6 // indirect - github.com/golang/snappy v0.0.4 // indirect - github.com/gorilla/mux v1.8.1 // indirect - github.com/hashicorp/yamux v0.1.1 // indirect - github.com/inconshreveable/mousetrap v1.1.0 // indirect - github.com/klauspost/cpuid/v2 v2.2.6 // indirect - github.com/klauspost/reedsolomon v1.12.0 // indirect - github.com/pelletier/go-toml/v2 v2.2.0 // indirect - github.com/pires/go-proxyproto v0.15.0 // indirect - github.com/pkg/errors v0.9.1 // indirect - github.com/quic-go/quic-go v0.60.0 // indirect - github.com/rodaine/table v1.2.0 // indirect - github.com/samber/lo v1.47.0 // indirect - github.com/songgao/water v0.0.0-20200317203138-2b4b6d7c09d8 // indirect - github.com/spf13/cobra v1.8.0 // indirect - github.com/spf13/pflag v1.0.5 // indirect - github.com/templexxx/cpu v0.1.1 // indirect - github.com/templexxx/xorsimd v0.4.3 // indirect - github.com/tjfoc/gmsm v1.4.1 // indirect - github.com/vishvananda/netlink v1.3.0 // indirect - github.com/vishvananda/netns v0.0.4 // indirect - github.com/xtaci/kcp-go/v5 v5.6.13 // indirect - golang.org/x/crypto v0.58.0 // indirect - golang.org/x/net v0.62.0 // indirect - golang.org/x/oauth2 v0.36.0 // indirect - golang.org/x/sync v0.24.0 // indirect - golang.org/x/sys v0.49.0 // indirect - golang.org/x/text v0.43.0 // indirect - golang.org/x/time v0.10.0 // indirect - golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 // indirect - golang.zx2c4.com/wireguard v0.0.0-20231211153847-12269c276173 // indirect - gopkg.in/ini.v1 v1.67.0 // indirect - gopkg.in/yaml.v2 v2.4.0 // indirect - k8s.io/apimachinery v0.28.8 // indirect - k8s.io/utils v0.0.0-20230406110748-d93618cff8a2 // indirect - sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect - sigs.k8s.io/yaml v1.3.0 // indirect -) diff --git a/tunnel/frpc/go.sum b/tunnel/frpc/go.sum deleted file mode 100644 index dab154d3d..000000000 --- a/tunnel/frpc/go.sum +++ /dev/null @@ -1,179 +0,0 @@ -cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -github.com/Azure/go-ntlmssp v0.1.0 h1:DjFo6YtWzNqNvQdrwEyr/e4nhU3vRiwenz5QX7sFz+A= -github.com/Azure/go-ntlmssp v0.1.0/go.mod h1:NYqdhxd/8aAct/s4qSYZEerdPuH1liG2/X9DiVTbhpk= -github.com/Azure/go-ntlmssp v0.1.1 h1:l+FM/EEMb0U9QZE7mKNEDw5Mu3mFiaa2GKOoTSsNDPw= -github.com/Azure/go-ntlmssp v0.1.1/go.mod h1:NYqdhxd/8aAct/s4qSYZEerdPuH1liG2/X9DiVTbhpk= -github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= -github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio= -github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= -github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= -github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= -github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= -github.com/coreos/go-oidc/v3 v3.18.0 h1:V9orjXynvu5wiC9SemFTWnG4F45v403aIcjWo0d41+A= -github.com/coreos/go-oidc/v3 v3.18.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4= -github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= -github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= -github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= -github.com/fatedier/frp v0.71.0 h1:hrzMepFp/asl2oAxxLMgffCI/wrzvg6lZyMzxEEnWbQ= -github.com/fatedier/frp v0.71.0/go.mod h1:331xzwO1dn+7QoHwW65q2FA2Zn/DaYqfxFUM7TUaH8I= -github.com/fatedier/golib v0.8.2 h1:02n2Dg7KJ7rR7p7n4/6hBUjaLQf2J7EiHYZQsgGTvww= -github.com/fatedier/golib v0.8.2/go.mod h1:ArUGvPg2cOw/py2RAuBt46nNZH2VQ5Z70p109MAZpJw= -github.com/fatedier/yamux v0.0.0-20250825093530-d0154be01cd6 h1:u92UUy6FURPmNsMBUuongRWC0rBqN6gd01Dzu+D21NE= -github.com/fatedier/yamux v0.0.0-20250825093530-d0154be01cd6/go.mod h1:c5/tk6G0dSpXGzJN7Wk1OEie8grdSJAmeawId9Zvd34= -github.com/go-jose/go-jose/v4 v4.1.6 h1:sNRkftxFJxwsILiQukqp5z83QBSmntVwmgRY7AqBDO4= -github.com/go-jose/go-jose/v4 v4.1.6/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= -github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= -github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= -github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= -github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= -github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= -github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= -github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= -github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= -github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= -github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM= -github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= -github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= -github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= -github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= -github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= -github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= -github.com/klauspost/cpuid/v2 v2.2.6 h1:ndNyv040zDGIDh8thGkXYjnFtiN02M1PVVF+JE/48xc= -github.com/klauspost/cpuid/v2 v2.2.6/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= -github.com/klauspost/reedsolomon v1.12.0 h1:I5FEp3xSwVCcEh3F5A7dofEfhXdF/bWhQWPH+XwBFno= -github.com/klauspost/reedsolomon v1.12.0/go.mod h1:EPLZJeh4l27pUGC3aXOjheaoh1I9yut7xTURiW3LQ9Y= -github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= -github.com/pelletier/go-toml/v2 v2.2.0 h1:QLgLl2yMN7N+ruc31VynXs1vhMZa7CeHHejIeBAsoHo= -github.com/pelletier/go-toml/v2 v2.2.0/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs= -github.com/pires/go-proxyproto v0.15.0 h1:dTshmNbFm/D+0+sbrxUuddPOZ5Y0B7c5NhtsBkm6LqI= -github.com/pires/go-proxyproto v0.15.0/go.mod h1:OXsCrKwrK2tXS9YrI5tkHx5xaQlO8FH3lFW76orFh24= -github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= -github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/quic-go/quic-go v0.60.0 h1:xcQioE8OM66UQLeUMHltK1CCcOu3JbVB4JAQdDQSB+0= -github.com/quic-go/quic-go v0.60.0/go.mod h1:wpKpjmPpftl30sL6pFh7REVpjbcCVy4zt2vDyK1TuJk= -github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= -github.com/rodaine/table v1.2.0 h1:38HEnwK4mKSHQJIkavVj+bst1TEY7j9zhLMWu4QJrMA= -github.com/rodaine/table v1.2.0/go.mod h1:wejb/q/Yd4T/SVmBSRMr7GCq3KlcZp3gyNYdLSBhkaE= -github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/samber/lo v1.47.0 h1:z7RynLwP5nbyRscyvcD043DWYoOcYRv3mV8lBeqOCLc= -github.com/samber/lo v1.47.0/go.mod h1:RmDH9Ct32Qy3gduHQuKJ3gW1fMHAnE/fAzQuf6He5cU= -github.com/songgao/water v0.0.0-20200317203138-2b4b6d7c09d8 h1:TG/diQgUe0pntT/2D9tmUCz4VNwm9MfrtPr0SU2qSX8= -github.com/songgao/water v0.0.0-20200317203138-2b4b6d7c09d8/go.mod h1:P5HUIBuIWKbyjl083/loAegFkfbFNx5i2qEP4CNbm7E= -github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0= -github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho= -github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= -github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= -github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= -github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= -github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= -github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= -github.com/templexxx/cpu v0.1.1 h1:isxHaxBXpYFWnk2DReuKkigaZyrjs2+9ypIdGP4h+HI= -github.com/templexxx/cpu v0.1.1/go.mod h1:w7Tb+7qgcAlIyX4NhLuDKt78AHA5SzPmq0Wj6HiEnnk= -github.com/templexxx/xorsimd v0.4.3 h1:9AQTFHd7Bhk3dIT7Al2XeBX5DWOvsUPZCuhyAtNbHjU= -github.com/templexxx/xorsimd v0.4.3/go.mod h1:oZQcD6RFDisW2Am58dSAGwwL6rHjbzrlu25VDqfWkQg= -github.com/tjfoc/gmsm v1.4.1 h1:aMe1GlZb+0bLjn+cKTPEvvn9oUEBlJitaZiiBwsbgho= -github.com/tjfoc/gmsm v1.4.1/go.mod h1:j4INPkHWMrhJb38G+J6W4Tw0AbuN8Thu3PbdVYhVcTE= -github.com/vishvananda/netlink v1.3.0 h1:X7l42GfcV4S6E4vHTsw48qbrV+9PVojNfIhZcwQdrZk= -github.com/vishvananda/netlink v1.3.0/go.mod h1:i6NetklAujEcC6fK0JPjT8qSwWyO0HLn4UKG+hGqeJs= -github.com/vishvananda/netns v0.0.4 h1:Oeaw1EM2JMxD51g9uhtC0D7erkIjgmj8+JZc26m1YX8= -github.com/vishvananda/netns v0.0.4/go.mod h1:SpkAiCQRtJ6TvvxPnOSyH3BMl6unz3xZlaprSwhNNJM= -github.com/xtaci/kcp-go/v5 v5.6.13 h1:FEjtz9+D4p8t2x4WjciGt/jsIuhlWjjgPCCWjrVR4Hk= -github.com/xtaci/kcp-go/v5 v5.6.13/go.mod h1:75S1AKYYzNUSXIv30h+jPKJYZUwqpfvLshu63nCNSOM= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20201012173705-84dcc777aaee/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= -golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= -golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= -golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= -golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20201010224723-4f7140c49acb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU= -golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= -golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= -golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= -golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= -golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs= -golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q= -golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= -golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= -golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= -golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= -golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= -golang.org/x/time v0.10.0 h1:3usCWA8tQn0L8+hFJQNgzpWbd89begxN66o1Ojdn5L4= -golang.org/x/time v0.10.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= -golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 h1:B82qJJgjvYKsXS9jeunTOisW56dUokqW/FOteYJJ/yg= -golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2/go.mod h1:deeaetjYA+DHMHg+sMSMI58GrEteJUUzzw7en6TJQcI= -golang.zx2c4.com/wireguard v0.0.0-20231211153847-12269c276173 h1:/jFs0duh4rdb8uIfPMv78iAJGcPKDeqAFnaLBropIC4= -golang.zx2c4.com/wireguard v0.0.0-20231211153847-12269c276173/go.mod h1:tkCQ4FQXmpAgYVh++1cq16/dH4QJtmvpRv19DWGAHSA= -google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= -google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= -google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= -google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= -google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= -google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= -google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= -google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= -google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= -google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= -google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= -google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= -google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= -google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= -gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= -gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= -gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -k8s.io/apimachinery v0.28.8 h1:hi/nrxHwk4QLV+W/SHve1bypTE59HCDorLY1stBIxKQ= -k8s.io/apimachinery v0.28.8/go.mod h1:cBnwIM3fXoRo28SqbV/Ihxf/iviw85KyXOrzxvZQ83U= -k8s.io/utils v0.0.0-20230406110748-d93618cff8a2 h1:qY1Ad8PODbnymg2pRbkyMT/ylpTrCM8P2RJ0yroCyIk= -k8s.io/utils v0.0.0-20230406110748-d93618cff8a2/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= -sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd h1:EDPBXCAspyGV4jQlpZSudPeMmr1bNJefnuqLsRAsHZo= -sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd/go.mod h1:B8JuhiUyNFVKdsE8h686QcCxMaH6HrOAZj4vswFpcB0= -sigs.k8s.io/yaml v1.3.0 h1:a2VclLzOGrwOHDiV8EfBGhvjHvP46CtW5j6POvhYGGo= -sigs.k8s.io/yaml v1.3.0/go.mod h1:GeOyir5tyXNByN85N/dRIT9es5UQNerPYEKK56eTBm8= diff --git a/tunnel/go.mod b/tunnel/go.mod deleted file mode 100644 index 12712b743..000000000 --- a/tunnel/go.mod +++ /dev/null @@ -1,51 +0,0 @@ -module github.com/GameplanePanel/gameplane/tunnel - -go 1.27.3 - -require tailscale.com v1.104.5 - -require ( - filippo.io/edwards25519 v1.2.0 // indirect - github.com/akutz/memconn v0.1.0 // indirect - github.com/alexbrainman/sspi v0.0.0-20250919150558-7d374ff0d59e // indirect - github.com/coder/websocket v1.8.15 // indirect - github.com/creachadair/msync v0.10.1 // indirect - github.com/dblohm7/wingoes v0.0.0-20260526185140-fb298caac7ca // indirect - github.com/fxamacker/cbor/v2 v2.9.3 // indirect - github.com/gaissmai/bart v0.29.0 // indirect - github.com/go-json-experiment/json v0.0.0-20260820222146-c27c302e5fc3 // indirect - github.com/godbus/dbus/v5 v5.2.2 // indirect - github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 // indirect - github.com/google/btree v1.1.3 // indirect - github.com/google/go-cmp v0.7.0 // indirect - github.com/hdevalence/ed25519consensus v0.2.0 // indirect - github.com/huin/goupnp v1.3.0 // indirect - github.com/jsimonetti/rtnetlink v1.4.2 // indirect - github.com/klauspost/compress v1.20.2 // indirect - github.com/mdlayher/netlink v1.11.2 // indirect - github.com/mdlayher/socket v0.7.0 // indirect - github.com/mitchellh/go-ps v1.0.0 // indirect - github.com/pires/go-proxyproto v0.15.0 // indirect - github.com/safchain/ethtool v0.7.0 // indirect - github.com/tailscale/certstore v0.1.1-0.20260409135935-3638fb84b77d // indirect - github.com/tailscale/go-winio v0.0.0-20231025203758-c4f33415bf55 // indirect - github.com/tailscale/hujson v0.0.0-20260727124030-b80ff77dac4f // indirect - github.com/tailscale/peercred v0.0.0-20250107143737-35a0c7bd7edc // indirect - github.com/tailscale/web-client-prebuilt v0.0.0-20260917222731-e0ed2d0d0fea // indirect - github.com/tailscale/wireguard-go v0.0.0-20260928213032-417aef361226 // indirect - github.com/x448/float16 v0.8.4 // indirect - go4.org/mem v0.0.0-20240501181205-ae6ca9944745 // indirect - go4.org/netipx v0.0.0-20260823151212-3075585bcbeb // indirect - golang.org/x/crypto v0.58.0 // indirect - golang.org/x/exp v0.0.0-20260908205506-85c1c2202aba // indirect - golang.org/x/net v0.62.0 // indirect - golang.org/x/oauth2 v0.37.0 // indirect - golang.org/x/sync v0.24.0 // indirect - golang.org/x/sys v0.49.0 // indirect - golang.org/x/term v0.47.0 // indirect - golang.org/x/text v0.43.0 // indirect - golang.org/x/time v0.16.0 // indirect - golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 // indirect - golang.zx2c4.com/wireguard/windows v1.0.1 // indirect - gvisor.dev/gvisor v0.0.0-20260915211658-a6f909f08a72 // indirect -) diff --git a/tunnel/go.sum b/tunnel/go.sum deleted file mode 100644 index 3ff74d576..000000000 --- a/tunnel/go.sum +++ /dev/null @@ -1,239 +0,0 @@ -9fans.net/go v0.0.8-0.20250307142834-96bdba94b63f h1:1C7nZuxUMNz7eiQALRfiqNOm04+m3edWlRff/BYHf0Q= -9fans.net/go v0.0.8-0.20250307142834-96bdba94b63f/go.mod h1:hHyrZRryGqVdqrknjq5OWDLGCTJ2NeEvtrpR96mjraM= -filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo= -filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc= -filippo.io/mkcert v1.4.4 h1:8eVbbwfVlaqUM7OwuftKc2nuYOoTDQWqsoXmzoXZdbc= -filippo.io/mkcert v1.4.4/go.mod h1:VyvOchVuAye3BoUsPUOOofKygVwLV2KQMVFJNRq+1dA= -github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk= -github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= -github.com/akutz/memconn v0.1.0 h1:NawI0TORU4hcOMsMr11g7vwlCdkYeLKXBcxWu2W/P8A= -github.com/akutz/memconn v0.1.0/go.mod h1:Jo8rI7m0NieZyLI5e2CDlRdRqRRB4S7Xp77ukDjH+Fw= -github.com/alexbrainman/sspi v0.0.0-20250919150558-7d374ff0d59e h1:4dAU9FXIyQktpoUAgOJK3OTFc/xug0PCXYCqU0FgDKI= -github.com/alexbrainman/sspi v0.0.0-20250919150558-7d374ff0d59e/go.mod h1:cEWa1LVoE5KvSD9ONXsZrj0z6KqySlCCNKHlLzbqAt4= -github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be h1:9AeTilPcZAjCFIImctFaOjnTIavg87rW78vTPkQqLI8= -github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be/go.mod h1:ySMOLuWl6zY27l47sB3qLNK6tF2fkHG55UZxx8oIVo4= -github.com/aws/aws-sdk-go-v2 v1.46.0 h1:1kt7m/EKcEHt5mlyyxx9cSlMddRPIKbjb6DIQsu4HPk= -github.com/aws/aws-sdk-go-v2 v1.46.0/go.mod h1:bttEH6JqnUL8LepvDVfdrds/fZ5bCIxzpe3abyUrhDU= -github.com/aws/aws-sdk-go-v2/config v1.33.3 h1:h090b3O5S17bF87/0ysHZuIT/7DCb4EBRFQX2PMVPCw= -github.com/aws/aws-sdk-go-v2/config v1.33.3/go.mod h1:YYDB1kTejxbfAbEVUqgCtkVp26xvNCHev9cLKABMGAk= -github.com/aws/aws-sdk-go-v2/credentials v1.20.3 h1:tToOYM/LXev4NpfWlIYGDvBvjHmJ3HXpRU9ppl+pM6k= -github.com/aws/aws-sdk-go-v2/credentials v1.20.3/go.mod h1:wfGneWyncO7p67wqXV2IQhPk14JqIc25woKlaArT3WI= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.19.2 h1:Ldv7RPHs7qwwTscRjAl3YBud32f3BvdAGRmSvAx5L38= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.19.2/go.mod h1:XyK6UV8xbo66ysVqLd2783C09pBYHOm8aKTRV5DVJ30= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.2 h1:q/PSLGuRWCChWg+dLnb9dWOnrCxJtnboXbBtFoqqRrI= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.2/go.mod h1:TD1jvU2LvXkJexct5vBqcd8QlNXh5EmRUeL/Z32p0n4= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.2 h1:6fl86IPqKEXoySqiOWdfgbEp9OVbn44zTfEICNEBDhY= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.2/go.mod h1:63HDfhFkdzBpI8WGXTSKUHPKS6mqldj4u3LJW7RZtSU= -github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.2 h1:XMgIRS+uW9F3yFKnXGRrI9pkHi99CXTmoz2kz2/TGBA= -github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.2/go.mod h1:vorxDzK+n3jiv9a5ST/LG0Eu9cSv1CRdKTpG6pDMs+M= -github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.19 h1:bAdDl/HkGCcGPoe25ToSHEw23VIxt6CT5fLcg111BKg= -github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.19/go.mod h1:KaUzbLxv4CeSxh6ZCl9B4m7CuFenS8kUEaDs+f/DQr4= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.2 h1:ZtHYnumr6QyxhzEzNZwzQTFJEXOswrZqTTkRxthwvr4= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.2/go.mod h1:a1NXrYpBd311gBzn1UI5UzJyyvXktM4xNh/ydPiPpqY= -github.com/aws/aws-sdk-go-v2/service/signin v1.9.0 h1:c3k+k/CS4L+sAIH6fxikL+g5g2LpeNczaoyjjw1iMKI= -github.com/aws/aws-sdk-go-v2/service/signin v1.9.0/go.mod h1:AGIoQg99fBrOIQnF78TLx4lj18mc4gZ0hJx1UaLIFM4= -github.com/aws/aws-sdk-go-v2/service/ssm v1.77.0 h1:JqKSBJlS68F4nxoPLwD7tB3lJ3gWEK9p+7eOiBE/lsM= -github.com/aws/aws-sdk-go-v2/service/ssm v1.77.0/go.mod h1:5TMMHmQGjCODMeIopSNfxkan11jG0SmFpyjcMvCLzHA= -github.com/aws/aws-sdk-go-v2/service/sso v1.37.0 h1:+rqBaOq7jzInjY8M12hr+zEe85JpRll9BjMx38r33Ok= -github.com/aws/aws-sdk-go-v2/service/sso v1.37.0/go.mod h1:XFlVwUsw3sYh8Hw37umYVJnrcWrwXWRxbNw/JY0bblw= -github.com/aws/aws-sdk-go-v2/service/ssooidc v1.42.0 h1:hzM3GslEAOBcLn3DHH6ENToFi+vXP+n02W+x6zejAIM= -github.com/aws/aws-sdk-go-v2/service/ssooidc v1.42.0/go.mod h1:588e7skMkYIYkSUseT8E3WKFfbAfrA1bj3Zf+qxJtJY= -github.com/aws/aws-sdk-go-v2/service/sts v1.49.0 h1:N7Ey8obY3uSui+cxl0OUzFlFmkxSucoJnrniFhw+cLc= -github.com/aws/aws-sdk-go-v2/service/sts v1.49.0/go.mod h1:zMBwjSf4Pt8a1OHYiZ5rPD0PJRK1kQrUaxhS/Dbld8E= -github.com/aws/smithy-go v1.28.1 h1:R/nXH00c8qcfCzQVELtRw+eLQWtzv+VAIEFJ1/xxXlQ= -github.com/aws/smithy-go v1.28.1/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc= -github.com/axiomhq/hyperloglog v0.2.6 h1:sRhvvF3RIXWQgAXaTphLp4yJiX4S0IN3MWTaAgZoRJw= -github.com/axiomhq/hyperloglog v0.2.6/go.mod h1:YjX/dQqCR/7QYX0g8mu8UZAjpIenz1FKM71UEsjFoTo= -github.com/benbjohnson/immutable v0.4.3 h1:GYHcksoJ9K6HyAUpGxwZURrbTkXA0Dh4otXGqbhdrjA= -github.com/benbjohnson/immutable v0.4.3/go.mod h1:qJIKKSmdqz1tVzNtst1DZzvaqOU1onk1rc03IeM3Owk= -github.com/bradfitz/reco v0.0.0-20260929154613-b883fbd17e3f h1:jdXGSp5Ge5/kzikuxGOw9+6HSStUjkNBJZjGNtpItek= -github.com/bradfitz/reco v0.0.0-20260929154613-b883fbd17e3f/go.mod h1:oiCPXxBoDKSkb/RGEZwAZk8y/fwDlQ1vYlBbNRxPysw= -github.com/cilium/ebpf v0.22.0 h1:v2ktp0roffpMOj2MMf3idtCQZOsAoC4BJbAJN+ke2bY= -github.com/cilium/ebpf v0.22.0/go.mod h1:CDzZbe2hC5JjlDC+CY3KFCzlYwN4gbxppYM+Z10bQt4= -github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA= -github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg= -github.com/coreos/go-iptables v0.8.0 h1:MPc2P89IhuVpLI7ETL/2tx3XZ61VeICZjYqDEgNsPRc= -github.com/coreos/go-iptables v0.8.0/go.mod h1:Qe8Bv2Xik5FyTXwgIbLAnv2sWSBmvWdFETJConOQ//Q= -github.com/creachadair/mds v0.31.0 h1:h4SXXgallvZfD8CFQnQNAOtBkUGpZjPwNBRQpHpHM/g= -github.com/creachadair/mds v0.31.0/go.mod h1:IZ3oLffgVNZ4O5WXTPxx7EX5ilSl1ypdv5FekYyynyI= -github.com/creachadair/msync v0.10.1 h1:14jT5Ujob64Zp2D3ZcUidayDMoXikhmYN8xBxEuPKPk= -github.com/creachadair/msync v0.10.1/go.mod h1:dFf4Z0cxE2nibFmAdq5OqTuGn++GgEqA9JuKH+7ceSA= -github.com/creachadair/taskgroup v0.14.4 h1:ttR8StLWmYA1O6x96YlTpQLXjKyRpO4RBo+OcO6W6C0= -github.com/creachadair/taskgroup v0.14.4/go.mod h1:uhCtIEsa7zpeMAFixddhCYjbJi7e4JMyU7OXUygkSsg= -github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s= -github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE= -github.com/dblohm7/wingoes v0.0.0-20260526185140-fb298caac7ca h1:h1Awca4lQOspNR/2eeo04Ricn5NixDX9mb17WSAgLhQ= -github.com/dblohm7/wingoes v0.0.0-20260526185140-fb298caac7ca/go.mod h1:2TGl1jRJrRpbzykmg7asHm3h08TqutUgQqY5v9k/g3c= -github.com/dgryski/go-metro v0.0.0-20250106013310-edb8663e5e33 h1:ucRHb6/lvW/+mTEIGbvhcYU3S8+uSNkuMjx/qZFfhtM= -github.com/dgryski/go-metro v0.0.0-20250106013310-edb8663e5e33/go.mod h1:c9O8+fpSOX1DM8cPNSkX/qsBWdkD4yd2dpciOWQjpBw= -github.com/digitalocean/go-smbios v0.0.0-20180907143718-390a4f403a8e h1:vUmf0yezR0y7jJ5pceLHthLaYf4bA5T14B6q39S4q2Q= -github.com/digitalocean/go-smbios v0.0.0-20180907143718-390a4f403a8e/go.mod h1:YTIHhz/QFSYnu/EhlF2SpU2Uk+32abacUYA5ZPljz1A= -github.com/djherbis/times v1.6.0 h1:w2ctJ92J8fBvWPxugmXIv7Nz7Q3iDMKNx9v5ocVH20c= -github.com/djherbis/times v1.6.0/go.mod h1:gOHeRAz2h+VJNZ5Gmc/o7iD9k4wW7NMVqieYCY99oc0= -github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= -github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= -github.com/fxamacker/cbor/v2 v2.9.3 h1:oQBnFATpNdY8gJHTndDDv5Xl4QqNaz51G5LLEPhng3Q= -github.com/fxamacker/cbor/v2 v2.9.3/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= -github.com/gaissmai/bart v0.29.0 h1:wO6HGE8g9YE0Wm0bCpYxwRzfQ4+fbJKOhL64e5ACGCI= -github.com/gaissmai/bart v0.29.0/go.mod h1:GREWQfTLRWz/c5FTOsIw+KkscuFkIV5t8Rp7Nd1Td5c= -github.com/github/fakeca v0.1.0 h1:Km/MVOFvclqxPM9dZBC4+QE564nU4gz4iZ0D9pMw28I= -github.com/github/fakeca v0.1.0/go.mod h1:+bormgoGMMuamOscx7N91aOuUST7wdaJ2rNjeohylyo= -github.com/go-json-experiment/json v0.0.0-20260820222146-c27c302e5fc3 h1:UADEEmDKgfXbtnGJZ97beY5XLo9ZechG1nlU4KnRrkE= -github.com/go-json-experiment/json v0.0.0-20260820222146-c27c302e5fc3/go.mod h1:tphK2c80bpPhMOI4v6bIc2xWywPfbqi1Z06+RcrMkDg= -github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE= -github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78= -github.com/go4org/hashtriemap v0.0.0-20260925222741-44e5305f85d9 h1:J8S+Ms89nvHX1F9Ma2m3KhdTl41ZhbFKMyAJqvDA+iE= -github.com/go4org/hashtriemap v0.0.0-20260925222741-44e5305f85d9/go.mod h1:OGmRfY/9QEK2P5zCRtmqfbCF283xPkU2dvVA4MvbvpI= -github.com/go4org/plan9netshell v0.0.0-20250324183649-788daa080737 h1:cf60tHxREO3g1nroKr2osU3JWZsJzkfi7rEg+oAB0Lo= -github.com/go4org/plan9netshell v0.0.0-20250324183649-788daa080737/go.mod h1:MIS0jDzbU/vuM9MC4YnBITCv+RYuTRq8dJzmCrFsK9g= -github.com/godbus/dbus/v5 v5.2.2 h1:TUR3TgtSVDmjiXOgAAyaZbYmIeP3DPkld3jgKGV8mXQ= -github.com/godbus/dbus/v5 v5.2.2/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c= -github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 h1:f+oWsMOmNPc8JmEHVZIycC7hBoQxHH9pNKQORJNozsQ= -github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8/go.mod h1:wcDNUvekVysuuOpQKo3191zZyTpiI6se1N1ULghS0sw= -github.com/google/btree v1.1.3 h1:CVpQJjYgC4VbzxeGVHfvZrv1ctoYCAI8vbl07Fcxlyg= -github.com/google/btree v1.1.3/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4= -github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= -github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= -github.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo= -github.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY= -github.com/google/nftables v0.3.0 h1:bkyZ0cbpVeMHXOrtlFc8ISmfVqq5gPJukoYieyVmITg= -github.com/google/nftables v0.3.0/go.mod h1:BCp9FsrbF1Fn/Yu6CLUc9GGZFw/+hsxfluNXXmxBfRM= -github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= -github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/hdevalence/ed25519consensus v0.2.0 h1:37ICyZqdyj0lAZ8P4D1d1id3HqbbG1N3iBb1Tb4rdcU= -github.com/hdevalence/ed25519consensus v0.2.0/go.mod h1:w3BHWjwJbFU29IRHL1Iqkw3sus+7FctEyM4RqDxYNzo= -github.com/huin/goupnp v1.3.0 h1:UvLUlWDNpoUdYzb2TCn+MuTWtcjXKSza2n6CBdQ0xXc= -github.com/huin/goupnp v1.3.0/go.mod h1:gnGPsThkYa7bFi/KWmEysQRf48l2dvR5bxr2OFckNX8= -github.com/illarion/gonotify/v3 v3.0.2 h1:O7S6vcopHexutmpObkeWsnzMJt/r1hONIEogeVNmJMk= -github.com/illarion/gonotify/v3 v3.0.2/go.mod h1:HWGPdPe817GfvY3w7cx6zkbzNZfi3QjcBm/wgVvEL1U= -github.com/insomniacslk/dhcp v0.0.0-20260901064844-234b97448fae h1:nXGg65fXsylSUTNNWwvHuQsXev7mhIzQTnZREPTbWzs= -github.com/insomniacslk/dhcp v0.0.0-20260901064844-234b97448fae/go.mod h1:tGfUTcnFYGYvVNCaZZhwlJySU/fQQxh9TmpsFzWXnnY= -github.com/jellydator/ttlcache/v3 v3.4.1 h1:bOdXmXiycyK6E6Qjyuj5vl+/vU3SCOoDs8a86NbHjAQ= -github.com/jellydator/ttlcache/v3 v3.4.1/go.mod h1:j7LO12PNghFg5+0v9budMAT4rDK4JY969jb9vOdOBBk= -github.com/jsimonetti/rtnetlink v1.4.2 h1:Df9w9TZ3npHTyDn0Ev9e1uzmN2odmXd0QX+J5GTEn90= -github.com/jsimonetti/rtnetlink v1.4.2/go.mod h1:92s6LJdE+1iOrw+F2/RO7LYI2Qd8pPpFNNUYW06gcoM= -github.com/kamstrup/intmap v0.5.2 h1:qnwBm1mh4XAnW9W9Ue9tZtTff8pS6+s6iKF6JRIV2Dk= -github.com/kamstrup/intmap v0.5.2/go.mod h1:gWUVWHKzWj8xpJVFf5GC0O26bWmv3GqdnIX/LMT6Aq4= -github.com/klauspost/compress v1.20.2 h1:v5tiZvm1KGLyg5d5oXdXe3lsSPrbEUiKoXGia//I7Qo= -github.com/klauspost/compress v1.20.2/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= -github.com/kortschak/wol v0.0.0-20200729010619-da482cc4850a h1:+RR6SqnTkDLWyICxS1xpjCi/3dhyV+TgZwA6Ww3KncQ= -github.com/kortschak/wol v0.0.0-20200729010619-da482cc4850a/go.mod h1:YTtCCM3ryyfiu4F7t8HQ1mxvp1UBdWM2r6Xa+nGWvDk= -github.com/kr/fs v0.1.0 h1:Jskdu9ieNAYnjxsi0LbQp1ulIKZV1LAFgK1tWhpZgl8= -github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= -github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= -github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= -github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= -github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= -github.com/mdlayher/genetlink v1.4.0 h1:f/Xs7Y2T+GyX9b3dbiUhnLE9InGs5F9RxJ2JwBMl71o= -github.com/mdlayher/genetlink v1.4.0/go.mod h1:d1hrKr8fwZU2JkcAtQUAzeTrI7nbgQSl+5k1cC0biSA= -github.com/mdlayher/netlink v1.11.2 h1:HKh2jqe+omdSWcQ88nrT7INE61B0NXfiSPFdgL4YbNI= -github.com/mdlayher/netlink v1.11.2/go.mod h1:uT2Yc/QLaZubzDpZIBi9d4GoeLwtp3x1AMeqSRrK2sA= -github.com/mdlayher/sdnotify v1.0.0 h1:Ma9XeLVN/l0qpyx1tNeMSeTjCPH6NtuD6/N9XdTlQ3c= -github.com/mdlayher/sdnotify v1.0.0/go.mod h1:HQUmpM4XgYkhDLtd+Uad8ZFK1T9D5+pNxnXQjCeJlGE= -github.com/mdlayher/socket v0.7.0 h1:qVREPVwtUMg17pwvveQxpurq0PVisMxi3FGgpsorMYQ= -github.com/mdlayher/socket v0.7.0/go.mod h1:f7iKql2EK/rfsWYDKofKjk2Ig7I+6HQWdMIdn1tO4A4= -github.com/miekg/dns v1.1.73 h1:uhT8nJxmTrPJYClxVxTCX+CVn6qnzSiybRk72Z6DgrE= -github.com/miekg/dns v1.1.73/go.mod h1:RW2Obtfd5NZHvOFe3zYG0W8koWOQtAzyHaLo8vASBuQ= -github.com/mitchellh/go-ps v1.0.0 h1:i6ampVEEF4wQFF+bkYfwYgY+F/uYJDktmvLPf7qIgjc= -github.com/mitchellh/go-ps v1.0.0/go.mod h1:J4lOc8z8yJs6vUwklHw2XEIiT4z4C40KtWVN3nvg8Pg= -github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= -github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= -github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 h1:zYyBkD/k9seD2A7fsi6Oo2LfFZAehjjQMERAvZLEDnQ= -github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646/go.mod h1:jpp1/29i3P1S/RLdc7JQKbRpFeM1dOBd8T9ki5s+AY8= -github.com/pierrec/lz4/v4 v4.1.26 h1:GrpZw1gZttORinvzBdXPUXATeqlJjqUG/D87TKMnhjY= -github.com/pierrec/lz4/v4 v4.1.26/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4= -github.com/pires/go-proxyproto v0.15.0 h1:dTshmNbFm/D+0+sbrxUuddPOZ5Y0B7c5NhtsBkm6LqI= -github.com/pires/go-proxyproto v0.15.0/go.mod h1:OXsCrKwrK2tXS9YrI5tkHx5xaQlO8FH3lFW76orFh24= -github.com/pkg/sftp v1.13.11 h1:0N92SLTB8JqASJB14ZLHHzFnBV8mG9zw4K7jghEFWuE= -github.com/pkg/sftp v1.13.11/go.mod h1:uNkH9roSXglNJqM+glJJi+TQXQUm0fXFWqCFmT8hsN0= -github.com/prometheus/client_model v0.6.3 h1:O0jaTVAYNxTHYInEPFJt5I3+sN8zqBtVMPTB1qyxiEo= -github.com/prometheus/client_model v0.6.3/go.mod h1:gpN5P9S7Rr6Yr92PiQ+Ixvhf6JZEkF1dnxsYL2aPBEM= -github.com/prometheus/common v0.71.0 h1:9KDAKb7Mj3HEVKyFCK6Dc/HIwlBzZIN2l7/lrHl3KK8= -github.com/prometheus/common v0.71.0/go.mod h1:CLJ5H8TEsGX8bl31BdMkfhIZ+QmZ9tBPPotUxUbfcmk= -github.com/rogpeppe/go-internal v1.16.0 h1:O9DK+vNMDVGLr2BeZqmpLeMjiMNkuXfcqntWbZV6S5g= -github.com/rogpeppe/go-internal v1.16.0/go.mod h1:DrUVZyrJU+txYW5/1kwtXQSMFio52ZOxX7yM1VHvnxs= -github.com/safchain/ethtool v0.7.0 h1:rlJzfDetsVvT61uz8x1YIcFn12akMfuPulHtZjtb7Is= -github.com/safchain/ethtool v0.7.0/go.mod h1:MenQKEjXdfkjD3mp2QdCk8B/hwvkrlOTm/FD4gTpFxQ= -github.com/studio-b12/gowebdav v0.13.0 h1:OcwSg6IQHOFNdYHn3bPOHwSE8looG8N56Y5xTT1asqQ= -github.com/studio-b12/gowebdav v0.13.0/go.mod h1:bHA7t77X/QFExdeAnDzK6vKM34kEZAcE1OX4MfiwjkE= -github.com/tailscale/certstore v0.1.1-0.20260409135935-3638fb84b77d h1:JcGKBZAL7ePLwOhUdN8qGQZlP5GueEiIZwY7R62pejE= -github.com/tailscale/certstore v0.1.1-0.20260409135935-3638fb84b77d/go.mod h1:XrBNfAFN+pwoWuksbFS9Ccxnopa15zJGgXRFN90l3K4= -github.com/tailscale/gliderssh v0.3.4-0.20261026144310-31f7cf365d3a h1:LQfS++EBVN2Bk9/FbFjJmdP/CsebU0OupOX58tO4p04= -github.com/tailscale/gliderssh v0.3.4-0.20261026144310-31f7cf365d3a/go.mod h1:wn16Km1EZOX4UEAyaZa3dBwfFGOJ7neck40NcwosJUw= -github.com/tailscale/go-winio v0.0.0-20231025203758-c4f33415bf55 h1:Gzfnfk2TWrk8Jj4P4c1a3CtQyMaTVCznlkLZI++hok4= -github.com/tailscale/go-winio v0.0.0-20231025203758-c4f33415bf55/go.mod h1:4k4QO+dQ3R5FofL+SanAUZe+/QfeK0+OIuwDIRu2vSg= -github.com/tailscale/golang-x-crypto v0.0.0-20260720160339-c86ca1284b96 h1:m9EAsCu/afUkg9YkknXaRqMPl/omkUNRol5yB7hbG0Y= -github.com/tailscale/golang-x-crypto v0.0.0-20260720160339-c86ca1284b96/go.mod h1:NC3xRCu4UR+m4n6ix8b6oLLbHa820Y0StbOQEdWTDo0= -github.com/tailscale/hujson v0.0.0-20260727124030-b80ff77dac4f h1:9hiVElpCmKzsBKQHkBqZ8LGzt82iLfM8egxr4sew+Ys= -github.com/tailscale/hujson v0.0.0-20260727124030-b80ff77dac4f/go.mod h1:8/zr1Tv0+cKpVtGCEB/7YfRXr2TszsMxMXLaT8YuBgU= -github.com/tailscale/netlink v1.1.1-0.20240822203006-4d49adab4de7 h1:uFsXVBE9Qr4ZoF094vE6iYTLDl0qCiKzYXlL6UeWObU= -github.com/tailscale/netlink v1.1.1-0.20240822203006-4d49adab4de7/go.mod h1:NzVQi3Mleb+qzq8VmcWpSkcSYxXIg0DkI6XDzpVkhJ0= -github.com/tailscale/peercred v0.0.0-20250107143737-35a0c7bd7edc h1:24heQPtnFR+yfntqhI3oAu9i27nEojcQ4NuBQOo5ZFA= -github.com/tailscale/peercred v0.0.0-20250107143737-35a0c7bd7edc/go.mod h1:f93CXfllFsO9ZQVq+Zocb1Gp4G5Fz0b0rXHLOzt/Djc= -github.com/tailscale/web-client-prebuilt v0.0.0-20260917222731-e0ed2d0d0fea h1:ah5jt6ZnxMvNclt6kBBoLcMpLLjMA44PTsnov2y7gpU= -github.com/tailscale/web-client-prebuilt v0.0.0-20260917222731-e0ed2d0d0fea/go.mod h1:agQPE6y6ldqCOui2gkIh7ZMztTkIQKH049tv8siLuNQ= -github.com/tailscale/wf v0.0.0-20240214030419-6fbb0a674ee6 h1:l10Gi6w9jxvinoiq15g8OToDdASBni4CyJOdHY1Hr8M= -github.com/tailscale/wf v0.0.0-20240214030419-6fbb0a674ee6/go.mod h1:ZXRML051h7o4OcI0d3AaILDIad/Xw0IkXaHM17dic1Y= -github.com/tailscale/wireguard-go v0.0.0-20260928213032-417aef361226 h1:v3Lpj2iHPWQDqeCwemQPz4fWweIEMLqBkwJqCjRyJQc= -github.com/tailscale/wireguard-go v0.0.0-20260928213032-417aef361226/go.mod h1:rUelGmuK4UnSJYM5gl5Mknp6YbwwcL8+VAPMhNYe+jg= -github.com/tailscale/xnet v0.0.0-20240729143630-8497ac4dab2e h1:zOGKqN5D5hHhiYUp091JqK7DPCqSARyUfduhGUY8Bek= -github.com/tailscale/xnet v0.0.0-20240729143630-8497ac4dab2e/go.mod h1:orPd6JZXXRyuDusYilywte7k094d7dycXXU5YnWsrwg= -github.com/tc-hib/winres v0.3.1 h1:CwRjEGrKdbi5CvZ4ID+iyVhgyfatxFoizjPhzez9Io4= -github.com/tc-hib/winres v0.3.1/go.mod h1:C/JaNhH3KBvhNKVbvdlDWkbMDO9H4fKKDaN7/07SSuk= -github.com/u-root/u-root v0.16.0 h1:wY40O83MBVks97+Is0WlFlOPSwKQMIrWP9R1IsrExg8= -github.com/u-root/u-root v0.16.0/go.mod h1:yL/XdSSW27PdGLgUh4MNRBy54mKM+TBLzpwiB4nwj90= -github.com/u-root/uio v0.0.0-20240224005618-d2acac8f3701 h1:pyC9PaHYZFgEKFdlp3G8RaCKgVpHZnecvArXvPXcFkM= -github.com/u-root/uio v0.0.0-20240224005618-d2acac8f3701/go.mod h1:P3a5rG4X7tI17Nn3aOIAYr5HbIMukwXG0urG0WuL8OA= -github.com/vishvananda/netns v0.0.5 h1:DfiHV+j8bA32MFM7bfEunvT8IAqQ/NzSJHtcmW5zdEY= -github.com/vishvananda/netns v0.0.5/go.mod h1:SpkAiCQRtJ6TvvxPnOSyH3BMl6unz3xZlaprSwhNNJM= -github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= -github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= -go4.org/mem v0.0.0-20240501181205-ae6ca9944745 h1:Tl++JLUCe4sxGu8cTpDzRLd3tN7US4hOxG5YpKCzkek= -go4.org/mem v0.0.0-20240501181205-ae6ca9944745/go.mod h1:reUoABIJ9ikfM5sgtSF3Wushcza7+WeD01VB9Lirh3g= -go4.org/netipx v0.0.0-20260823151212-3075585bcbeb h1:XBM4hvfwGAttkkiTIFfeigdfcL1xIfdKXqFdgiHGtDs= -go4.org/netipx v0.0.0-20260823151212-3075585bcbeb/go.mod h1:PLyyIXexvUFg3Owu6p/WfdlivPbZJsZdgWZlrGope/Y= -golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= -golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= -golang.org/x/exp v0.0.0-20260908205506-85c1c2202aba h1:Ck8QetSgk912qxWLMCKxd0in+aiyBQyDSMae6e/xmpU= -golang.org/x/exp v0.0.0-20260908205506-85c1c2202aba/go.mod h1:50RgIsmK7OwqzTTeqcSXQW8SswW0o8fRcDxmqGluJ8E= -golang.org/x/exp/typeparams v0.0.0-20260811152304-ee035b5b010f h1:+lI8cDJ4uceLipg2f1ODay7fEuLkk0BIHXd6PB8icxo= -golang.org/x/exp/typeparams v0.0.0-20260811152304-ee035b5b010f/go.mod h1:PqrXSW65cXDZH0k4IeUbhmg/bcAZDbzNz3byBpKCsXo= -golang.org/x/image v0.46.0 h1:b1+oYj0Jbp6K5MDT4i4/eZpYlk3V8SJhhDKh6LBHAyQ= -golang.org/x/image v0.46.0/go.mod h1:3B3W05VGVQyuXucLINLjXKrqISASfi4Xj+iCVkLMwew= -golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c= -golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o= -golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= -golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= -golang.org/x/oauth2 v0.37.0 h1:JUlcxA8oAtauLfiH8FX2/FkAWHAdi0QtGCGc+hofE98= -golang.org/x/oauth2 v0.37.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58= -golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= -golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= -golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= -golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= -golang.org/x/term v0.47.0 h1:cpyOwQkr2Nzxe2p6KnrTG7Ei2wtzjsuSjhpXXepZ/BM= -golang.org/x/term v0.47.0/go.mod h1:efAfAuG6RKABvg1ArGebRkvX6LXul14SM67o2e4mUCY= -golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= -golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= -golang.org/x/time v0.16.0 h1:vMb6ptszcQMkcwiRTAuNNU50gom6++Q/6gY2hDM6VDE= -golang.org/x/time v0.16.0/go.mod h1:rVKOqvZeKvrDKTQiAHJ7wmwP0RzleSphoEA9RcdLA0s= -golang.org/x/tools v0.51.0 h1:k4Xc/1Om9jwkBJBo4NVLMSARBoWtK10mx+W5BnXCeAI= -golang.org/x/tools v0.51.0/go.mod h1:9eEncMayCV6zRMGhR5eZEC2iBx98qWcF1HZ9Z7wJOoA= -golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 h1:B82qJJgjvYKsXS9jeunTOisW56dUokqW/FOteYJJ/yg= -golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2/go.mod h1:deeaetjYA+DHMHg+sMSMI58GrEteJUUzzw7en6TJQcI= -golang.zx2c4.com/wireguard v0.0.0-20260522210424-ecfc5a8d5446 h1:cqHQ3AycTHvM2R7ikgyX57D+XvtcSnGylsLkOVhta/w= -golang.zx2c4.com/wireguard v0.0.0-20260522210424-ecfc5a8d5446/go.mod h1:rpwXGsirqLqN2L0JDJQlwOboGHmptD5ZD6T2VmcqhTw= -golang.zx2c4.com/wireguard/windows v1.0.1 h1:eOxiDVbywPC+ZQqvdCK7x+ZwWXKbYv50TtH8ysFIbw8= -golang.zx2c4.com/wireguard/windows v1.0.1/go.mod h1:+fbT3FFdX4zzYDLwJh5+HPEcNN/3HyNdzhNSVsQM+zs= -google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc= -google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= -gvisor.dev/gvisor v0.0.0-20260915211658-a6f909f08a72 h1:EytKYr5WrVs+Aah/0xDO8ZAZZzS/iTEVC8ln4ipDbL0= -gvisor.dev/gvisor v0.0.0-20260915211658-a6f909f08a72/go.mod h1:8aLQqUBHDH8fY5y60lzmwDpMMbQCcT3EBfoSwhfaGCY= -honnef.co/go/tools v0.8.1 h1:+JKf3xJ1ni4CwrhVg4/pqsfPGP6vNAXcKbMXJodYx3w= -honnef.co/go/tools v0.8.1/go.mod h1:XA+OnlRA9EDh/ukGvXMNSZNKGwFQJ+5dER0ioUkOxks= -howett.net/plist v1.0.0 h1:7CrbWYbPPO/PyNy38b2EB/+gYbjCe2DXBxgtOOZbSQM= -howett.net/plist v1.0.0/go.mod h1:lqaXoTrLY4hg8tnEzNru53gicrbv7rrk+2xJA/7hw9g= -software.sslmate.com/src/go-pkcs12 v0.7.3 h1:JBQD3FDqYjTeyDAeZQklj2ar88ykBLtALloPJHyAauU= -software.sslmate.com/src/go-pkcs12 v0.7.3/go.mod h1:Qiz0EyvDRJjjxGyUQa2cCNZn/wMyzrRJ/qcDXOQazLI= -tailscale.com v1.104.5 h1:TLemRww20+bcQ0FEVTTZ7yMtVDZ4pOpSCL86Oo9g3mA= -tailscale.com v1.104.5/go.mod h1:Hq4zB8UpaxMW1fvqO30CLVQo3A7Ith0t9MnvEyiuoSA= diff --git a/tunnel/internal/relayload/load.go b/tunnel/internal/relayload/load.go deleted file mode 100644 index 1549f58f9..000000000 --- a/tunnel/internal/relayload/load.go +++ /dev/null @@ -1,187 +0,0 @@ -// Package relayload measures an open-loop UDP echo workload. -package relayload - -import ( - "context" - "crypto/rand" - "encoding/binary" - "errors" - "fmt" - "math" - "net" - "slices" - "sync" - "sync/atomic" - "time" -) - -// Profile is offered independently to each endpoint. -type Profile struct { - Clients int - Hz int - Bytes int - Seconds int -} - -// Result reports actual sends and unique replies within the one-second drain. -// Percentiles are milliseconds; empty samples encode as null. -type Result struct { - Endpoint string - Profile Profile - Scheduled, Sent, Received int - LateTicks int - SentPerSecond, LossPercent float64 - RTTP95ms, RTTP99ms, JitterP95ms, JitterP99ms *float64 -} - -func (p Profile) validate() error { - if p.Clients < 1 || p.Clients > 512 || p.Hz < 1 || p.Hz > 1000 || p.Bytes < 16 || p.Bytes > 1400 || p.Seconds < 1 || p.Seconds > 300 || p.Clients*p.Hz*p.Seconds > 2_000_000 { - return errors.New("need 1-512 clients, 1-1000 Hz, 16-1400 bytes, 1-300 seconds, at most 2 million samples") - } - return nil -} - -type clientResult struct { - sent, late int - rtt []time.Duration -} - -// Measure allocates a connected UDP socket per client, spaces sends across -// each tick and receives concurrently. Missed ticks are counted and skipped -// so a saturated load generator cannot fake the requested rate with bursts. -func Measure(ctx context.Context, endpoint string, p Profile) (Result, error) { - result := Result{Endpoint: endpoint, Profile: p} - if err := p.validate(); err != nil { - return result, err - } - target, err := net.ResolveUDPAddr("udp", endpoint) - if err != nil { - return result, fmt.Errorf("resolve target: %w", err) - } - conns := make([]*net.UDPConn, 0, p.Clients) - defer func() { - for _, c := range conns { - _ = c.Close() - } - }() - for range p.Clients { - conn, err := net.DialUDP("udp", nil, target) - if err != nil { - return result, fmt.Errorf("open client: %w", err) - } - conns = append(conns, conn) - } - ids := make([]byte, 8*p.Clients) - if _, err := rand.Read(ids); err != nil { - return result, fmt.Errorf("generate run ID: %w", err) - } - start := time.Now().Add(100 * time.Millisecond) - clients := make([]clientResult, p.Clients) - var workers sync.WaitGroup - for i, conn := range conns { - workers.Go(func() { clients[i] = drive(ctx, conn, p, start, [8]byte(ids[8*i:8*i+8]), i) }) - } - workers.Wait() - if err := ctx.Err(); err != nil { - return result, err - } - result.Scheduled = p.Clients * p.Hz * p.Seconds - var rtts, jitter []float64 - for _, c := range clients { - result.Sent += c.sent - result.LateTicks += c.late - var prev time.Duration - for _, rtt := range c.rtt { - if rtt > 0 { - rtts = append(rtts, float64(rtt)/float64(time.Millisecond)) - if prev > 0 { - jitter = append(jitter, math.Abs(float64(rtt-prev))/float64(time.Millisecond)) - } - } - prev = rtt - } - } - result.Received = len(rtts) - if result.Sent == 0 { - return result, errors.New("no packets sent") - } - result.SentPerSecond = float64(result.Sent) / float64(p.Seconds) - result.LossPercent = 100 * float64(result.Sent-result.Received) / float64(result.Sent) - result.RTTP95ms, result.RTTP99ms = percentiles(rtts) - result.JitterP95ms, result.JitterP99ms = percentiles(jitter) - return result, nil -} - -func percentiles(samples []float64) (*float64, *float64) { - if len(samples) == 0 { - return nil, nil - } - slices.Sort(samples) - return &samples[(95*len(samples)+99)/100-1], &samples[(99*len(samples)+99)/100-1] -} - -func drive(ctx context.Context, c *net.UDPConn, p Profile, start time.Time, id [8]byte, client int) clientResult { - n := p.Hz * p.Seconds - result := clientResult{rtt: make([]time.Duration, n)} - period := time.Second / time.Duration(p.Hz) - offset := time.Duration(client) * period / time.Duration(p.Clients) - _ = c.SetDeadline(start.Add(time.Duration(p.Seconds)*time.Second + time.Second)) - stop := context.AfterFunc(ctx, func() { _ = c.Close() }) - defer stop() - sentAt := make([]atomic.Int64, n) - done := make(chan struct{}) - go func() { - defer close(done) - buf := make([]byte, p.Bytes+1) - for { - size, err := c.Read(buf) - if err != nil { - var timeout net.Error - if (errors.As(err, &timeout) && timeout.Timeout()) || ctx.Err() != nil || errors.Is(err, net.ErrClosed) { - return - } - // Connected UDP receives asynchronous ICMP errors. Remaining - // samples can still succeed if the path recovers. - continue - } - if size != p.Bytes || [8]byte(buf[:8]) != id { - continue - } - seq := binary.BigEndian.Uint32(buf[8:12]) - if int64(seq) >= int64(n) || result.rtt[seq] != 0 { - continue - } - sent := time.Duration(sentAt[seq].Load()) - elapsed := time.Since(start) - if sent > 0 && sent < elapsed { - result.rtt[seq] = elapsed - sent - } - } - }() - packet := make([]byte, p.Bytes) - copy(packet, id[:]) - timer := time.NewTimer(time.Hour) - defer timer.Stop() - for seq := uint32(0); int64(seq) < int64(n); seq++ { - due := start.Add(offset + time.Duration(seq)*period) - timer.Reset(time.Until(due)) - select { - case <-ctx.Done(): - <-done - return result - case <-timer.C: - } - now := time.Now() - if now.Sub(due) >= period { - result.late++ - continue - } - binary.BigEndian.PutUint32(packet[8:12], seq) - sentAt[seq].Store(int64(now.Sub(start))) - if _, err := c.Write(packet); err == nil { - result.sent++ - } - } - <-done - return result -} diff --git a/tunnel/main.go b/tunnel/main.go deleted file mode 100644 index 02ac8202a..000000000 --- a/tunnel/main.go +++ /dev/null @@ -1,619 +0,0 @@ -// Command tunnel is a relay client supervisor that runs as a pod and -// configures/starts/supervises frp and playit, or embeds a Tailscale node. -// The binary picks its behavior from the TUNNEL_TYPE env var and handles provider-specific -// config rendering, credential management, and child process supervision. -// -// Configuration and contract (see operator/internal/controller/gameserver_tunnel.go -// on the operator side, which is authoritative): -// -// - Env: GAMESERVER_NAME, GAMESERVER_NAMESPACE, TUNNEL_TYPE (frp|tailscale|playit). -// - frp: FRP_SERVER_ADDR, FRP_SERVER_PORT, BACKING_SERVICE_DNS, BACKING_SERVICE_PORT. -// - tailscale: TAILSCALE_HOSTNAME, TAILSCALE_TAGS, BACKING_SERVICE_DNS, BACKING_SERVICE_PORTS. -// - playit: PLAYIT_TUNNEL_NAME, BACKING_SERVICE_DNS, BACKING_SERVICE_PORTS. Validated for the -// operator contract but NOT passed to playitd: playitd has no local config file for port -// forwards -- those are managed against the account tied to the secret key via the playit.gg -// dashboard/API, not by this supervisor. BACKING_SERVICE_PORTS also names the ports the -// address reporter (playit_reporter.go) maps playitd's assigned addresses onto before -// patching them into the GameServer's status.tunnelEndpoints. -// - Credentials Secret is mounted read-only at /etc/gameplane/tunnel-auth. -// - Credential key names: frp uses "token", tailscale uses "authKey", playit uses "secretKey". -package main - -import ( - "context" - "errors" - "fmt" - "log" - "os" - "os/exec" - "os/signal" - "path/filepath" - "strconv" - "strings" - "sync" - "syscall" - "time" -) - -// Version is overridden at build time via -ldflags (see Dockerfile). -var Version = "dev" - -const ( - tunnelAuthMountDir = "/etc/gameplane/tunnel-auth" - - // Rendered config file paths, one per provider. These are fixed - // (rather than a random os.CreateTemp name) for two reasons: (1) each - // pod running this supervisor hosts exactly one relay process for the - // lifetime of the container, so there is no concurrent-writer or - // collision risk a random name would guard against, and (2) they must - // be compile-time string constants -- not variables -- for buildCommand - // below to pass gosec's G204 subprocess-argument check structurally - // (see the doc comment on buildCommand). - frpConfigPath = "/tmp/gameplane-tunnel-frpc.toml" - playitAuthPath = "/tmp/gameplane-tunnel-playit-auth" -) - -// credentialsDir is the directory holding the mounted Secret's credential -// files. It defaults to the real mount point; it is a package-level -// variable, rather than a constant, solely so tests can repoint it at a -// t.TempDir() and exercise readCredentials' real success/error paths -// without depending on the container filesystem. Production code never -// changes it from tunnelAuthMountDir. -var credentialsDir = tunnelAuthMountDir - -// allowedCredentialKeys is the closed set of credential file names the -// supervisor will read, keyed by TUNNEL_TYPE. -var allowedCredentialKeys = map[string]string{ - "frp": "token", - "tailscale": "authKey", - "playit": "secretKey", -} - -func main() { - cfg, err := loadConfig(os.Getenv) - if err != nil { - log.Fatalf("config: %v", err) - } - - log.Printf("tunnel %s starting for %s/%s (provider=%s)", Version, cfg.GameServerNamespace, cfg.GameServerName, cfg.TunnelType) - - ctx, cancel := context.WithCancel(context.Background()) - sigCh := make(chan os.Signal, 1) - signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGINT) - go func() { - sig := <-sigCh - log.Printf("received signal %v, shutting down", sig) - cancel() - }() - - if err := run(ctx, cfg); err != nil { - log.Fatalf("tunnel exiting: %v", err) - } - cancel() - signal.Stop(sigCh) -} - -// Config holds the parsed configuration for the tunnel supervisor. -type Config struct { - GameServerName string - GameServerNamespace string - GameServerUID string - TunnelType string // "frp", "tailscale", or "playit" - - // FRP-specific - FrpServerAddr string - FrpServerPort int - BackingServiceDNS string - BackingServicePort string // "name:port,..." format - - // Tailscale-specific - ForwardLimits forwardLimits - TailscaleHostname string - TailscaleTags string // comma-separated - BackingServicePorts string // Tailscale: name:port:protocol; playit: name:port - - // Playit-specific - PlayitTunnelName string - // BackingServicePorts shared with Tailscale -} - -// loadConfig reads and validates the tunnel's configuration via getenv. -func loadConfig(getenv func(string) string) (Config, error) { - cfg := Config{ - GameServerName: getenv("GAMESERVER_NAME"), - GameServerNamespace: getenv("GAMESERVER_NAMESPACE"), - GameServerUID: getenv("GAMESERVER_UID"), - TunnelType: getenv("TUNNEL_TYPE"), - BackingServiceDNS: getenv("BACKING_SERVICE_DNS"), - } - - if cfg.GameServerName == "" { - return Config{}, errors.New("GAMESERVER_NAME is required") - } - if cfg.GameServerNamespace == "" { - return Config{}, errors.New("GAMESERVER_NAMESPACE is required") - } - if cfg.TunnelType == "" { - return Config{}, errors.New("TUNNEL_TYPE is required") - } - if cfg.BackingServiceDNS == "" { - return Config{}, errors.New("BACKING_SERVICE_DNS is required") - } - - switch cfg.TunnelType { - case "frp": - if !validFrpIdentity(cfg.GameServerUID) { - return Config{}, errors.New("GAMESERVER_UID must be a nonempty alphanumeric or hyphen identity for frp; update the operator and tunnel images together") - } - cfg.FrpServerAddr = getenv("FRP_SERVER_ADDR") - if cfg.FrpServerAddr == "" { - return Config{}, errors.New("FRP_SERVER_ADDR is required for frp provider") - } - - portStr := getenv("FRP_SERVER_PORT") - if portStr == "" { - cfg.FrpServerPort = 7000 - } else { - port, err := strconv.Atoi(portStr) - if err != nil || port < 1 || port > 65535 { - return Config{}, fmt.Errorf("invalid FRP_SERVER_PORT: %q", portStr) - } - cfg.FrpServerPort = port - } - - cfg.BackingServicePort = getenv("BACKING_SERVICE_PORT") - if cfg.BackingServicePort == "" { - return Config{}, errors.New("BACKING_SERVICE_PORT is required for frp provider") - } - - case "tailscale": - cfg.TailscaleHostname = getenv("TAILSCALE_HOSTNAME") - if cfg.TailscaleHostname == "" { - return Config{}, errors.New("TAILSCALE_HOSTNAME is required for tailscale provider") - } - cfg.TailscaleTags = getenv("TAILSCALE_TAGS") - cfg.ForwardLimits = defaultForwardLimits - for _, option := range []struct { - key string - value *int - max int - }{ - {"TAILSCALE_MAX_SESSIONS", &cfg.ForwardLimits.sessions, 256}, - {"TAILSCALE_UDP_QUEUE", &cfg.ForwardLimits.udpQueue, 16}, - } { - if raw := getenv(option.key); raw != "" { - n, err := strconv.Atoi(raw) - if err != nil || n < 1 || n > option.max { - return Config{}, fmt.Errorf("%s must be between 1 and %d", option.key, option.max) - } - *option.value = n - } - } - if cfg.ForwardLimits.sessions*(1+cfg.ForwardLimits.udpQueue) > 640 { - return Config{}, errors.New("configured Tailscale sessions times (UDP queue + 1) must not exceed 640") - } - - cfg.BackingServicePorts = getenv("BACKING_SERVICE_PORTS") - if cfg.BackingServicePorts == "" { - return Config{}, errors.New("BACKING_SERVICE_PORTS is required for tailscale provider") - } - - case "playit": - cfg.PlayitTunnelName = getenv("PLAYIT_TUNNEL_NAME") - if cfg.PlayitTunnelName == "" { - return Config{}, errors.New("PLAYIT_TUNNEL_NAME is required for playit provider") - } - - cfg.BackingServicePorts = getenv("BACKING_SERVICE_PORTS") - if cfg.BackingServicePorts == "" { - return Config{}, errors.New("BACKING_SERVICE_PORTS is required for playit provider") - } - - default: - return Config{}, fmt.Errorf("unsupported TUNNEL_TYPE: %q", cfg.TunnelType) - } - - return cfg, nil -} - -// run supervises the relay process until ctx is cancelled or the process -// exits with an unrecoverable error (e.g., bad credentials, missing config). -func run(ctx context.Context, cfg Config) error { - // Read the provider's credentials from the mounted Secret. - creds, err := readCredentials(cfg) - if err != nil { - return fmt.Errorf("read credentials: %w", err) - } - - if cfg.TunnelType == "tailscale" { - return runTailscale(ctx, cfg, creds) - } - - // Render the provider's config file. - configFile, err := renderConfig(cfg, creds) - if err != nil { - return fmt.Errorf("render config: %w", err) - } - defer func() { - if configFile != "" { - _ = os.Remove(configFile) - } - }() - - // playit assigns the public address server-side; poll playitd for it - // and report it into status.tunnelEndpoints for the lifetime of run. - // frp and tailscale addresses are computed by the operator from spec. - if cfg.TunnelType == "playit" { - reporterCtx, stopReporter := context.WithCancel(ctx) - waitReporter := startPlayitReporter(reporterCtx, cfg) - defer func() { - stopReporter() - waitReporter() - }() - } - - h := &relayHealth{connectionUnsupported: cfg.TunnelType == "playit"} - if ctx.Err() != nil { - return nil - } - if cfg.TunnelType == "frp" || cfg.TunnelType == "playit" { - closeHealth, err := startRelayHealth(ctx, h) - if err != nil { - return err - } - defer closeHealth() - } - return superviseRelay(ctx, cfg, h, relayHealthCheck(cfg, creds), func(attemptCtx context.Context) error { - log.Printf("starting %s relay process", cfg.TunnelType) - return runCommand(attemptCtx, buildCommand(attemptCtx, cfg)) - }, waitRelayRetry) -} - -// readCredentials reads the provider's credential from the mounted Secret directory. -func readCredentials(cfg Config) (string, error) { - keyName, ok := allowedCredentialKeys[cfg.TunnelType] - if !ok { - return "", fmt.Errorf("unknown tunnel type: %q", cfg.TunnelType) - } - - dir := filepath.Clean(credentialsDir) - path := filepath.Join(dir, keyName) - - // Defense in depth: keyName is drawn from the closed set above, but - // confirm the resolved path did not escape the mount directory before - // opening it, so a variable can never be used to read an arbitrary file. - rel, err := filepath.Rel(dir, path) - if err != nil || rel == ".." || strings.HasPrefix(rel, "../") { - return "", fmt.Errorf("credential path %q escapes mount directory %q", path, dir) - } - - data, err := os.ReadFile(path) - if err != nil { - // Don't log the file contents; log only the path. - return "", fmt.Errorf("read credential from %s: %w", path, err) - } - - return strings.TrimSpace(string(data)), nil -} - -// renderConfig generates the provider-specific config file and returns its path. -// The caller is responsible for cleaning it up. -func renderConfig(cfg Config, credential string) (string, error) { - switch cfg.TunnelType { - case "frp": - return renderFrpConfig(cfg, credential) - case "playit": - return renderPlayitConfig(credential) - default: - return "", fmt.Errorf("unknown tunnel type: %q", cfg.TunnelType) - } -} - -// renderFrpConfig generates an frpc config file at the fixed frpConfigPath -// (see the const block near the top of the file for why the path is fixed -// rather than a random os.CreateTemp name). -func renderFrpConfig(cfg Config, token string) (string, error) { - if !validFrpIdentity(cfg.GameServerUID) { - return "", errors.New("invalid GameServer UID for frp identity") - } - // Build the frpc config: server address/port, auth token, and per-port proxies. - config := fmt.Sprintf(` -user = "%s" -serverAddr = "%s" -serverPort = %d -auth.method = "token" -auth.token = "%s" -webServer.addr = "127.0.0.1" -webServer.port = 7400 -webServer.user = "gameplane" -webServer.password = "%s" -transport.heartbeatInterval = 5 -transport.heartbeatTimeout = 15 -transport.tcpMuxKeepaliveInterval = 5 -`, escapeTomlString(cfg.GameServerUID), escapeTomlString(cfg.FrpServerAddr), cfg.FrpServerPort, escapeTomlString(token), escapeTomlString(token)) - - // Parse BACKING_SERVICE_PORT format: - // "name:localPort:remotePort:protocol,name:localPort:remotePort:protocol,...". - // localPort is the backing Service's own port (from the GameTemplate's - // containerPort) and remotePort is the public port on the frps host the - // user picked (spec.networking.tunnel.frp.remotePorts); they are - // independent values. protocol is "tcp" or "udp", from the template - // port's own protocol. Using localPort/protocol unconditionally, rather - // than assuming remotePort also names the Service port and the port is - // always TCP, is the fix for F-052: frp only worked before when a - // user's remotePort happened to equal the Service port and the game - // used TCP. - for _, entry := range strings.Split(cfg.BackingServicePort, ",") { - entry = strings.TrimSpace(entry) - if entry == "" { - continue - } - parts := strings.Split(entry, ":") - if len(parts) != 4 { - return "", fmt.Errorf("invalid port mapping: %q", entry) - } - name := strings.TrimSpace(parts[0]) - localPort := strings.TrimSpace(parts[1]) - remotePort := strings.TrimSpace(parts[2]) - protocol := strings.ToLower(strings.TrimSpace(parts[3])) - if protocol != "tcp" && protocol != "udp" { - return "", fmt.Errorf("invalid port mapping protocol: %q", entry) - } - - config += fmt.Sprintf(` -[[proxies]] -name = "%s" -type = "%s" -localIP = "%s" -localPort = %s -remotePort = %s -`, escapeTomlString(name), protocol, cfg.BackingServiceDNS, localPort, remotePort) - } - - if err := os.WriteFile(frpConfigPath, []byte(config), 0o600); err != nil { - return "", fmt.Errorf("write frpc config: %w", err) - } - - return frpConfigPath, nil -} - -// tailscaleTagNameChar reports whether b may appear in a tag name after the -// "tag:" prefix: ASCII letters, digits and '-', per tailcfg.CheckTag. -func tailscaleTagNameChar(b byte) bool { - return (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || (b >= '0' && b <= '9') || b == '-' -} - -// parseTailscaleTags turns the raw TAILSCALE_TAGS value (a comma-separated -// list that may carry whitespace around each entry and empty entries from -// a leading, trailing or doubled comma) into fully qualified tags. Each -// entry is trimmed, empty entries are dropped, and a bare name gets the -// "tag:" prefix, as `tailscale up` itself does for a name with no colon. -// Duplicate tags are skipped, preserving order of first appearance. -// Every resulting tag must pass the same rule as tailscale's -// tailcfg.CheckTag: "tag:" followed by an ASCII letter, then only ASCII -// letters, digits or '-'. The first tag that fails is returned as an error -// and no tags are returned, so a bad value can never reach tsnet registration. -// It returns (nil, nil) when no -// non-empty entry remains. -func parseTailscaleTags(tagsStr string) ([]string, error) { - var tags []string - seen := make(map[string]bool) - for _, tag := range strings.Split(tagsStr, ",") { - tag = strings.TrimSpace(tag) - if tag == "" { - continue - } - if !strings.Contains(tag, ":") { - tag = "tag:" + tag - } - name, ok := strings.CutPrefix(tag, "tag:") - if !ok || name == "" { - return nil, fmt.Errorf("invalid tag %q: must be \"tag:\" followed by a name", tag) - } - if (name[0] < 'a' || name[0] > 'z') && (name[0] < 'A' || name[0] > 'Z') { - return nil, fmt.Errorf("invalid tag %q: the name must start with a letter", tag) - } - for i := 0; i < len(name); i++ { - if !tailscaleTagNameChar(name[i]) { - return nil, fmt.Errorf("invalid tag %q: the name may only contain letters, digits or '-'", tag) - } - } - if seen[tag] { - continue - } - seen[tag] = true - tags = append(tags, tag) - } - return tags, nil -} - -// renderPlayitConfig writes the secret key to the fixed playitAuthPath -// (see the const block near the top of the file for why the path is fixed -// rather than a random os.CreateTemp name) for playitd's --secret-path flag. -// -// playitd (confirmed against playit-cloud/playit-agent's own source: the -// playitd CLI in packages/playitd/src/bin/playitd.rs takes only --secret, -// --secret-path, --socket-path, --log-path, --platform-docker, and -// --version-overrides) has no local config file for port forwards or a -// tunnel name -- those are configured against the account tied to this -// secret key via the playit.gg dashboard/API, not by this supervisor. The -// PlayitTunnelName and BackingServicePorts fields on Config are -// intentionally not used here; see the package doc comment. -// -// --secret-path (rather than passing the key inline via --secret) is used -// so the secret never appears in the process's argv, which is readable by -// anything that can see /proc//cmdline in the pod. -func renderPlayitConfig(secretKey string) (string, error) { - if err := os.WriteFile(playitAuthPath, []byte(secretKey), 0o600); err != nil { - return "", fmt.Errorf("write playit secret: %w", err) - } - - return playitAuthPath, nil -} - -// escapeTomlString escapes special characters in a TOML string value. -func escapeTomlString(s string) string { - return strings.NewReplacer( - "\\", "\\\\", - "\"", "\\\"", - "\n", "\\n", - "\r", "\\r", - "\t", "\\t", - ).Replace(s) -} - -// buildCommand constructs the command to run the relay process for -// cfg.TunnelType, or nil for an unrecognized type. loadConfig already -// rejects any TunnelType outside "frp"/"tailscale"/"playit" before run() -// is ever reached in the normal main() contract, so the nil case only -// happens if a caller builds a Config by hand (see TestBuildCommandUnknownType). -// -// frpc's TOML embeds its token, and playitd's --secret-path points to a -// private credential file. buildCommand never needs the raw credential. -// Tailscale uses the embedded node path and does not call this function. -// -// The relay binary path and config-file path are both named constants -// (rather than parameters or computed variables) so every argument to -// exec.CommandContext below is either a literal or resolves to one: that is -// what lets this pass gosec's G204 check structurally instead of via -// suppression. G204 flags any subprocess argument it cannot prove constant; -// a previous revision here took the binary path as a flag-configurable -// parameter (validated post hoc by an allow-list) specifically for -// testability, but gosec's analysis doesn't follow that validation, so it -// kept flagging the variable regardless. Since loadConfig already restricts -// TunnelType to a closed set before run() is ever reached, there is no -// legitimate case where a different binary or config path should be used -// for a given provider, so hardcoding both as consts loses nothing at -// runtime. Tests cover the resulting argument lists directly (see -// TestBuildCommandFrp et al.) rather than by exec'ing anything. -// -// The command is tied to ctx so cancellation stops the child (see -// runCommand, which overrides the default Cancel behavior to signal -// SIGTERM rather than SIGKILL). -func buildCommand(ctx context.Context, cfg Config) *exec.Cmd { - switch cfg.TunnelType { - case "frp": - // Confirmed against fatedier/frp's cmd/frpc/sub/root.go: "-c"/"--config" - // is frpc's real config-file flag. - return exec.CommandContext(ctx, "/usr/local/bin/frpc", "-c", frpConfigPath) - case "playit": - // Confirmed against playit-cloud/playit-agent's packages/playitd/src/bin/playitd.rs - // and its own Dockerfile/docker/entrypoint.sh, which exec exactly this - // (playitd --secret ... --platform-docker) as the foreground process in - // their official container image. playit-cli (historically installed as - // "playit") is a separate *service manager* around playitd with no flag - // to run a tunnel in the foreground under this file's exec+Wait - // supervision model, so playitd -- not playit-cli -- is the binary here. - // - // --socket-path moves playitd's IPC control socket from its Linux - // default (/run/playit/playitd.sock, which this non-root distroless - // image can't create) to a fixed /tmp path; the address reporter in - // playit_reporter.go polls it for the assigned public address (F-174). - return exec.CommandContext(ctx, "/usr/local/bin/playitd", - "--secret-path", playitAuthPath, - "--socket-path", playitSocketPath, - "--platform-docker", - ) - default: - return nil - } -} - -// runCommand executes the relay command and waits for it to exit or ctx to cancel. -// -// cmd must have been built with exec.CommandContext against the same ctx -// (see buildCommand). By default that arranges to SIGKILL the child the -// instant ctx is done; that's too abrupt for a relay process, so this -// overrides Cancel to send SIGTERM instead and gives it WaitDelay to exit -// cleanly before exec falls back to a hard kill. -func runCommand(ctx context.Context, cmd *exec.Cmd) error { - // Inherit stdio so relay logs flow through to the pod's stdout/stderr. - cmd.Stdout = os.Stdout - cmd.Stderr = os.Stderr - cmd.Stdin = os.Stdin - - cmd.Cancel = func() error { - if cmd.Process == nil { - return nil - } - return cmd.Process.Signal(syscall.SIGTERM) - } - cmd.WaitDelay = 10 * time.Second - - if err := cmd.Start(); err != nil { - return fmt.Errorf("start relay: %w", err) - } - - err := cmd.Wait() - if ctx.Err() != nil { - // Context was cancelled; cmd.Cancel already signalled the child and - // exec.Cmd waited (up to WaitDelay) for it to exit. - return ctx.Err() - } - return err -} - -// isUnrecoverable reports whether an error is unrecoverable (e.g., bad config, -// missing credentials) vs. transient (e.g., network failure, relay unavailable). -// Heuristic: if the error looks like a permission/config issue, it's unrecoverable; -// otherwise assume it's transient and worth retrying. -func isUnrecoverable(_ Config, err error) bool { - if err == nil { - return false - } - errStr := err.Error() - // Exit code 126 or 127: permission denied or command not found (unrecoverable). - if strings.Contains(errStr, "exit status 126") || strings.Contains(errStr, "exit status 127") { - return true - } - // Permission denied reading credentials or config: unrecoverable. - if strings.Contains(errStr, "permission denied") { - return true - } - return false -} - -// exponentialBackoff tracks restart delay with capped exponential backoff. -type exponentialBackoff struct { - mu sync.Mutex - retries int -} - -func (b *exponentialBackoff) reset() { - b.mu.Lock() - defer b.mu.Unlock() - b.retries = 0 -} - -// next returns the next backoff duration and increments the retry counter. -func (b *exponentialBackoff) next() time.Duration { - b.mu.Lock() - defer b.mu.Unlock() - - // Exponential backoff: 1s, 2s, 4s, 8s, 16s, capped at 5 minutes. - // - // No jitter: jitter exists to spread out a thundering herd of many - // replicas reconnecting to the same endpoint at once. This supervisor - // runs as a single-replica Deployment per GameServer talking to its own - // dedicated relay connection, so there's no herd here to spread out, - // and adding one would only make restart timing less predictable to - // operators reading logs. - // - // retries is capped at 10 before the shift: base already saturates at - // the 300s cap below by retries==10 (1<<9 = 512 > 300), so counting any - // higher never changes the returned delay. The cap matters because, - // uncapped, a relay that stays up long enough to reach 64 lifetime - // retries hit undefined shift behavior: on a 64-bit int, 1<<63 is - // math.MinInt64, which is not > 300 so the cap below was skipped, and - // time.Duration(MinInt64)*time.Second wrapped again to 0 -- sending the - // supervisor into a busy restart loop from the 64th retry on (F-172). - if b.retries < 10 { - b.retries++ - } - - base := 1 << uint(b.retries-1) - if base > 300 { - base = 300 - } - return time.Duration(base) * time.Second -} diff --git a/tunnel/main_test.go b/tunnel/main_test.go deleted file mode 100644 index bfcf6526a..000000000 --- a/tunnel/main_test.go +++ /dev/null @@ -1,1106 +0,0 @@ -package main - -import ( - "context" - "errors" - "os" - "os/exec" - "path/filepath" - "strings" - "testing" - "time" -) - -// ----------------------------------------------------------------------- -// loadConfig tests -// ----------------------------------------------------------------------- - -func stubEnv(vars map[string]string) func(string) string { - return func(key string) string { - if key == "GAMESERVER_UID" && vars["TUNNEL_TYPE"] == "frp" { - return "fixture-uid" - } - return vars[key] - } -} - -func TestLoadConfigFrp(t *testing.T) { - cfg, err := loadConfig(stubEnv(map[string]string{ - "GAMESERVER_NAME": "my-server", - "GAMESERVER_NAMESPACE": "games", - "TUNNEL_TYPE": "frp", - "FRP_SERVER_ADDR": "frp.example.com", - "FRP_SERVER_PORT": "7000", - "BACKING_SERVICE_DNS": "my-server.games.svc", - "BACKING_SERVICE_PORT": "game:25565", - })) - if err != nil { - t.Fatalf("loadConfig() error = %v", err) - } - if cfg.GameServerName != "my-server" { - t.Errorf("GameServerName = %q, want %q", cfg.GameServerName, "my-server") - } - if cfg.TunnelType != "frp" { - t.Errorf("TunnelType = %q, want %q", cfg.TunnelType, "frp") - } - if cfg.FrpServerAddr != "frp.example.com" { - t.Errorf("FrpServerAddr = %q, want %q", cfg.FrpServerAddr, "frp.example.com") - } - if cfg.FrpServerPort != 7000 { - t.Errorf("FrpServerPort = %d, want %d", cfg.FrpServerPort, 7000) - } -} - -func TestLoadConfigFrpDefaultPort(t *testing.T) { - cfg, err := loadConfig(stubEnv(map[string]string{ - "GAMESERVER_NAME": "my-server", - "GAMESERVER_NAMESPACE": "games", - "TUNNEL_TYPE": "frp", - "FRP_SERVER_ADDR": "frp.example.com", - "BACKING_SERVICE_DNS": "my-server.games.svc", - "BACKING_SERVICE_PORT": "game:25565", - })) - if err != nil { - t.Fatalf("loadConfig() error = %v", err) - } - if cfg.FrpServerPort != 7000 { - t.Errorf("default FrpServerPort = %d, want %d", cfg.FrpServerPort, 7000) - } -} - -func TestLoadConfigTailscale(t *testing.T) { - cfg, err := loadConfig(stubEnv(map[string]string{ - "GAMESERVER_NAME": "my-server", - "GAMESERVER_NAMESPACE": "games", - "TUNNEL_TYPE": "tailscale", - "TAILSCALE_HOSTNAME": "my-game", - "TAILSCALE_TAGS": "tag:gameplane,tag:game", - "BACKING_SERVICE_DNS": "my-server.games.svc", - "BACKING_SERVICE_PORTS": "game:25565:tcp", - })) - if err != nil { - t.Fatalf("loadConfig() error = %v", err) - } - if cfg.TunnelType != "tailscale" { - t.Errorf("TunnelType = %q, want %q", cfg.TunnelType, "tailscale") - } - if cfg.TailscaleHostname != "my-game" { - t.Errorf("TailscaleHostname = %q, want %q", cfg.TailscaleHostname, "my-game") - } - if cfg.TailscaleTags != "tag:gameplane,tag:game" { - t.Errorf("TailscaleTags = %q, want %q", cfg.TailscaleTags, "tag:gameplane,tag:game") - } -} - -func TestTailscaleForwardLimits(t *testing.T) { - env := map[string]string{"GAMESERVER_NAME": "game", "GAMESERVER_NAMESPACE": "games", "TUNNEL_TYPE": "tailscale", "TAILSCALE_HOSTNAME": "game", "BACKING_SERVICE_DNS": "game.games.svc", "BACKING_SERVICE_PORTS": "echo:9000:udp"} - for _, tc := range []struct { - sessions, queue string - ok bool - }{{"", "", true}, {"256", "1", true}, {"32", "16", true}, {"0", "1", false}, {"257", "1", false}, {"1", "17", false}, {"256", "4", false}, {"bad", "1", false}} { - env["TAILSCALE_MAX_SESSIONS"], env["TAILSCALE_UDP_QUEUE"] = tc.sessions, tc.queue - cfg, err := loadConfig(stubEnv(env)) - if (err == nil) != tc.ok { - t.Fatalf("limits %q/%q: %v", tc.sessions, tc.queue, err) - } - if tc.sessions == "" && cfg.ForwardLimits != defaultForwardLimits { - t.Fatalf("changed default: %+v", cfg.ForwardLimits) - } - } -} - -func TestLoadConfigPlayit(t *testing.T) { - cfg, err := loadConfig(stubEnv(map[string]string{ - "GAMESERVER_NAME": "my-server", - "GAMESERVER_NAMESPACE": "games", - "TUNNEL_TYPE": "playit", - "PLAYIT_TUNNEL_NAME": "my-tunnel", - "BACKING_SERVICE_DNS": "my-server.games.svc", - "BACKING_SERVICE_PORTS": "game:25565", - })) - if err != nil { - t.Fatalf("loadConfig() error = %v", err) - } - if cfg.TunnelType != "playit" { - t.Errorf("TunnelType = %q, want %q", cfg.TunnelType, "playit") - } - if cfg.PlayitTunnelName != "my-tunnel" { - t.Errorf("PlayitTunnelName = %q, want %q", cfg.PlayitTunnelName, "my-tunnel") - } -} - -func TestLoadConfigMissingRequired(t *testing.T) { - tests := []struct { - name string - env map[string]string - }{ - { - name: "missing GAMESERVER_NAME", - env: map[string]string{ - "GAMESERVER_NAMESPACE": "games", - "TUNNEL_TYPE": "frp", - }, - }, - { - name: "missing GAMESERVER_NAMESPACE", - env: map[string]string{ - "GAMESERVER_NAME": "my-server", - "TUNNEL_TYPE": "frp", - }, - }, - { - name: "missing TUNNEL_TYPE", - env: map[string]string{ - "GAMESERVER_NAME": "my-server", - "GAMESERVER_NAMESPACE": "games", - }, - }, - { - name: "missing BACKING_SERVICE_DNS", - env: map[string]string{ - "GAMESERVER_NAME": "my-server", - "GAMESERVER_NAMESPACE": "games", - "TUNNEL_TYPE": "frp", - }, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - _, err := loadConfig(stubEnv(tt.env)) - if err == nil { - t.Error("expected error, got nil") - } - }) - } -} - -func TestLoadConfigFrpMissingAddress(t *testing.T) { - _, err := loadConfig(stubEnv(map[string]string{ - "GAMESERVER_NAME": "my-server", - "GAMESERVER_NAMESPACE": "games", - "TUNNEL_TYPE": "frp", - "BACKING_SERVICE_DNS": "my-server.games.svc", - })) - if err == nil { - t.Error("expected error for missing FRP_SERVER_ADDR") - } -} - -func TestLoadConfigFrpMissingPortMapping(t *testing.T) { - _, err := loadConfig(stubEnv(map[string]string{ - "GAMESERVER_NAME": "my-server", - "GAMESERVER_NAMESPACE": "games", - "TUNNEL_TYPE": "frp", - "FRP_SERVER_ADDR": "frp.example.com", - "BACKING_SERVICE_DNS": "my-server.games.svc", - })) - if err == nil { - t.Error("expected error for missing BACKING_SERVICE_PORT") - } -} - -func TestLoadConfigInvalidFrpPort(t *testing.T) { - tests := []struct { - name string - portVal string - wantErr bool - }{ - {"valid", "7000", false}, - {"out of range", "70000", true}, - {"non-numeric", "abc", true}, - {"zero", "0", true}, - {"negative", "-1", true}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - _, err := loadConfig(stubEnv(map[string]string{ - "GAMESERVER_NAME": "my-server", - "GAMESERVER_NAMESPACE": "games", - "TUNNEL_TYPE": "frp", - "FRP_SERVER_ADDR": "frp.example.com", - "FRP_SERVER_PORT": tt.portVal, - "BACKING_SERVICE_DNS": "my-server.games.svc", - "BACKING_SERVICE_PORT": "game:25565", - })) - if (err != nil) != tt.wantErr { - t.Errorf("error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} - -func TestLoadConfigTailscaleMissingHostname(t *testing.T) { - _, err := loadConfig(stubEnv(map[string]string{ - "GAMESERVER_NAME": "my-server", - "GAMESERVER_NAMESPACE": "games", - "TUNNEL_TYPE": "tailscale", - "BACKING_SERVICE_DNS": "my-server.games.svc", - "BACKING_SERVICE_PORTS": "game:25565", - })) - if err == nil || !strings.Contains(err.Error(), "TAILSCALE_HOSTNAME") { - t.Errorf("loadConfig() error = %v, want it to mention TAILSCALE_HOSTNAME", err) - } -} - -func TestLoadConfigTailscaleMissingBackingServicePorts(t *testing.T) { - _, err := loadConfig(stubEnv(map[string]string{ - "GAMESERVER_NAME": "my-server", - "GAMESERVER_NAMESPACE": "games", - "TUNNEL_TYPE": "tailscale", - "TAILSCALE_HOSTNAME": "my-game", - "BACKING_SERVICE_DNS": "my-server.games.svc", - })) - if err == nil || !strings.Contains(err.Error(), "BACKING_SERVICE_PORTS") { - t.Errorf("loadConfig() error = %v, want it to mention BACKING_SERVICE_PORTS", err) - } -} - -func TestLoadConfigPlayitMissingTunnelName(t *testing.T) { - _, err := loadConfig(stubEnv(map[string]string{ - "GAMESERVER_NAME": "my-server", - "GAMESERVER_NAMESPACE": "games", - "TUNNEL_TYPE": "playit", - "BACKING_SERVICE_DNS": "my-server.games.svc", - "BACKING_SERVICE_PORTS": "game:25565", - })) - if err == nil || !strings.Contains(err.Error(), "PLAYIT_TUNNEL_NAME") { - t.Errorf("loadConfig() error = %v, want it to mention PLAYIT_TUNNEL_NAME", err) - } -} - -func TestLoadConfigPlayitMissingBackingServicePorts(t *testing.T) { - _, err := loadConfig(stubEnv(map[string]string{ - "GAMESERVER_NAME": "my-server", - "GAMESERVER_NAMESPACE": "games", - "TUNNEL_TYPE": "playit", - "PLAYIT_TUNNEL_NAME": "my-tunnel", - "BACKING_SERVICE_DNS": "my-server.games.svc", - })) - if err == nil || !strings.Contains(err.Error(), "BACKING_SERVICE_PORTS") { - t.Errorf("loadConfig() error = %v, want it to mention BACKING_SERVICE_PORTS", err) - } -} - -func TestLoadConfigUnsupportedTunnelType(t *testing.T) { - _, err := loadConfig(stubEnv(map[string]string{ - "GAMESERVER_NAME": "my-server", - "GAMESERVER_NAMESPACE": "games", - "TUNNEL_TYPE": "invalid-provider", - "BACKING_SERVICE_DNS": "my-server.games.svc", - })) - if err == nil { - t.Error("expected error for unsupported TUNNEL_TYPE") - } -} - -// ----------------------------------------------------------------------- -// renderConfig tests -// ----------------------------------------------------------------------- - -func TestRenderFrpConfig(t *testing.T) { - cfg := Config{ - GameServerName: "my-server", - GameServerNamespace: "games", - TunnelType: "frp", - FrpServerAddr: "frp.example.com", - FrpServerPort: 7000, - BackingServiceDNS: "my-server.games.svc", - BackingServicePort: "game:25565:30000:tcp", - } - - cfg.GameServerUID = "fixture-uid" - path, err := renderFrpConfig(cfg, "test-token") - if err != nil { - t.Fatalf("renderFrpConfig() error = %v", err) - } - defer os.Remove(path) - - data, err := os.ReadFile(path) - if err != nil { - t.Fatalf("read config file: %v", err) - } - - content := string(data) - if !strings.Contains(content, "serverAddr = \"frp.example.com\"") { - t.Errorf("config missing serverAddr") - } - if !strings.Contains(content, "serverPort = 7000") { - t.Errorf("config missing serverPort") - } - if !strings.Contains(content, "auth.token = \"test-token\"") { - t.Errorf("config missing auth token") - } - if !strings.Contains(content, "localIP = \"my-server.games.svc\"") { - t.Errorf("config missing backing service DNS") - } - if !strings.Contains(content, "type = \"tcp\"") { - t.Errorf("config missing proxy type") - } - if !strings.Contains(content, "localPort = 25565") { - t.Errorf("config missing local (Service) port") - } - if !strings.Contains(content, "remotePort = 30000") { - t.Errorf("config missing remote (public) port") - } -} - -func TestRenderFrpConfigInvalidPortMapping(t *testing.T) { - cfg := Config{ - FrpServerAddr: "frp.example.com", - FrpServerPort: 7000, - BackingServiceDNS: "my-server.games.svc", - BackingServicePort: "not-a-valid-mapping", - } - - cfg.GameServerUID = "fixture-uid" - _, err := renderFrpConfig(cfg, "token") - if err == nil || !strings.Contains(err.Error(), "invalid port mapping") { - t.Errorf("renderFrpConfig() error = %v, want invalid port mapping error", err) - } -} - -func TestRenderFrpConfigMultiplePorts(t *testing.T) { - cfg := Config{ - FrpServerAddr: "frp.example.com", - FrpServerPort: 7000, - BackingServiceDNS: "my-server.games.svc", - BackingServicePort: "java:25565:25565:tcp,bedrock:19133:19133:udp", - } - - cfg.GameServerUID = "fixture-uid" - path, err := renderFrpConfig(cfg, "token") - if err != nil { - t.Fatalf("renderFrpConfig() error = %v", err) - } - defer os.Remove(path) - - data, err := os.ReadFile(path) - if err != nil { - t.Fatalf("read config file: %v", err) - } - - content := string(data) - if !strings.Contains(content, "name = \"java\"") { - t.Errorf("config missing java port mapping") - } - if !strings.Contains(content, "name = \"bedrock\"") { - t.Errorf("config missing bedrock port mapping") - } -} - -func TestRenderFrpConfigUDPProtocol(t *testing.T) { - // F-052: a UDP-advertised port (e.g. Factorio 34197/UDP) must render - // type = "udp", not the old hard-coded "tcp", and localPort must be the - // backing Service's own port even when it differs from the public - // remotePort the user chose. - cfg := Config{ - FrpServerAddr: "frp.example.com", - FrpServerPort: 7000, - BackingServiceDNS: "factorio.games.svc", - BackingServicePort: "game:34197:30000:udp", - } - - cfg.GameServerUID = "fixture-uid" - path, err := renderFrpConfig(cfg, "token") - if err != nil { - t.Fatalf("renderFrpConfig() error = %v", err) - } - defer os.Remove(path) - - data, err := os.ReadFile(path) - if err != nil { - t.Fatalf("read config file: %v", err) - } - - content := string(data) - if !strings.Contains(content, "type = \"udp\"") { - t.Errorf("config missing udp proxy type, got:\n%s", content) - } - if !strings.Contains(content, "localPort = 34197") { - t.Errorf("config missing local (Service) port 34197, got:\n%s", content) - } - if !strings.Contains(content, "remotePort = 30000") { - t.Errorf("config missing remote (public) port 30000, got:\n%s", content) - } -} - -func TestRenderFrpConfigInvalidProtocol(t *testing.T) { - cfg := Config{ - FrpServerAddr: "frp.example.com", - FrpServerPort: 7000, - BackingServiceDNS: "my-server.games.svc", - BackingServicePort: "game:25565:25565:sctp", - } - - cfg.GameServerUID = "fixture-uid" - _, err := renderFrpConfig(cfg, "token") - if err == nil || !strings.Contains(err.Error(), "invalid port mapping protocol") { - t.Errorf("renderFrpConfig() error = %v, want invalid port mapping protocol error", err) - } -} - -func TestParseTailscaleTags(t *testing.T) { - tests := []struct { - name string - tagsStr string - want []string - wantErr bool - }{ - {name: "whitespace and blank entries trimmed and dropped", tagsStr: " tag:a , tag:b,, ", want: []string{"tag:a", "tag:b"}}, - {name: "single tag", tagsStr: "tag:gameplane", want: []string{"tag:gameplane"}}, - {name: "bare name gets tag: prefix", tagsStr: "eng, tag:ops-2", want: []string{"tag:eng", "tag:ops-2"}}, - {name: "empty string", tagsStr: "", want: nil}, - {name: "only commas and whitespace", tagsStr: " , ,, ", want: nil}, - {name: "empty name", tagsStr: "tag:", wantErr: true}, - {name: "name starts with digit", tagsStr: "tag:1abc", wantErr: true}, - {name: "inner space", tagsStr: "tag:a b", wantErr: true}, - {name: "other prefix", tagsStr: "user:bob", wantErr: true}, - {name: "flag-like value", tagsStr: "tag:a,--reset", wantErr: true}, - {name: "shell metacharacter", tagsStr: "tag:a;rm", wantErr: true}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got, err := parseTailscaleTags(tt.tagsStr) - if (err != nil) != tt.wantErr { - t.Fatalf("parseTailscaleTags(%q) error = %v, wantErr %v", tt.tagsStr, err, tt.wantErr) - } - if !equalArgs(got, tt.want) || (got == nil) != (tt.want == nil) { - t.Errorf("parseTailscaleTags(%q) = %#v, want %#v", tt.tagsStr, got, tt.want) - } - }) - } -} - -// TestParseTailscaleTagsDeduplicate asserts that duplicate tags are skipped. -func TestParseTailscaleTagsDeduplicate(t *testing.T) { - tags, err := parseTailscaleTags("a,tag:a,b") - if err != nil { - t.Fatalf("parseTailscaleTags() error = %v", err) - } - if len(tags) != 2 || tags[0] != "tag:a" || tags[1] != "tag:b" { - t.Errorf("parseTailscaleTags(\"a,tag:a,b\") = %v, want [tag:a tag:b]", tags) - } -} - -func TestRenderFrpConfigServerAddrEscaped(t *testing.T) { - cfg := Config{ - FrpServerAddr: `server.example.com"` + "\n" + `extra = "value`, - FrpServerPort: 7000, - BackingServiceDNS: "my-server.games.svc", - BackingServicePort: "game:25565:30000:tcp", - } - cfg.GameServerUID = "fixture-uid" - path, err := renderFrpConfig(cfg, "test-token") - if err != nil { - t.Fatalf("renderFrpConfig() error = %v", err) - } - defer os.Remove(path) - - data, err := os.ReadFile(path) - if err != nil { - t.Fatalf("read config: %v", err) - } - - config := string(data) - // escapeTomlString backslash-escapes both the embedded quote and the - // embedded newline, so the whole malicious value collapses onto a - // single serverAddr line rather than the newline terminating that - // line and "extra" starting a real new TOML key. Assert the exact - // rendered line rather than a substring shape, since the escaped - // quote is not immediately followed by the line's closing quote. - wantLine := `serverAddr = "server.example.com\"\nextra = \"value"` - foundServerAddr := false - for _, line := range strings.Split(config, "\n") { - if strings.HasPrefix(line, "serverAddr = ") { - foundServerAddr = true - if line != wantLine { - t.Errorf("serverAddr line = %q, want %q", line, wantLine) - } - } - // A real (unescaped) "extra = ..." line would mean the newline - // broke out of the serverAddr string and injected a new key. - if strings.TrimSpace(line) == `extra = "value` { - t.Errorf("TOML injection detected: found injected line %q in:\n%s", line, config) - } - } - if !foundServerAddr { - t.Errorf("serverAddr line not found in:\n%s", config) - } - // Verify the file parses as valid TOML (basic check: no parse error) - // We'd use encoding/toml but we want to avoid external imports for simple checks - if !strings.Contains(config, "auth.token") { - t.Errorf("rendered TOML missing auth.token") - } -} - -func TestRenderFrpConfigProxyNameEscaped(t *testing.T) { - cfg := Config{ - FrpServerAddr: "frp.example.com", - FrpServerPort: 7000, - BackingServiceDNS: "my-server.games.svc", - BackingServicePort: `bad"name:25565:30000:tcp`, - } - cfg.GameServerUID = "fixture-uid" - path, err := renderFrpConfig(cfg, "test-token") - if err != nil { - t.Fatalf("renderFrpConfig() error = %v", err) - } - defer os.Remove(path) - - data, err := os.ReadFile(path) - if err != nil { - t.Fatalf("read config: %v", err) - } - - config := string(data) - // Verify the proxy name is properly escaped - if !strings.Contains(config, `name = "bad\"name"`) { - t.Errorf("proxy name not properly escaped, got:\n%s", config) - } - // Verify no TOML injection - if strings.Count(config, "[[proxies]]") != 1 { - t.Errorf("TOML injection detected in proxy name escaping, got:\n%s", config) - } -} - -// TestRenderPlayitConfig covers what renderPlayitConfig actually does: write -// the raw secret to a file for playitd's --secret-path flag. playitd has no -// local config file for tunnel name or port forwards (see the function's -// doc comment), so there is nothing else to assert here. -func TestRenderPlayitConfig(t *testing.T) { - path, err := renderPlayitConfig("test-secret-key") - if err != nil { - t.Fatalf("renderPlayitConfig() error = %v", err) - } - defer os.Remove(path) - - data, err := os.ReadFile(path) - if err != nil { - t.Fatalf("read secret file: %v", err) - } - - if string(data) != "test-secret-key" { - t.Errorf("playit secret file content = %q, want %q", string(data), "test-secret-key") - } -} - -func TestRenderConfigDispatchesByType(t *testing.T) { - tests := []struct { - tunnelType string - cfg Config - }{ - { - "frp", - Config{ - TunnelType: "frp", - GameServerUID: "fixture-uid", - FrpServerAddr: "frp.example.com", - BackingServiceDNS: "svc.svc", - BackingServicePort: "game:25565:30000:tcp", - }, - }, - { - "playit", - Config{ - TunnelType: "playit", - PlayitTunnelName: "my-tunnel", - BackingServicePorts: "game:25565", - }, - }, - } - - for _, tt := range tests { - t.Run(tt.tunnelType, func(t *testing.T) { - path, err := renderConfig(tt.cfg, "cred") - if err != nil { - t.Errorf("renderConfig() error = %v", err) - return - } - defer os.Remove(path) - if path == "" { - t.Error("renderConfig() returned empty path") - } - }) - } -} - -func TestRenderConfigUnknownType(t *testing.T) { - _, err := renderConfig(Config{TunnelType: "bogus"}, "cred") - if err == nil || !strings.Contains(err.Error(), "unknown tunnel type") { - t.Errorf("renderConfig() error = %v, want unknown tunnel type error", err) - } -} - -// ----------------------------------------------------------------------- -// readCredentials tests -// ----------------------------------------------------------------------- - -// withCredentialsDir repoints the package-level credentialsDir var at dir -// for the duration of the test, restoring the original afterward. This is -// what lets readCredentials be exercised end-to-end without touching the -// real /etc/gameplane/tunnel-auth mount. -func withCredentialsDir(t *testing.T, dir string) { - t.Helper() - orig := credentialsDir - credentialsDir = dir - t.Cleanup(func() { credentialsDir = orig }) -} - -func TestReadCredentialsSuccess(t *testing.T) { - tests := []struct { - tunnelType string - keyName string - }{ - {"frp", "token"}, - {"tailscale", "authKey"}, - {"playit", "secretKey"}, - } - - for _, tt := range tests { - t.Run(tt.tunnelType, func(t *testing.T) { - tmpdir := t.TempDir() - withCredentialsDir(t, tmpdir) - - credPath := filepath.Join(tmpdir, tt.keyName) - // Leading/trailing whitespace should be trimmed, as it commonly - // is when a Secret value ends in a trailing newline. - if err := os.WriteFile(credPath, []byte(" test-value\n"), 0o600); err != nil { - t.Fatalf("write test credential: %v", err) - } - - got, err := readCredentials(Config{TunnelType: tt.tunnelType}) - if err != nil { - t.Fatalf("readCredentials() error = %v", err) - } - if got != "test-value" { - t.Errorf("readCredentials() = %q, want %q", got, "test-value") - } - }) - } -} - -func TestReadCredentialsMissingFile(t *testing.T) { - tmpdir := t.TempDir() // empty; no credential files written - - withCredentialsDir(t, tmpdir) - - _, err := readCredentials(Config{TunnelType: "tailscale"}) - if err == nil || !strings.Contains(err.Error(), "read credential") { - t.Errorf("readCredentials() error = %v, want credential read error", err) - } -} - -func TestReadCredentialsKeyNames(t *testing.T) { - tests := []struct { - tunnelType string - expectedKey string - }{ - {"frp", "token"}, - {"tailscale", "authKey"}, - {"playit", "secretKey"}, - } - - tmpdir := t.TempDir() // empty; every lookup below is expected to fail - withCredentialsDir(t, tmpdir) - - for _, tt := range tests { - t.Run(tt.tunnelType, func(t *testing.T) { - _, err := readCredentials(Config{TunnelType: tt.tunnelType}) - if err == nil { - t.Fatal("expected error for missing credential file") - } - if !strings.Contains(err.Error(), tt.expectedKey) { - t.Errorf("error should mention key name %q, got %v", tt.expectedKey, err) - } - }) - } -} - -func TestReadCredentialsUnknownTunnelType(t *testing.T) { - _, err := readCredentials(Config{TunnelType: "bogus"}) - if err == nil || !strings.Contains(err.Error(), "unknown tunnel type") { - t.Errorf("readCredentials() error = %v, want unknown tunnel type error", err) - } -} - -// ----------------------------------------------------------------------- -// escapeTomlString tests -// ----------------------------------------------------------------------- - -func TestEscapeTomlString(t *testing.T) { - tests := []struct { - input string - want string - }{ - {"simple", "simple"}, - {"with\"quote", "with\\\"quote"}, - {"with\\slash", "with\\\\slash"}, - {"with\nnewline", "with\\nnewline"}, - {"with\ttab", "with\\ttab"}, - {"combined\\\"both", "combined\\\\\\\"both"}, - } - - for _, tt := range tests { - t.Run(tt.input, func(t *testing.T) { - got := escapeTomlString(tt.input) - if got != tt.want { - t.Errorf("escapeTomlString(%q) = %q, want %q", tt.input, got, tt.want) - } - }) - } -} - -// ----------------------------------------------------------------------- -// buildCommand tests -// ----------------------------------------------------------------------- - -func TestBuildCommandFrp(t *testing.T) { - cfg := Config{TunnelType: "frp"} - cmd := buildCommand(context.Background(), cfg) - if cmd == nil { - t.Fatal("buildCommand() returned nil") - } - if cmd.Path != "/usr/local/bin/frpc" { - t.Errorf("Path = %q, want %q", cmd.Path, "/usr/local/bin/frpc") - } - // frpc's real config flag, confirmed against fatedier/frp's - // cmd/frpc/sub/root.go, is "-c"/"--config". - wantArgs := []string{"/usr/local/bin/frpc", "-c", frpConfigPath} - if !equalArgs(cmd.Args, wantArgs) { - t.Errorf("Args = %v, want %v", cmd.Args, wantArgs) - } -} - -func TestBuildCommandPlayit(t *testing.T) { - cfg := Config{TunnelType: "playit"} - cmd := buildCommand(context.Background(), cfg) - if cmd == nil { - t.Fatal("buildCommand() returned nil") - } - // playitd (not playit-cli) takes --secret-path, --socket-path and - // --platform-docker, confirmed against playit-cloud/playit-agent's - // playitd.rs (v1.0.10) and its official Dockerfile/entrypoint.sh. - // --socket-path points the IPC socket the address reporter polls at a - // path the non-root image can create (F-174). - wantArgs := []string{"/usr/local/bin/playitd", "--secret-path", playitAuthPath, "--socket-path", playitSocketPath, "--platform-docker"} - if !equalArgs(cmd.Args, wantArgs) { - t.Errorf("Args = %v, want %v", cmd.Args, wantArgs) - } -} - -func TestBuildCommandUnknownType(t *testing.T) { - cfg := Config{TunnelType: "bogus"} - cmd := buildCommand(context.Background(), cfg) - if cmd != nil { - t.Errorf("buildCommand() for unknown type = %v, want nil", cmd) - } -} - -func equalArgs(got, want []string) bool { - if len(got) != len(want) { - return false - } - for i := range got { - if got[i] != want[i] { - return false - } - } - return true -} - -// ----------------------------------------------------------------------- -// exponentialBackoff tests -// ----------------------------------------------------------------------- - -func TestExponentialBackoff(t *testing.T) { - b := &exponentialBackoff{} - - // First retry: 1s (base 1). - d1 := b.next() - if d1 < 900*time.Millisecond || d1 > 1100*time.Millisecond { - t.Errorf("first backoff = %v, want ~1s", d1) - } - - // Second retry: ~2s (base 2). - d2 := b.next() - if d2 < 1800*time.Millisecond || d2 > 2200*time.Millisecond { - t.Errorf("second backoff = %v, want ~2s", d2) - } - - // Backoff should be increasing. - if d2 <= d1 { - t.Errorf("second backoff %v should be > first %v", d2, d1) - } -} - -func TestExponentialBackoffCap(t *testing.T) { - b := &exponentialBackoff{} - - // Advance to near the cap: 256 = 2^8, next would be 512. - for i := 0; i < 10; i++ { - b.next() - } - - // Check that we're capped at 5 minutes. - d := b.next() - if d > 5*time.Minute+200*time.Millisecond { - t.Errorf("backoff %v exceeds 5-minute cap", d) - } -} - -func TestExponentialBackoffNeverZeroAcrossLifetimeRetries(t *testing.T) { - // F-172: uncapped, retry 64 overflowed the shift and returned 0s, - // putting the supervisor into a busy restart loop. Call next() 70 - // times (past that point) and confirm every delay stays in [1s, 5m]. - b := &exponentialBackoff{} - for i := 1; i <= 70; i++ { - d := b.next() - if d < time.Second { - t.Fatalf("retry %d: backoff = %v, want >= 1s (want never 0)", i, d) - } - if d > 5*time.Minute { - t.Fatalf("retry %d: backoff = %v, want <= 5m", i, d) - } - } - // From retry 64 on (the old overflow point) the delay must have - // settled at the 5-minute cap, not reset or wrapped. - if d := b.next(); d != 5*time.Minute { - t.Fatalf("retry 71: backoff = %v, want exactly 5m (capped)", d) - } -} - -// ----------------------------------------------------------------------- -// isUnrecoverable tests -// ----------------------------------------------------------------------- - -func TestIsUnrecoverable(t *testing.T) { - tests := []struct { - name string - err error - want bool - }{ - {"nil", nil, false}, - {"permission denied", errors.New("permission denied"), true}, - {"exit 126", errors.New("exit status 126"), true}, - {"exit 127", errors.New("exit status 127"), true}, - {"network error", errors.New("dial: connection refused"), false}, - {"generic", errors.New("something went wrong"), false}, - } - - cfg := Config{} - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got := isUnrecoverable(cfg, tt.err) - if got != tt.want { - t.Errorf("isUnrecoverable(%v) = %v, want %v", tt.err, got, tt.want) - } - }) - } -} - -// ----------------------------------------------------------------------- -// run/supervision tests -// ----------------------------------------------------------------------- - -func TestRunContextCancellation(t *testing.T) { - tmpdir := t.TempDir() - withCredentialsDir(t, tmpdir) - if err := os.WriteFile(filepath.Join(tmpdir, "token"), []byte("test-token"), 0o600); err != nil { - t.Fatalf("write test credential: %v", err) - } - - cfg := Config{ - GameServerName: "test", - GameServerNamespace: "games", - TunnelType: "frp", - FrpServerAddr: "localhost", - FrpServerPort: 7000, - BackingServiceDNS: "test.games.svc", - BackingServicePort: "game:25565:30000:tcp", - } - - ctx, cancel := context.WithCancel(context.Background()) - cancel() // Cancel immediately - - // With a cancelled context, run should return nil (clean shutdown) even - // though it never gets far enough to actually exec anything: the loop's - // first ctx.Done() check fires before buildCommand is ever called. - cfg.GameServerUID = "fixture-uid" - err := run(ctx, cfg) - if err != nil { - t.Errorf("run with cancelled context = %v, want nil", err) - } -} - -// TestRunTransientFailureBacksOffThenCancels drives run() past its initial -// setup and into the supervision loop for real: buildCommand's relay binary -// (/usr/local/bin/frpc) does not exist on the machine running this test (no -// relay binaries are installed outside the shipped container image), so -// runCommand's cmd.Start() deterministically fails with "no such file or -// directory" -- a real, safe, side-effect-free exec attempt, not a mock. -// That's treated as a transient failure (it doesn't match isUnrecoverable's -// permission-denied/exit-126/127 patterns), so run() computes a backoff -// delay (1s) and sleeps; the short context timeout here fires well before -// that delay elapses, exercising the backoff select's ctx.Done() case. -func TestRunTransientFailureBacksOffThenCancels(t *testing.T) { - tmpdir := t.TempDir() - withCredentialsDir(t, tmpdir) - if err := os.WriteFile(filepath.Join(tmpdir, "token"), []byte("test-token"), 0o600); err != nil { - t.Fatalf("write test credential: %v", err) - } - - cfg := Config{ - GameServerName: "test", - GameServerNamespace: "games", - TunnelType: "frp", - FrpServerAddr: "localhost", - FrpServerPort: 7000, - BackingServiceDNS: "test.games.svc", - BackingServicePort: "game:25565:30000:tcp", - } - - ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) - defer cancel() - - cfg.GameServerUID = "fixture-uid" - err := run(ctx, cfg) - if err != nil { - t.Errorf("run() = %v, want nil (clean shutdown once the context times out)", err) - } -} - -func TestRunRenderConfigFailure(t *testing.T) { - tmpdir := t.TempDir() - withCredentialsDir(t, tmpdir) - if err := os.WriteFile(filepath.Join(tmpdir, "token"), []byte("test-token"), 0o600); err != nil { - t.Fatalf("write test credential: %v", err) - } - - cfg := Config{ - GameServerName: "test", - GameServerNamespace: "games", - TunnelType: "frp", - FrpServerAddr: "localhost", - FrpServerPort: 7000, - BackingServiceDNS: "test.games.svc", - // Not a "name:port" pair, so renderFrpConfig fails before run() ever - // reaches the supervision loop. - BackingServicePort: "not-a-valid-mapping", - } - - cfg.GameServerUID = "fixture-uid" - err := run(context.Background(), cfg) - if err == nil || !strings.Contains(err.Error(), "render config") { - t.Errorf("run() error = %v, want a render-config error", err) - } -} - -func TestRunReadCredentialsFailure(t *testing.T) { - withCredentialsDir(t, t.TempDir()) // empty dir; no credential file present - - cfg := Config{ - GameServerName: "test", - GameServerNamespace: "games", - TunnelType: "tailscale", - TailscaleHostname: "my-game", - BackingServiceDNS: "test.games.svc", - BackingServicePorts: "game:25565", - } - - cfg.GameServerUID = "fixture-uid" - err := run(context.Background(), cfg) - if err == nil || !strings.Contains(err.Error(), "read credentials") { - t.Errorf("run() error = %v, want a read-credentials error", err) - } -} - -func TestRunPlayitConfigDispatch(t *testing.T) { - tmpdir := t.TempDir() - withCredentialsDir(t, tmpdir) - if err := os.WriteFile(filepath.Join(tmpdir, "secretKey"), []byte("test-secret"), 0o600); err != nil { - t.Fatalf("write test credential: %v", err) - } - - cfg := Config{ - GameServerName: "test", - GameServerNamespace: "games", - TunnelType: "playit", - PlayitTunnelName: "my-tunnel", - BackingServiceDNS: "test.games.svc", - BackingServicePorts: "game:25565", - } - - // Cancel up front: run() should still walk readCredentials -> renderConfig - // for the playit branch before observing the cancellation, and return - // cleanly. - ctx, cancel := context.WithCancel(context.Background()) - cancel() - - cfg.GameServerUID = "fixture-uid" - err := run(ctx, cfg) - if err != nil { - t.Errorf("run() for playit with cancelled context = %v, want nil", err) - } -} - -// ----------------------------------------------------------------------- -// runCommand tests -// -// These use real, standard Linux utilities (true/false/sleep) rather than -// the provider relay binaries: runCommand itself is provider-agnostic, and -// exercising it directly with well-known, always-present system binaries -// lets these assert real process-exit and cancellation behavior without -// touching any gosec-relevant exec call in main.go (this file is exempt -// from gosec per .golangci.yml, and none of these paths are variable -// binaries the production code would ever pass through). -// ----------------------------------------------------------------------- - -func TestRunCommandSuccess(t *testing.T) { - cmd := exec.CommandContext(context.Background(), "true") - if err := runCommand(context.Background(), cmd); err != nil { - t.Errorf("runCommand() = %v, want nil", err) - } -} - -func TestRunCommandNonZeroExit(t *testing.T) { - cmd := exec.CommandContext(context.Background(), "false") - err := runCommand(context.Background(), cmd) - if err == nil { - t.Error("runCommand() = nil, want a non-zero-exit error") - } -} - -func TestRunCommandStartError(t *testing.T) { - cmd := exec.CommandContext(context.Background(), "/nonexistent/binary/gameplane-tunnel-test") - err := runCommand(context.Background(), cmd) - if err == nil || !strings.Contains(err.Error(), "start relay") { - t.Errorf("runCommand() error = %v, want a start-relay error", err) - } -} - -func TestRunCommandContextCancellation(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - cmd := exec.CommandContext(ctx, "sleep", "5") - - go func() { - time.Sleep(50 * time.Millisecond) - cancel() - }() - - start := time.Now() - err := runCommand(ctx, cmd) - elapsed := time.Since(start) - - if !errors.Is(err, context.Canceled) { - t.Errorf("runCommand() error = %v, want context.Canceled", err) - } - // cmd.Cancel sends SIGTERM (see runCommand), which "sleep" honors - // immediately, so this should return well before the 5s sleep would - // have finished on its own and well before the 10s WaitDelay fallback. - if elapsed > 4*time.Second { - t.Errorf("runCommand() took %v after cancellation, want well under the sleep's 5s duration", elapsed) - } -} diff --git a/tunnel/playit_reporter.go b/tunnel/playit_reporter.go deleted file mode 100644 index 1a37d4e1e..000000000 --- a/tunnel/playit_reporter.go +++ /dev/null @@ -1,525 +0,0 @@ -package main - -// Playit address discovery (F-174, OD-026 option a). -// -// playit.gg assigns a tunnel's public address server-side, so -- unlike frp -// and Tailscale, whose addresses the operator computes from the spec -- the -// supervisor has to learn it at runtime and report it back. This file polls -// playitd's local IPC control socket for the assigned addresses and patches -// them into the GameServer's status.tunnelEndpoints; the operator validates -// those entries (validatePlayitEndpoints in -// operator/internal/controller/gameserver_status.go) and merges them into -// status.endpoints, exactly like the endpoints it computes for frp/tailscale. -// -// IPC protocol, established from playit-cloud/playit-agent at the pinned -// v1.0.10 (packages/playit-ipc/src/ipc.rs + model.rs, and -// packages/playitd/src/ipc_server.rs): -// -// - Transport: a Unix-domain stream socket at the path given by playitd's -// --socket-path flag (default /run/playit/playitd.sock on Linux, which a -// non-root distroless container cannot create -- hence the explicit -// /tmp path below). playitd chmods it 0660 owned by its own uid, so this -// supervisor (same uid 65532) can connect. -// - Framing: newline-delimited JSON (tokio LinesCodec), one object per line. -// - On connect the server immediately writes a hello frame: -// {"message_kind":"hello","data":{"protocol":{"ipc_version":2,"capabilities":[...]}}} -// - Client request: {"ipc_version":2,"request_id":N,"request":{"type":"get_state"}} -// - Server response: -// {"message_kind":"response","data":{"ipc_version":2,"request_id":N, -// "response":{"type":"state","data":}}} -// where AgentLifecycle is {"state":"starting"} (and other unit states) or -// {"state":"running","data":{"tunnels":[{"display_address":"host:port", -// "destination":"ip:port","is_disabled":false,"disabled_reason":null}],...}}. -// An error is {"type":"error","data":{"code":...,"message":...}}. -// - Event frames ("message_kind":"event") are only sent after a subscribe -// request, which this client never makes; they are skipped defensively. - -import ( - "bufio" - "bytes" - "context" - "crypto/tls" - "crypto/x509" - "encoding/json" - "errors" - "fmt" - "io" - "log" - "net" - "net/http" - "net/url" - "os" - "path/filepath" - "reflect" - "sort" - "strconv" - "strings" - "time" -) - -const ( - // playitSocketPath is the IPC socket playitd is told to listen on via - // --socket-path. A compile-time constant for the same G204 reason as - // the other fixed paths in main.go. - playitSocketPath = "/tmp/gameplane-tunnel-playitd.sock" - - // playitIPCVersion is playit-ipc's IPC_VERSION at v1.0.10. A server that - // reports another version is treated as an error rather than guessed at. - playitIPCVersion = 2 - - // playitIOTimeout bounds one whole query (dial, hello, request, reply). - playitIOTimeout = 5 * time.Second - - // playitMaxFrameBytes caps one JSON line; a state frame is a few KiB. - playitMaxFrameBytes = 1 << 20 - - // maxTunnelEndpoints mirrors the CRD's MaxItems=32 on tunnelEndpoints. - maxTunnelEndpoints = 32 - - // serviceAccountMountDir is the standard in-cluster ServiceAccount - // mount (projected token, CA bundle). - serviceAccountMountDir = "/var/run/secrets/kubernetes.io/serviceaccount" - - // kubeAPIServerURL is the in-cluster API server address. The - // kubernetes.default.svc name is in the API server certificate's SANs - // on every conformant cluster. - kubeAPIServerURL = "https://kubernetes.default.svc" -) - -// playitTunnel is one entry of AgentState.tunnels. -type playitTunnel struct { - DisplayAddress string `json:"display_address"` - Destination string `json:"destination"` - IsDisabled bool `json:"is_disabled"` -} - -// playitState is the decoded result of one get_state query. -type playitState struct { - // Phase is the AgentLifecycle state tag ("running", "starting", ...). - Phase string - Tunnels []playitTunnel -} - -// tunnelEndpoint is the JSON shape of a GameServerEndpoint entry in -// status.tunnelEndpoints (operator/api/v1alpha1/gameserver_types.go). -type tunnelEndpoint struct { - Name string `json:"name"` - Host string `json:"host"` - Port int32 `json:"port"` - TunnelProvider string `json:"tunnelProvider,omitempty"` -} - -// queryPlayitState connects to playitd's IPC socket, performs one get_state -// request, and returns the decoded lifecycle. -func queryPlayitState(ctx context.Context, socketPath string) (playitState, error) { - ctx, cancel := context.WithTimeout(ctx, playitIOTimeout) - defer cancel() - - var d net.Dialer - conn, err := d.DialContext(ctx, "unix", socketPath) - if err != nil { - return playitState{}, fmt.Errorf("dial playitd socket %s: %w", socketPath, err) - } - defer func() { _ = conn.Close() }() - if deadline, ok := ctx.Deadline(); ok { - if err := conn.SetDeadline(deadline); err != nil { - return playitState{}, fmt.Errorf("set playitd socket deadline: %w", err) - } - } - - sc := bufio.NewScanner(conn) - sc.Buffer(make([]byte, 0, 64*1024), playitMaxFrameBytes) - - var hello struct { - MessageKind string `json:"message_kind"` - Data struct { - Protocol struct { - IPCVersion int `json:"ipc_version"` - } `json:"protocol"` - } `json:"data"` - } - if err := readFrame(sc, &hello); err != nil { - return playitState{}, fmt.Errorf("read playitd hello: %w", err) - } - if hello.MessageKind != "hello" { - return playitState{}, fmt.Errorf("playitd sent %q frame, want hello", hello.MessageKind) - } - if hello.Data.Protocol.IPCVersion != playitIPCVersion { - return playitState{}, fmt.Errorf("playitd IPC version %d, want %d", hello.Data.Protocol.IPCVersion, playitIPCVersion) - } - - const requestID = 1 - req, err := json.Marshal(map[string]any{ - "ipc_version": playitIPCVersion, - "request_id": requestID, - "request": map[string]string{"type": "get_state"}, - }) - if err != nil { - return playitState{}, fmt.Errorf("encode get_state request: %w", err) - } - if _, err := conn.Write(append(req, '\n')); err != nil { - return playitState{}, fmt.Errorf("write get_state request: %w", err) - } - - for { - var frame struct { - MessageKind string `json:"message_kind"` - Data struct { - IPCVersion int `json:"ipc_version"` - RequestID int `json:"request_id"` - Response struct { - Type string `json:"type"` - Data json.RawMessage `json:"data"` - } `json:"response"` - } `json:"data"` - } - if err := readFrame(sc, &frame); err != nil { - return playitState{}, fmt.Errorf("read get_state response: %w", err) - } - if frame.MessageKind == "event" { - continue - } - if frame.MessageKind != "response" { - return playitState{}, fmt.Errorf("playitd sent unexpected %q frame", frame.MessageKind) - } - if frame.Data.RequestID != requestID { - return playitState{}, fmt.Errorf("playitd response id %d, want %d", frame.Data.RequestID, requestID) - } - return decodePlayitResponse(frame.Data.Response.Type, frame.Data.Response.Data) - } -} - -// readFrame reads one newline-delimited JSON frame into v. -func readFrame(sc *bufio.Scanner, v any) error { - if !sc.Scan() { - if err := sc.Err(); err != nil { - return fmt.Errorf("scan frame: %w", err) - } - return io.ErrUnexpectedEOF - } - if err := json.Unmarshal(sc.Bytes(), v); err != nil { - return fmt.Errorf("decode frame: %w", err) - } - return nil -} - -// decodePlayitResponse turns a ServiceResponse body into a playitState. -func decodePlayitResponse(respType string, data json.RawMessage) (playitState, error) { - switch respType { - case "state": - var lifecycle struct { - State string `json:"state"` - Data struct { - Tunnels []playitTunnel `json:"tunnels"` - } `json:"data"` - } - // Unit lifecycle states carry no "data"; error states carry a - // ServiceError object there, which the anonymous struct above simply - // decodes to zero tunnels. - if err := json.Unmarshal(data, &lifecycle); err != nil { - return playitState{}, fmt.Errorf("decode playitd lifecycle: %w", err) - } - if lifecycle.State == "" { - return playitState{}, errors.New("playitd lifecycle has no state") - } - return playitState{Phase: lifecycle.State, Tunnels: lifecycle.Data.Tunnels}, nil - case "error": - var svcErr struct { - Code string `json:"code"` - Message string `json:"message"` - } - if err := json.Unmarshal(data, &svcErr); err != nil { - return playitState{}, fmt.Errorf("decode playitd error: %w", err) - } - return playitState{}, fmt.Errorf("playitd error %s: %s", svcErr.Code, svcErr.Message) - default: - return playitState{}, fmt.Errorf("playitd sent unexpected %q response to get_state", respType) - } -} - -// backingPort is one "name:port" entry of BACKING_SERVICE_PORTS. -type backingPort struct { - name string - port int32 -} - -// parsePort parses a decimal TCP/UDP port number (1-65535). -func parsePort(s string) (int32, bool) { - v, err := strconv.ParseInt(s, 10, 32) - if err != nil || v < 1 || v > 65535 { - return 0, false - } - return int32(v), true -} - -// parseBackingPorts parses BACKING_SERVICE_PORTS ("name:port,..."). -func parseBackingPorts(spec string) ([]backingPort, error) { - var out []backingPort - for _, entry := range strings.Split(spec, ",") { - entry = strings.TrimSpace(entry) - if entry == "" { - continue - } - name, portStr, ok := strings.Cut(entry, ":") - if !ok || name == "" { - return nil, fmt.Errorf("invalid backing port entry %q", entry) - } - port, ok := parsePort(portStr) - if !ok { - return nil, fmt.Errorf("invalid port in backing port entry %q", entry) - } - out = append(out, backingPort{name: name, port: port}) - } - return out, nil -} - -// destinationPort extracts the local port from a TunnelState.destination. -// playitd formats port tunnels as ":" and HTTPS tunnels as -// " (http: N, https: M)"; the latter yields ok=false. -func destinationPort(dest string) (int32, bool) { - i := strings.LastIndex(dest, ":") - if i < 0 { - return 0, false - } - return parsePort(dest[i+1:]) -} - -// playitEndpoints maps playitd's tunnels onto the template's advertised port -// names. playitd's TunnelState carries no tunnel name, so each tunnel is -// matched to a backing port by its destination (local) port. When exactly -// one port is advertised and exactly one enabled tunnel exists, that pair is -// matched even if the ports differ (the playit dashboard may point it at the -// Service on a different port). A display address without a port (a playit -// hostname served via an SRV record) is reported with the backing port. -// The result is sorted by name for stable comparison. -func playitEndpoints(tunnels []playitTunnel, ports []backingPort) []tunnelEndpoint { - var enabled []playitTunnel - for _, t := range tunnels { - if !t.IsDisabled && t.DisplayAddress != "" { - enabled = append(enabled, t) - } - } - - seen := make(map[string]bool) - var out []tunnelEndpoint - for _, t := range enabled { - var match *backingPort - if p, ok := destinationPort(t.Destination); ok { - for i := range ports { - if ports[i].port == p { - match = &ports[i] - break - } - } - } - if match == nil && len(ports) == 1 && len(enabled) == 1 { - match = &ports[0] - } - if match == nil || seen[match.name] { - continue - } - - host, port := t.DisplayAddress, match.port - if h, p, err := net.SplitHostPort(t.DisplayAddress); err == nil { - n, ok := parsePort(p) - if !ok { - continue - } - host, port = h, n - } - seen[match.name] = true - out = append(out, tunnelEndpoint{ - Name: match.name, - Host: host, - Port: port, - TunnelProvider: "playit", - }) - } - sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name }) - if len(out) > maxTunnelEndpoints { - out = out[:maxTunnelEndpoints] - } - return out -} - -// statusPatcher writes the tunnel endpoints into the GameServer's status. -type statusPatcher interface { - PatchTunnelEndpoints(ctx context.Context, eps []tunnelEndpoint) error -} - -// kubeStatusPatcher patches gameservers/status with the pod's projected -// ServiceAccount token over plain HTTPS, keeping the module stdlib-only. -// The operator's per-GameServer Role (tunnel_rbac.go) allows exactly this -// verb on exactly this object. -type kubeStatusPatcher struct { - baseURL string // kubeAPIServerURL in production; an httptest URL in tests - namespace string - name string - caPath string - tokenPath string - client *http.Client -} - -// newInClusterStatusPatcher builds a patcher from the ServiceAccount mount -// under saDir (serviceAccountMountDir in production). -func newInClusterStatusPatcher(saDir, namespace, name string) (*kubeStatusPatcher, error) { - p := &kubeStatusPatcher{ - baseURL: kubeAPIServerURL, - namespace: namespace, - name: name, - caPath: filepath.Join(saDir, "ca.crt"), - tokenPath: filepath.Join(saDir, "token"), - } - pool, err := p.loadCAPool() - if err != nil { - return nil, err - } - transport := &http.Transport{ - TLSClientConfig: &tls.Config{RootCAs: pool, MinVersion: tls.VersionTLS12}, - TLSHandshakeTimeout: 10 * time.Second, - IdleConnTimeout: 90 * time.Second, - } - p.client = &http.Client{Transport: transport, Timeout: 10 * time.Second} - return p, nil -} - -// loadCAPool reads the ServiceAccount CA bundle from the path recorded on p -// and parses it into a certificate pool. -func (p *kubeStatusPatcher) loadCAPool() (*x509.CertPool, error) { - caPEM, err := os.ReadFile(p.caPath) - if err != nil { - return nil, fmt.Errorf("read service account CA: %w", err) - } - pool := x509.NewCertPool() - if !pool.AppendCertsFromPEM(caPEM) { - return nil, errors.New("service account CA contains no certificates") - } - return pool, nil -} - -// PatchTunnelEndpoints merge-patches status.tunnelEndpoints. An empty set is -// sent as null, which removes the field so stale addresses from a previous -// pod don't linger. -func (p *kubeStatusPatcher) PatchTunnelEndpoints(ctx context.Context, eps []tunnelEndpoint) error { - var list any - if len(eps) > 0 { - list = eps - } - body, err := json.Marshal(map[string]any{"status": map[string]any{"tunnelEndpoints": list}}) - if err != nil { - return fmt.Errorf("encode status patch: %w", err) - } - // Re-read the token each time: projected tokens rotate. - token, err := os.ReadFile(p.tokenPath) - if err != nil { - return fmt.Errorf("read service account token: %w", err) - } - target := fmt.Sprintf("%s/apis/gameplane.local/v1alpha1/namespaces/%s/gameservers/%s/status", - p.baseURL, url.PathEscape(p.namespace), url.PathEscape(p.name)) - req, err := http.NewRequestWithContext(ctx, http.MethodPatch, target, bytes.NewReader(body)) - if err != nil { - return fmt.Errorf("build status patch request: %w", err) - } - req.Header.Set("Content-Type", "application/merge-patch+json") - req.Header.Set("Accept", "application/json") - req.Header.Set("Authorization", "Bearer "+strings.TrimSpace(string(token))) - resp, err := p.client.Do(req) - if err != nil { - return fmt.Errorf("patch gameserver status: %w", err) - } - defer func() { _ = resp.Body.Close() }() - if resp.StatusCode/100 != 2 { - msg, _ := io.ReadAll(io.LimitReader(resp.Body, 512)) - return fmt.Errorf("patch gameserver status: HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(msg))) - } - return nil -} - -// reporterTiming holds the poll cadence; a variable so tests can shrink it. -type reporterTiming struct { - minBackoff time.Duration // first retry delay after a failure / not-running - maxBackoff time.Duration // retry delay cap - steady time.Duration // poll interval once the address is reported -} - -var defaultReporterTiming = reporterTiming{ - minBackoff: 1 * time.Second, - maxBackoff: 30 * time.Second, - steady: 30 * time.Second, -} - -// runPlayitReporter polls playitd until ctx ends, patching status whenever -// the discovered endpoint set changes. Failures (socket not up yet, playitd -// restarting, API errors) back off exponentially from minBackoff to -// maxBackoff; once a set is reported, polling continues every steady -// interval so a changed or removed address is picked up. -func runPlayitReporter(ctx context.Context, socketPath string, ports []backingPort, patcher statusPatcher, timing reporterTiming) { - var last []tunnelEndpoint - reported := false - delay := timing.minBackoff - - for { - wait := delay - state, err := queryPlayitState(ctx, socketPath) - switch { - case err != nil: - if ctx.Err() != nil { - return - } - log.Print("playit reporter: local provider state unavailable") - delay = min(delay*2, timing.maxBackoff) - case state.Phase != "running": - // Not yet assigned (starting, waiting_for_secret, ...): keep - // backing off without touching status. - delay = min(delay*2, timing.maxBackoff) - default: - eps := playitEndpoints(state.Tunnels, ports) - if !reported || !reflect.DeepEqual(eps, last) { - if err := patcher.PatchTunnelEndpoints(ctx, eps); err != nil { - if ctx.Err() != nil { - return - } - log.Print("playit reporter: endpoint status update failed") - delay = min(delay*2, timing.maxBackoff) - break - } - log.Printf("playit reporter: reported %d endpoint(s)", len(eps)) - last, reported = eps, true - } - delay = timing.minBackoff - wait = timing.steady - } - - t := time.NewTimer(wait) - select { - case <-ctx.Done(): - t.Stop() - return - case <-t.C: - } - } -} - -// startPlayitReporter launches the reporter goroutine for a playit tunnel -// and returns a function that waits for it to exit. If the in-cluster -// client can't be built the reporter is skipped (logged): the relay itself -// still works, only the address report is missing. -func startPlayitReporter(ctx context.Context, cfg Config) (wait func()) { - noop := func() {} - ports, err := parseBackingPorts(cfg.BackingServicePorts) - if err != nil { - log.Printf("playit reporter disabled: %v", err) - return noop - } - patcher, err := newInClusterStatusPatcher(serviceAccountMountDir, cfg.GameServerNamespace, cfg.GameServerName) - if err != nil { - log.Printf("playit reporter disabled: %v", err) - return noop - } - done := make(chan struct{}) - go func() { - defer close(done) - runPlayitReporter(ctx, playitSocketPath, ports, patcher, defaultReporterTiming) - }() - return func() { <-done } -} diff --git a/tunnel/playit_reporter_test.go b/tunnel/playit_reporter_test.go deleted file mode 100644 index ec44e6726..000000000 --- a/tunnel/playit_reporter_test.go +++ /dev/null @@ -1,652 +0,0 @@ -package main - -import ( - "bufio" - "context" - "encoding/json" - "encoding/pem" - "errors" - "io" - "net" - "net/http" - "net/http/httptest" - "os" - "path/filepath" - "reflect" - "strconv" - "strings" - "sync" - "testing" - "time" -) - -// ----------------------------------------------------------------------- -// Fake playitd IPC server -// -// Speaks the v1.0.10 wire format (see the header of playit_reporter.go): -// newline-delimited JSON, hello frame first, then one response per request. -// ----------------------------------------------------------------------- - -type fakePlayitd struct { - path string - ln net.Listener - - mu sync.Mutex - hello string // raw hello line; default is a valid v2 hello - respond func(req map[string]any) []string - requests []map[string]any -} - -// shortSocketDir returns a short temp dir: Unix socket paths are capped at -// ~108 bytes and t.TempDir() can exceed that. -func shortSocketDir(t *testing.T) string { - t.Helper() - dir, err := os.MkdirTemp("", "pit") - if err != nil { - t.Fatalf("mkdtemp: %v", err) - } - t.Cleanup(func() { _ = os.RemoveAll(dir) }) - return dir -} - -func newFakePlayitd(t *testing.T, respond func(req map[string]any) []string) *fakePlayitd { - t.Helper() - path := filepath.Join(shortSocketDir(t), "p.sock") - var lc net.ListenConfig - ln, err := lc.Listen(context.Background(), "unix", path) - if err != nil { - t.Fatalf("listen: %v", err) - } - f := &fakePlayitd{ - path: path, - ln: ln, - hello: `{"message_kind":"hello","data":{"protocol":{"ipc_version":2,"capabilities":["lifecycle_state"]}}}`, - respond: respond, - } - t.Cleanup(func() { _ = ln.Close() }) - go f.serve() - return f -} - -func (f *fakePlayitd) serve() { - for { - conn, err := f.ln.Accept() - if err != nil { - return - } - go f.handle(conn) - } -} - -func (f *fakePlayitd) handle(conn net.Conn) { - defer conn.Close() - f.mu.Lock() - hello := f.hello - f.mu.Unlock() - if _, err := io.WriteString(conn, hello+"\n"); err != nil { - return - } - sc := bufio.NewScanner(conn) - for sc.Scan() { - var req map[string]any - if err := json.Unmarshal(sc.Bytes(), &req); err != nil { - return - } - f.mu.Lock() - f.requests = append(f.requests, req) - respond := f.respond - f.mu.Unlock() - for _, line := range respond(req) { - if _, err := io.WriteString(conn, line+"\n"); err != nil { - return - } - } - } -} - -func (f *fakePlayitd) setHello(h string) { - f.mu.Lock() - f.hello = h - f.mu.Unlock() -} - -func (f *fakePlayitd) setRespond(r func(req map[string]any) []string) { - f.mu.Lock() - f.respond = r - f.mu.Unlock() -} - -func stateResponse(lifecycle string) func(req map[string]any) []string { - return func(req map[string]any) []string { - id, _ := req["request_id"].(float64) - b, _ := json.Marshal(map[string]any{ - "message_kind": "response", - "data": map[string]any{ - "ipc_version": 2, - "request_id": int(id), - "response": map[string]any{"type": "state", "data": json.RawMessage(lifecycle)}, - }, - }) - return []string{string(b)} - } -} - -const runningTwoTunnels = `{"state":"running","data":{"version":"1.0.10","tunnels":[ - {"display_address":"alpha.gl.joinmc.link:31337","destination":"10.43.0.10:25565","is_disabled":false,"disabled_reason":null}, - {"display_address":"147.185.221.5:40000","destination":"10.43.0.10:19132","is_disabled":false,"disabled_reason":null} -],"pending_tunnels":[],"notices":[],"account_status":"verified","agent_id":"a","login_link":null,"start_time":0}}` - -// ----------------------------------------------------------------------- -// queryPlayitState -// ----------------------------------------------------------------------- - -func TestQueryPlayitStateRunning(t *testing.T) { - f := newFakePlayitd(t, stateResponse(runningTwoTunnels)) - - st, err := queryPlayitState(context.Background(), f.path) - if err != nil { - t.Fatalf("queryPlayitState: %v", err) - } - if st.Phase != "running" || len(st.Tunnels) != 2 { - t.Fatalf("state = %+v, want running with 2 tunnels", st) - } - if st.Tunnels[0].DisplayAddress != "alpha.gl.joinmc.link:31337" || st.Tunnels[0].Destination != "10.43.0.10:25565" { - t.Errorf("tunnel[0] = %+v", st.Tunnels[0]) - } - - f.mu.Lock() - defer f.mu.Unlock() - if len(f.requests) != 1 { - t.Fatalf("requests = %d, want 1", len(f.requests)) - } - req := f.requests[0] - if req["ipc_version"] != float64(2) || req["request_id"] != float64(1) { - t.Errorf("request envelope = %v", req) - } - inner, _ := req["request"].(map[string]any) - if inner["type"] != "get_state" { - t.Errorf("request type = %v, want get_state", inner["type"]) - } -} - -func TestQueryPlayitStateStarting(t *testing.T) { - f := newFakePlayitd(t, stateResponse(`{"state":"starting"}`)) - st, err := queryPlayitState(context.Background(), f.path) - if err != nil { - t.Fatalf("queryPlayitState: %v", err) - } - if st.Phase != "starting" || len(st.Tunnels) != 0 { - t.Errorf("state = %+v, want starting with no tunnels", st) - } -} - -func TestQueryPlayitStateErrorLifecycle(t *testing.T) { - // Error-bearing lifecycle states carry a ServiceError in "data"; they - // decode as that phase with no tunnels rather than failing. - f := newFakePlayitd(t, stateResponse(`{"state":"has_invalid_secret","data":{"code":"invalid_secret","message":"bad","retryable":false,"details":null}}`)) - st, err := queryPlayitState(context.Background(), f.path) - if err != nil { - t.Fatalf("queryPlayitState: %v", err) - } - if st.Phase != "has_invalid_secret" || len(st.Tunnels) != 0 { - t.Errorf("state = %+v", st) - } -} - -func TestQueryPlayitStateSkipsEvents(t *testing.T) { - f := newFakePlayitd(t, func(req map[string]any) []string { - ev := `{"message_kind":"event","data":{"ipc_version":2,"event":{"type":"stats","data":{"bytes_in":0,"bytes_out":0,"active_tcp":0,"active_udp":0}}}}` - return append([]string{ev}, stateResponse(`{"state":"stopping"}`)(req)...) - }) - st, err := queryPlayitState(context.Background(), f.path) - if err != nil { - t.Fatalf("queryPlayitState: %v", err) - } - if st.Phase != "stopping" { - t.Errorf("phase = %q, want stopping", st.Phase) - } -} - -func TestQueryPlayitStateErrors(t *testing.T) { - tests := []struct { - name string - hello string - respond func(req map[string]any) []string - want string - }{ - { - name: "wrong ipc version", - hello: `{"message_kind":"hello","data":{"protocol":{"ipc_version":3,"capabilities":[]}}}`, - want: "IPC version 3", - }, - { - name: "first frame not hello", - hello: `{"message_kind":"event","data":{}}`, - want: "want hello", - }, - { - name: "garbage hello", - hello: `not json`, - want: "read playitd hello", - }, - { - name: "service error response", - respond: func(map[string]any) []string { - return []string{`{"message_kind":"response","data":{"ipc_version":2,"request_id":1,"response":{"type":"error","data":{"code":"unsupported_protocol","message":"nope","retryable":false}}}}`} - }, - want: "playitd error unsupported_protocol: nope", - }, - { - name: "unexpected response type", - respond: func(map[string]any) []string { - return []string{`{"message_kind":"response","data":{"ipc_version":2,"request_id":1,"response":{"type":"status","data":{}}}}`} - }, - want: `unexpected "status" response`, - }, - { - name: "mismatched request id", - respond: func(map[string]any) []string { - return []string{`{"message_kind":"response","data":{"ipc_version":2,"request_id":7,"response":{"type":"state","data":{"state":"starting"}}}}`} - }, - want: "response id 7", - }, - { - name: "duplicate hello", - respond: func(map[string]any) []string { - return []string{`{"message_kind":"hello","data":{"protocol":{"ipc_version":2}}}`} - }, - want: `unexpected "hello" frame`, - }, - { - name: "state without tag", - respond: func(map[string]any) []string { - return []string{`{"message_kind":"response","data":{"ipc_version":2,"request_id":1,"response":{"type":"state","data":{}}}}`} - }, - want: "no state", - }, - { - name: "blank response frame", - respond: func(map[string]any) []string { - return []string{""} - }, - want: "read get_state response", - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - respond := tt.respond - if respond == nil { - respond = stateResponse(`{"state":"starting"}`) - } - f := newFakePlayitd(t, respond) - if tt.hello != "" { - f.setHello(tt.hello) - } - ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) - defer cancel() - _, err := queryPlayitState(ctx, f.path) - if err == nil || !strings.Contains(err.Error(), tt.want) { - t.Errorf("err = %v, want containing %q", err, tt.want) - } - }) - } -} - -func TestQueryPlayitStateNoSocket(t *testing.T) { - _, err := queryPlayitState(context.Background(), filepath.Join(shortSocketDir(t), "missing.sock")) - if err == nil || !strings.Contains(err.Error(), "dial playitd socket") { - t.Errorf("err = %v, want dial error", err) - } -} - -func TestQueryPlayitStateTimesOut(t *testing.T) { - // A server that sends hello then never answers must not hang forever: - // the caller's context bounds the read. - f := newFakePlayitd(t, func(map[string]any) []string { return nil }) - ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) - defer cancel() - start := time.Now() - _, err := queryPlayitState(ctx, f.path) - if err == nil { - t.Fatal("expected timeout error") - } - if time.Since(start) > 3*time.Second { - t.Errorf("query took %v, want bounded by ctx", time.Since(start)) - } -} - -// ----------------------------------------------------------------------- -// Mapping -// ----------------------------------------------------------------------- - -func TestParseBackingPorts(t *testing.T) { - got, err := parseBackingPorts("java:25565, bedrock:19132,") - if err != nil { - t.Fatalf("parseBackingPorts: %v", err) - } - want := []backingPort{{"java", 25565}, {"bedrock", 19132}} - if !reflect.DeepEqual(got, want) { - t.Errorf("got %v, want %v", got, want) - } - for _, bad := range []string{"java", ":25565", "java:0", "java:70000", "java:abc"} { - if _, err := parseBackingPorts(bad); err == nil { - t.Errorf("parseBackingPorts(%q) = nil error, want error", bad) - } - } -} - -func TestPlayitEndpointsMatchesByDestinationPort(t *testing.T) { - ports := []backingPort{{"java", 25565}, {"bedrock", 19132}} - tunnels := []playitTunnel{ - {DisplayAddress: "alpha.gl.joinmc.link:31337", Destination: "10.43.0.10:25565"}, - {DisplayAddress: "147.185.221.5:40000", Destination: "10.43.0.10:19132"}, - {DisplayAddress: "disabled.example:1", Destination: "10.43.0.10:25565", IsDisabled: true}, - {DisplayAddress: "web.example", Destination: "10.43.0.10 (http: 80, https: 443)"}, - {DisplayAddress: "other.example:5000", Destination: "10.43.0.10:9999"}, - } - got := playitEndpoints(tunnels, ports) - want := []tunnelEndpoint{ - {Name: "bedrock", Host: "147.185.221.5", Port: 40000, TunnelProvider: "playit"}, - {Name: "java", Host: "alpha.gl.joinmc.link", Port: 31337, TunnelProvider: "playit"}, - } - if !reflect.DeepEqual(got, want) { - t.Errorf("got %+v\nwant %+v", got, want) - } -} - -func TestPlayitEndpointsSinglePortFallbackAndPortlessAddress(t *testing.T) { - // One advertised port, one enabled tunnel pointed at a different local - // port, and a display address with no port (SRV-style hostname). - ports := []backingPort{{"game", 25565}} - tunnels := []playitTunnel{{DisplayAddress: "beta.joinmc.link", Destination: "127.0.0.1:1234"}} - got := playitEndpoints(tunnels, ports) - want := []tunnelEndpoint{{Name: "game", Host: "beta.joinmc.link", Port: 25565, TunnelProvider: "playit"}} - if !reflect.DeepEqual(got, want) { - t.Errorf("got %+v, want %+v", got, want) - } -} - -func TestPlayitEndpointsDedupAndBadPort(t *testing.T) { - ports := []backingPort{{"game", 25565}, {"query", 25566}} - tunnels := []playitTunnel{ - {DisplayAddress: "a.example:1000", Destination: "x:25565"}, - {DisplayAddress: "b.example:2000", Destination: "x:25565"}, // duplicate name, dropped - {DisplayAddress: "c.example:99999", Destination: "x:25566"}, // bad public port, dropped - } - got := playitEndpoints(tunnels, ports) - want := []tunnelEndpoint{{Name: "game", Host: "a.example", Port: 1000, TunnelProvider: "playit"}} - if !reflect.DeepEqual(got, want) { - t.Errorf("got %+v, want %+v", got, want) - } - if got := playitEndpoints(nil, ports); len(got) != 0 { - t.Errorf("no tunnels: got %+v, want empty", got) - } -} - -func TestPlayitEndpointsCappedAtCRDMax(t *testing.T) { - var ports []backingPort - var tunnels []playitTunnel - for i := 0; i < maxTunnelEndpoints+5; i++ { - p := int32(20000 + i) - name := "p" + string(rune('a'+i/26)) + string(rune('a'+i%26)) - ports = append(ports, backingPort{name, p}) - tunnels = append(tunnels, playitTunnel{ - DisplayAddress: "h.example:" + strconv.Itoa(int(p)), - Destination: "x:" + strconv.Itoa(int(p)), - }) - } - if got := playitEndpoints(tunnels, ports); len(got) != maxTunnelEndpoints { - t.Errorf("len = %d, want %d", len(got), maxTunnelEndpoints) - } -} - -// ----------------------------------------------------------------------- -// kubeStatusPatcher -// ----------------------------------------------------------------------- - -func TestKubeStatusPatcherPatches(t *testing.T) { - var gotPath, gotCT, gotAuth, gotMethod string - var gotBody map[string]any - srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - gotMethod, gotPath = r.Method, r.URL.Path - gotCT, gotAuth = r.Header.Get("Content-Type"), r.Header.Get("Authorization") - _ = json.NewDecoder(r.Body).Decode(&gotBody) - w.WriteHeader(http.StatusOK) - })) - defer srv.Close() - - dir := t.TempDir() - if err := os.WriteFile(filepath.Join(dir, "token"), []byte("tok-123\n"), 0o600); err != nil { - t.Fatal(err) - } - p := &kubeStatusPatcher{ - baseURL: srv.URL, namespace: "games", name: "mc", - tokenPath: filepath.Join(dir, "token"), client: srv.Client(), - } - eps := []tunnelEndpoint{{Name: "java", Host: "a.example", Port: 1000, TunnelProvider: "playit"}} - if err := p.PatchTunnelEndpoints(context.Background(), eps); err != nil { - t.Fatalf("PatchTunnelEndpoints: %v", err) - } - if gotMethod != http.MethodPatch { - t.Errorf("method = %s", gotMethod) - } - if gotPath != "/apis/gameplane.local/v1alpha1/namespaces/games/gameservers/mc/status" { - t.Errorf("path = %s", gotPath) - } - if gotCT != "application/merge-patch+json" { - t.Errorf("content-type = %s", gotCT) - } - if gotAuth != "Bearer tok-123" { - t.Errorf("authorization = %q", gotAuth) - } - status, _ := gotBody["status"].(map[string]any) - list, _ := status["tunnelEndpoints"].([]any) - if len(list) != 1 { - t.Fatalf("body = %v", gotBody) - } - ep, _ := list[0].(map[string]any) - if ep["name"] != "java" || ep["host"] != "a.example" || ep["port"] != float64(1000) || ep["tunnelProvider"] != "playit" { - t.Errorf("endpoint = %v", ep) - } - - // Empty set clears the field with an explicit null. - if err := p.PatchTunnelEndpoints(context.Background(), nil); err != nil { - t.Fatalf("PatchTunnelEndpoints(nil): %v", err) - } - status, _ = gotBody["status"].(map[string]any) - if v, ok := status["tunnelEndpoints"]; !ok || v != nil { - t.Errorf("empty patch body = %v, want tunnelEndpoints: null", gotBody) - } -} - -func TestKubeStatusPatcherErrors(t *testing.T) { - srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - http.Error(w, "forbidden", http.StatusForbidden) - })) - defer srv.Close() - dir := t.TempDir() - tokenPath := filepath.Join(dir, "token") - if err := os.WriteFile(tokenPath, []byte("t"), 0o600); err != nil { - t.Fatal(err) - } - p := &kubeStatusPatcher{baseURL: srv.URL, namespace: "g", name: "n", tokenPath: tokenPath, client: srv.Client()} - err := p.PatchTunnelEndpoints(context.Background(), nil) - if err == nil || !strings.Contains(err.Error(), "HTTP 403") { - t.Errorf("err = %v, want HTTP 403", err) - } - - p.tokenPath = filepath.Join(dir, "missing") - err = p.PatchTunnelEndpoints(context.Background(), nil) - if err == nil || !errors.Is(err, os.ErrNotExist) { - t.Errorf("err = %v, want wrapped ErrNotExist", err) - } -} - -func TestNewInClusterStatusPatcher(t *testing.T) { - dir := t.TempDir() - if _, err := newInClusterStatusPatcher(dir, "g", "n"); err == nil { - t.Error("missing CA: want error") - } - if err := os.WriteFile(filepath.Join(dir, "ca.crt"), []byte("not a pem"), 0o600); err != nil { - t.Fatal(err) - } - if _, err := newInClusterStatusPatcher(dir, "g", "n"); err == nil { - t.Error("invalid CA: want error") - } - - srv := httptest.NewTLSServer(http.NotFoundHandler()) - defer srv.Close() - certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: srv.Certificate().Raw}) - if err := os.WriteFile(filepath.Join(dir, "ca.crt"), certPEM, 0o600); err != nil { - t.Fatal(err) - } - p, err := newInClusterStatusPatcher(dir, "g", "n") - if err != nil { - t.Fatalf("valid CA: %v", err) - } - if p.baseURL != kubeAPIServerURL || p.tokenPath != filepath.Join(dir, "token") { - t.Errorf("patcher = %+v", p) - } -} - -// ----------------------------------------------------------------------- -// runPlayitReporter -// ----------------------------------------------------------------------- - -type recordingPatcher struct { - mu sync.Mutex - calls [][]tunnelEndpoint - fail int // number of initial calls to fail - ch chan struct{} -} - -func (r *recordingPatcher) PatchTunnelEndpoints(_ context.Context, eps []tunnelEndpoint) error { - r.mu.Lock() - defer func() { - r.mu.Unlock() - select { - case r.ch <- struct{}{}: - default: - } - }() - if r.fail > 0 { - r.fail-- - return errors.New("apiserver unavailable") - } - r.calls = append(r.calls, eps) - return nil -} - -func (r *recordingPatcher) snapshot() [][]tunnelEndpoint { - r.mu.Lock() - defer r.mu.Unlock() - return append([][]tunnelEndpoint(nil), r.calls...) -} - -var fastTiming = reporterTiming{minBackoff: 5 * time.Millisecond, maxBackoff: 20 * time.Millisecond, steady: 10 * time.Millisecond} - -func waitFor(t *testing.T, cond func() bool) { - t.Helper() - deadline := time.Now().Add(3 * time.Second) - for time.Now().Before(deadline) { - if cond() { - return - } - time.Sleep(5 * time.Millisecond) - } - t.Fatal("condition not met within 3s") -} - -func TestRunPlayitReporterReportsOnceAndOnChange(t *testing.T) { - f := newFakePlayitd(t, stateResponse(`{"state":"starting"}`)) - ports := []backingPort{{"java", 25565}, {"bedrock", 19132}} - rp := &recordingPatcher{fail: 1, ch: make(chan struct{}, 1)} - - ctx, cancel := context.WithCancel(context.Background()) - done := make(chan struct{}) - go func() { - defer close(done) - runPlayitReporter(ctx, f.path, ports, rp, fastTiming) - }() - - // While starting, nothing is patched. - time.Sleep(30 * time.Millisecond) - if n := len(rp.snapshot()); n != 0 { - t.Fatalf("patched %d times while starting, want 0", n) - } - - // Running: the first patch fails, the retry succeeds. - f.setRespond(stateResponse(runningTwoTunnels)) - waitFor(t, func() bool { return len(rp.snapshot()) == 1 }) - - // Unchanged state: no further patches across several steady polls. - time.Sleep(50 * time.Millisecond) - if n := len(rp.snapshot()); n != 1 { - t.Fatalf("patched %d times with unchanged state, want 1", n) - } - - // Address change: patched again. - f.setRespond(stateResponse(`{"state":"running","data":{"tunnels":[{"display_address":"new.example:1","destination":"x:25565","is_disabled":false}]}}`)) - waitFor(t, func() bool { return len(rp.snapshot()) == 2 }) - calls := rp.snapshot() - want := []tunnelEndpoint{{Name: "java", Host: "new.example", Port: 1, TunnelProvider: "playit"}} - if !reflect.DeepEqual(calls[1], want) { - t.Errorf("second patch = %+v, want %+v", calls[1], want) - } - - cancel() - select { - case <-done: - case <-time.After(2 * time.Second): - t.Fatal("reporter did not stop after ctx cancel") - } -} - -func TestRunPlayitReporterReportsEmptySetOnFirstRun(t *testing.T) { - // A running agent with no matching tunnels still patches once (with - // null) so stale endpoints from a previous pod are cleared. - f := newFakePlayitd(t, stateResponse(`{"state":"running","data":{"tunnels":[]}}`)) - rp := &recordingPatcher{ch: make(chan struct{}, 1)} - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - go runPlayitReporter(ctx, f.path, []backingPort{{"java", 25565}}, rp, fastTiming) - waitFor(t, func() bool { return len(rp.snapshot()) == 1 }) - if got := rp.snapshot()[0]; len(got) != 0 { - t.Errorf("first patch = %+v, want empty", got) - } -} - -func TestRunPlayitReporterStopsWhenSocketMissing(t *testing.T) { - rp := &recordingPatcher{ch: make(chan struct{}, 1)} - ctx, cancel := context.WithTimeout(context.Background(), 60*time.Millisecond) - defer cancel() - done := make(chan struct{}) - go func() { - defer close(done) - runPlayitReporter(ctx, filepath.Join(shortSocketDir(t), "none.sock"), nil, rp, fastTiming) - }() - select { - case <-done: - case <-time.After(2 * time.Second): - t.Fatal("reporter did not stop at ctx deadline") - } - if n := len(rp.snapshot()); n != 0 { - t.Errorf("patched %d times without a socket, want 0", n) - } -} - -func TestStartPlayitReporterDisabledOutsideCluster(_ *testing.T) { - // Outside a cluster the ServiceAccount mount is absent: the reporter is - // skipped and the returned wait function returns immediately. The - // context is pre-cancelled so that, should the test host happen to have - // a ServiceAccount mount, the started reporter exits at once too. - ctx, cancel := context.WithCancel(context.Background()) - cancel() - wait := startPlayitReporter(ctx, Config{ - GameServerName: "g", GameServerNamespace: "n", BackingServicePorts: "java:25565", - }) - wait() - - wait = startPlayitReporter(ctx, Config{BackingServicePorts: "bad"}) - wait() -} diff --git a/tunnel/relay_health.go b/tunnel/relay_health.go deleted file mode 100644 index 6c4c65298..000000000 --- a/tunnel/relay_health.go +++ /dev/null @@ -1,295 +0,0 @@ -package main - -import ( - "context" - "encoding/json" - "fmt" - "io" - "log" - "net" - "net/http" - "strings" - "sync" - "time" -) - -const ( - healthPollInterval = 2 * time.Second - healthStaleAfter = 10 * time.Second - healthyResetAfter = time.Minute - frpHealthURL = "http://127.0.0.1:7400/api/status" -) - -// Only closed-set, non-sensitive state reaches the health endpoint. Never put -// provider response text, credentials, login links or target addresses here. -type relayObservation struct { - Connection string `json:"connection"` - Forwards bool `json:"forwardsRegistered"` - Assigned bool `json:"endpointAssigned"` -} - -func (o relayObservation) ready() bool { - return o.Connection == "connected" && o.Forwards && o.Assigned -} - -type relaySnapshot struct { - relayObservation - Ready bool `json:"ready"` - checked time.Time -} - -type relayHealth struct { - // Immutable provider capability, independent of fresh observation state. - connectionUnsupported bool - forwarding *forwardTelemetry - mu sync.Mutex - supervisorUnavailable bool - observation relayObservation - checked, healthySince time.Time -} - -func (h *relayHealth) clear() { - h.mu.Lock() - defer h.mu.Unlock() - h.supervisorUnavailable = false - h.observation = relayObservation{Connection: "unknown"} - h.checked, h.healthySince = time.Time{}, time.Time{} -} - -// markUnavailable records that no forwarding attempt is serving. Unlike a -// provider observation, this local fact remains true throughout retry/backoff. -func (h *relayHealth) markUnavailable() { - h.mu.Lock() - defer h.mu.Unlock() - h.supervisorUnavailable = true - h.observation = relayObservation{Connection: "unavailable"} - h.checked, h.healthySince = time.Time{}, time.Time{} -} - -func (h *relayHealth) observe(now time.Time, observation relayObservation, backoff *exponentialBackoff) { - h.mu.Lock() - defer h.mu.Unlock() - h.observeLocked(now, observation, backoff) -} - -func (h *relayHealth) observeLocked(now time.Time, observation relayObservation, backoff *exponentialBackoff) { - h.supervisorUnavailable = false - if !observation.ready() { - h.healthySince = time.Time{} - } else { - if h.healthySince.IsZero() || now.Sub(h.checked) >= healthStaleAfter { - h.healthySince = now - } - if backoff != nil && now.Sub(h.healthySince) >= healthyResetAfter { - backoff.reset() - } - } - h.observation, h.checked = observation, now -} - -func (h *relayHealth) snapshot(now time.Time) relaySnapshot { - h.mu.Lock() - defer h.mu.Unlock() - if h.supervisorUnavailable { - return relaySnapshot{relayObservation: relayObservation{Connection: "unavailable"}} - } - if h.checked.IsZero() || now.Sub(h.checked) >= healthStaleAfter { - return relaySnapshot{relayObservation: relayObservation{Connection: "unknown"}} - } - return relaySnapshot{relayObservation: h.observation, Ready: h.observation.ready(), checked: h.checked} -} - -func relayHealthHandler(h *relayHealth) http.Handler { - mux := http.NewServeMux() - mux.Handle("/metrics", relayMetrics(h)) - mux.HandleFunc("/healthz", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) }) - mux.HandleFunc("/readyz", func(w http.ResponseWriter, _ *http.Request) { - if !h.snapshot(time.Now()).Ready { - http.Error(w, "relay connection or forwards not confirmed", http.StatusServiceUnavailable) - return - } - w.WriteHeader(http.StatusOK) - }) - mux.HandleFunc("/status", func(w http.ResponseWriter, _ *http.Request) { - w.Header().Set("Content-Type", "application/json") - _ = json.NewEncoder(w).Encode(h.snapshot(time.Now())) - }) - return mux -} - -type relayCheck func(context.Context) relayObservation - -func startRelayHealth(ctx context.Context, h *relayHealth) (func(), error) { - listener, err := (&net.ListenConfig{}).Listen(ctx, "tcp", ":8091") - if err != nil { - return nil, fmt.Errorf("relay health listener: %w", err) - } - server := &http.Server{Handler: relayHealthHandler(h), ReadHeaderTimeout: 2 * time.Second, ReadTimeout: 5 * time.Second, WriteTimeout: 5 * time.Second, IdleTimeout: 10 * time.Second} - done := make(chan struct{}) - go func() { defer close(done); _ = server.Serve(listener) }() - return func() { _ = server.Close(); <-done }, nil -} - -func monitorRelay(ctx context.Context, h *relayHealth, check relayCheck, backoff *exponentialBackoff) { - if check == nil { - return - } - for ctx.Err() == nil { - queryCtx, cancel := context.WithTimeout(ctx, 2*time.Second) - observation := check(queryCtx) - cancel() - h.mu.Lock() - if ctx.Err() == nil { - h.observeLocked(time.Now(), observation, backoff) - } - h.mu.Unlock() - if !waitRelayRetry(ctx, healthPollInterval) { - return - } - } -} - -func waitRelayRetry(ctx context.Context, delay time.Duration) bool { - timer := time.NewTimer(delay) - defer timer.Stop() - select { - case <-ctx.Done(): - return false - case <-timer.C: - return true - } -} - -// Each attempt owns its monitor. Joining it before clearing state prevents a -// final in-flight response from re-marking an exited child ready. -func superviseRelay(ctx context.Context, cfg Config, h *relayHealth, check relayCheck, runChild func(context.Context) error, wait func(context.Context, time.Duration) bool) error { - backoff := &exponentialBackoff{} - for ctx.Err() == nil { - h.clear() - attemptCtx, cancel := context.WithCancel(ctx) - done := make(chan struct{}) - go func() { defer close(done); monitorRelay(attemptCtx, h, check, backoff) }() - err := runChild(attemptCtx) - cancel() - h.clear() - <-done - select { - case <-ctx.Done(): - return nil - default: - } - log.Print("relay process exited; readiness cleared") - if isUnrecoverable(cfg, err) { - return fmt.Errorf("unrecoverable relay error: %w", err) - } - // A clean unexpected exit is also a failure. Never busy-loop on it. - delay := backoff.next() - log.Printf("restarting relay in %v", delay) - if !wait(ctx, delay) { - return nil - } - } - return nil -} - -func relayHealthCheck(cfg Config, credential string) relayCheck { - if cfg.TunnelType == "frp" { - // No environment proxy or redirects: the admin credential is restricted - // to this process's loopback frpc endpoint. - client := &http.Client{Transport: &http.Transport{Proxy: nil}, Timeout: 2 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} - return func(ctx context.Context) relayObservation { - return checkFrpHealth(ctx, client, frpHealthURL, cfg, credential) - } - } - if cfg.TunnelType == "playit" { - ports, err := parseBackingPorts(cfg.BackingServicePorts) - return func(ctx context.Context) relayObservation { - if err != nil { - return relayObservation{Connection: "unknown"} - } - state, err := queryPlayitState(ctx, playitSocketPath) - if err != nil { - return relayObservation{Connection: "unknown"} - } - return playitHealthObservation(state, ports) - } - } - return nil // Tailscale's embedded server supplies its own readiness. -} - -func checkFrpHealth(ctx context.Context, client *http.Client, endpoint string, cfg Config, credential string) relayObservation { - unknown := relayObservation{Connection: "unknown"} - req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) - if err != nil { - return unknown - } - req.SetBasicAuth("gameplane", credential) - response, err := client.Do(req) - if err != nil { - return unknown - } - defer func() { _ = response.Body.Close() }() - if response.StatusCode != http.StatusOK { - return unknown - } - var status map[string][]struct { - Name string `json:"name"` - Type string `json:"type"` - Status string `json:"status"` - Error string `json:"err"` - } - if err := json.NewDecoder(io.LimitReader(response.Body, 1<<20)).Decode(&status); err != nil { - return unknown - } - count := 0 - allRegistered := true - connection := "unavailable" - for _, entry := range strings.Split(cfg.BackingServicePort, ",") { - parts := strings.Split(strings.TrimSpace(entry), ":") - if len(parts) != 4 { - return unknown - } - name, protocol := strings.TrimSpace(parts[0]), strings.ToLower(strings.TrimSpace(parts[3])) - found := false - for _, proxy := range status[protocol] { - if proxy.Name == name && proxy.Type == protocol { - // These states belong to an authenticated control session. - // A rejected registration is distinct from a missing connection. - if proxy.Status == "running" || proxy.Status == "start error" || proxy.Status == "wait start" { - connection = "connected" - } - if proxy.Status == "running" && proxy.Error == "" { - found = true - } - } - } - if !found { - allRegistered = false - } - count++ - } - if count == 0 { - return unknown - } - return relayObservation{Connection: connection, Forwards: allRegistered, Assigned: allRegistered} -} - -func playitHealthObservation(state playitState, ports []backingPort) relayObservation { - // v1.0.10's IPC reports cached API assignment, not relay heartbeat. Its - // daemon retains Running on refresh errors. Keep connection unknown even - // when addresses exist; polling cached state cannot renew a health lease. - assigned := state.Phase == "running" && len(ports) > 0 && len(playitEndpoints(state.Tunnels, ports)) == len(ports) - return relayObservation{Connection: "unknown", Assigned: assigned} -} - -func validFrpIdentity(uid string) bool { - if len(uid) == 0 || len(uid) > 128 { - return false - } - for _, r := range uid { - if (r < 'a' || r > 'z') && (r < 'A' || r > 'Z') && (r < '0' || r > '9') && r != '-' { - return false - } - } - return true -} diff --git a/tunnel/relay_health_test.go b/tunnel/relay_health_test.go deleted file mode 100644 index b6b363225..000000000 --- a/tunnel/relay_health_test.go +++ /dev/null @@ -1,223 +0,0 @@ -package main - -import ( - "context" - "errors" - "net/http" - "net/http/httptest" - "os" - "strings" - "testing" - "time" -) - -func TestRelayHealthExpiresAndResetsOnlyAfterConfirmedInterval(t *testing.T) { - t.Parallel() - h := &relayHealth{} - b := &exponentialBackoff{} - for i := 0; i < 12; i++ { - b.next() - } - start := time.Unix(100, 0) - good := relayObservation{Connection: "connected", Forwards: true, Assigned: true} - h.observe(start, good, b) - if !h.snapshot(start.Add(healthStaleAfter - time.Nanosecond)).Ready { - t.Fatal("fresh confirmed health not ready") - } - if h.snapshot(start.Add(healthStaleAfter)).Ready { - t.Fatal("stale health remained ready") - } - // A gap in observations breaks continuity, even when the child lives on. - h.observe(start.Add(healthyResetAfter), good, b) - if got := b.next(); got != 300*time.Second { - t.Fatalf("stale interval reset backoff: %v", got) - } - for elapsed := time.Duration(0); elapsed <= healthyResetAfter; elapsed += healthPollInterval { - h.observe(start.Add(healthyResetAfter+elapsed), good, b) - } - if got := b.next(); got != time.Second { - t.Fatalf("confirmed healthy interval did not reset: %v", got) - } - h.clear() - if h.snapshot(start.Add(2 * healthyResetAfter)).Ready { - t.Fatal("child exit retained ready") - } -} - -func TestRelayHealthHTTPSeparatesLivenessAndReadiness(t *testing.T) { - t.Parallel() - h := &relayHealth{} - handler := relayHealthHandler(h) - for _, path := range []string{"/healthz", "/readyz", "/status"} { - w := httptest.NewRecorder() - handler.ServeHTTP(w, httptest.NewRequestWithContext(t.Context(), http.MethodGet, path, nil)) - want := http.StatusOK - if path == "/readyz" { - want = http.StatusServiceUnavailable - } - if w.Code != want { - t.Fatalf("%s status=%d want=%d", path, w.Code, want) - } - if strings.Contains(w.Body.String(), "secret") { - t.Fatal("health response exposed credentials") - } - } -} - -func TestFrpHealthRequiresEveryRegisteredProxy(t *testing.T) { - t.Parallel() - cfg := Config{BackingServicePort: "game:25565:30000:tcp,query:19132:30001:udp"} - cases := []struct { - name, body string - code int - ready bool - }{ - {"registered", `{"tcp":[{"name":"game","type":"tcp","status":"running","err":""}],"udp":[{"name":"query","type":"udp","status":"running","err":""}]}`, 200, true}, - {"duplicate refused", `{"tcp":[{"name":"game","type":"tcp","status":"start error","err":"already exists"}],"udp":[{"name":"query","type":"udp","status":"running"}]}`, 200, false}, - {"missing udp", `{"tcp":[{"name":"game","type":"tcp","status":"running"}]}`, 200, false}, - {"lost control", `{}`, 200, false}, - {"wrong type", `{"tcp":[{"name":"game","type":"udp","status":"running"}],"udp":[{"name":"query","type":"udp","status":"running"}]}`, 200, false}, - {"auth refused", `secret rejection body must not escape`, 401, false}, - {"bad body", `{`, 200, false}, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - u, p, ok := r.BasicAuth() - if !ok || u != "gameplane" || p != "fixture-token" { - t.Error("missing admin authentication") - } - w.WriteHeader(tc.code) - _, _ = w.Write([]byte(tc.body)) - })) - defer s.Close() - got := checkFrpHealth(context.Background(), s.Client(), s.URL, cfg, "fixture-token") - if got.ready() != tc.ready { - t.Fatalf("observation=%+v ready want %v", got, tc.ready) - } - }) - } -} - -func TestFrpIdentityStableAcrossRestartAndUniqueAcrossRecreation(t *testing.T) { - // Config output has a fixed path, so this test cannot run in parallel. - defer func() { _ = os.Remove(frpConfigPath) }() - for _, uid := range []string{"uid-one", "uid-two"} { - cfg := Config{GameServerUID: uid, GameServerName: "same", GameServerNamespace: "games", FrpServerAddr: "relay", FrpServerPort: 7000, BackingServiceDNS: "same.games.svc", BackingServicePort: "game:25565:30000:tcp"} - var prior string - for i := 0; i < 2; i++ { - path, err := renderFrpConfig(cfg, "token") - if err != nil { - t.Fatal(err) - } - data, err := os.ReadFile(path) - if err != nil { - t.Fatal(err) - } - if !strings.Contains(string(data), `user = "`+uid+`"`) || !strings.Contains(string(data), `name = "game"`) { - t.Fatalf("identity or public mapping changed: %s", data) - } - if i > 0 && prior != string(data) { - t.Fatal("restart changed identity/config") - } - prior = string(data) - } - } - for _, uid := range []string{"", "with.dot", "bad\nuser", `bad"user`} { - if validFrpIdentity(uid) { - t.Fatalf("accepted unsafe identity %q", uid) - } - } -} - -func TestSupervisionBoundsCleanExitRetriesAndCancels(t *testing.T) { - t.Parallel() - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - calls := 0 - var delays []time.Duration - err := superviseRelay(ctx, Config{}, &relayHealth{}, nil, func(context.Context) error { calls++; return nil }, func(_ context.Context, delay time.Duration) bool { - delays = append(delays, delay) - if calls == 4 { - cancel() - return false - } - return true - }) - if err != nil || calls != 4 || len(delays) != 4 { - t.Fatalf("err=%v calls=%d delays=%v", err, calls, delays) - } - for i, d := range delays { - if d != time.Duration(1<..svc` | -| `FRP_SERVER_ADDR` | string | if frp | Hostname or IP of the frp server | -| `FRP_SERVER_PORT` | int | no (default 7000) | frp server port; validated 1–65535 | -| `BACKING_SERVICE_PORT` | string | if frp | Port mappings for frp, format `name:localPort:remotePort:protocol,...` (e.g., `game:34197:30000:udp`); localPort and protocol come from the GameTemplate port, remotePort from `spec.networking.tunnel.frp.remotePorts` (F-052) | -| `TAILSCALE_HOSTNAME` | string | if tailscale | MagicDNS hostname in the tailnet; fatal if unset for tailscale provider | -| `TAILSCALE_TAGS` | string | no | Comma-separated requested tags. Whitespace/empty entries are removed, bare names receive `tag:`, duplicates are removed. Invalid tags fail startup. Requested tags must be granted by tailnet `tagOwners`; refusal does not fall back to an untagged identity. | -| `BACKING_SERVICE_PORTS` | string | if tailscale or playit | Tailscale: `name:port:protocol,...`, only `tcp` and `udp`, at most 32 unique protocol/port pairs. Playit retains `name:port,...`. Upgrade operator and tunnel images together; ambiguous legacy Tailscale mappings fail closed. | -| `PLAYIT_TUNNEL_NAME` | string | if playit | Label/name for the playit tunnel; fatal if unset for playit provider | - -**Validation**: At startup, `loadConfig` enforces mutual requirement rules: frp mandates `FRP_SERVER_ADDR` and `BACKING_SERVICE_PORT`; tailscale mandates `TAILSCALE_HOSTNAME` and `BACKING_SERVICE_PORTS`; playit mandates `PLAYIT_TUNNEL_NAME` and `BACKING_SERVICE_PORTS`. Invalid `FRP_SERVER_PORT` values (non-numeric, out of range 1–65535) are fatal. Unknown `TUNNEL_TYPE` values are fatal. - -### Credentials & Secrets - -The operator mounts a read-only Secret volume at `/etc/gameplane/tunnel-auth` containing provider-specific credential keys: - -| Provider | Key Name | Example Usage | Notes | -|---|---|---|---| -| frp | `token` | Auth token for the frpc client | Read by `readCredentials` and embedded in rendered `/tmp/gameplane-tunnel-frpc.toml` | -| tailscale | `authKey` | Reusable auth key for registration | Read into tsnet.Server.AuthKey in memory; identity state is stored in the Pod volume | -| playit | `secretKey` | API secret key for playitd authentication | Read and written to `/tmp/gameplane-tunnel-playit-auth` for playitd's `--secret-path` flag | - -Whitespace (leading/trailing newlines, spaces) is trimmed from credential values before use. Missing credentials are fatal errors and prevent relay startup. - -### Rendered Config Paths - -| Provider | Path | Format | Ownership | -|---|---|---|---| -| frp | `/tmp/gameplane-tunnel-frpc.toml` | TOML | Rendered by `renderFrpConfig`; read by frpc process | -| playit | `/tmp/gameplane-tunnel-playit-auth` | Raw text (secret key) | Rendered by `renderPlayitConfig`; read by playitd via `--secret-path` flag | - -frp/playit rendered files use mode 0600 and are removed when `run` returns. Tailscale uses the state volume described below; no daemon config or CLI auth file is produced. - -### Relay Binaries and Command-Line Arguments - -| Provider | Binary | Arguments | -|---|---|---| -| frp | `/usr/local/bin/frpc` | `-c /tmp/gameplane-tunnel-frpc.toml` (config file flag) | -| playit | `/usr/local/bin/playitd` | `--secret-path /tmp/gameplane-tunnel-playit-auth`, `--socket-path /tmp/gameplane-tunnel-playitd.sock`, `--platform-docker` | - -All binary paths are fixed constants, not configurable. Secrets are never passed via command-line arguments (gosec G204 compliance). - -### Playit Address Reporting (F-174) - -playit.gg assigns a tunnel's public address server-side, so the supervisor learns it at runtime (`playit_reporter.go`) and reports it back: - -1. `playitd` is started with `--socket-path /tmp/gameplane-tunnel-playitd.sock`. Its Linux default, `/run/playit/playitd.sock`, can't be created by the non-root distroless image. `playitd` chmods the socket to `0660` under its own uid (65532), which the supervisor shares. -2. A goroutine started by `run` polls that socket with playitd's IPC protocol (playit-agent v1.0.10, `packages/playit-ipc`). The protocol is newline-delimited JSON over a Unix stream socket. The server sends `{"message_kind":"hello","data":{"protocol":{"ipc_version":2,...}}}`. The client then sends `{"ipc_version":2,"request_id":1,"request":{"type":"get_state"}}`. The reply is `{"message_kind":"response","data":{...,"response":{"type":"state","data":{"state":"running","data":{"tunnels":[{"display_address","destination","is_disabled",...}]}}}}}`. Any IPC version other than 2 is treated as an error. -3. `TunnelState` carries no tunnel name, so each enabled tunnel is mapped to a `BACKING_SERVICE_PORTS` name by matching the port in its `destination` (the local origin, `ip:port`). With exactly one advertised port and one enabled tunnel, the two are paired even if the ports differ. A `display_address` without a port (an SRV-style playit hostname) is reported with the backing port number. HTTPS tunnels and unmatched tunnels are skipped. The list is capped at 32 entries (the CRD's `MaxItems`). -4. When the mapped set differs from the last one reported, it's merge-patched into `status.tunnelEndpoints` on `PATCH https://kubernetes.default.svc/apis/gameplane.local/v1alpha1/namespaces//gameservers//status`. The request uses the pod's projected ServiceAccount token and CA from `/var/run/secrets/kubernetes.io/serviceaccount`. The first report after startup is always sent, and an empty set is sent as `null` so stale addresses from a previous pod are cleared. The operator validates those entries (`validatePlayitEndpoints`) and merges them into `status.endpoints`, the same place frp/tailscale endpoints land. -5. Timing: while the socket is down, playitd isn't `running` yet, or a patch fails, the reporter backs off from 1s, doubling up to 30s. Once a set has been reported, it re-polls every 30s so address changes are picked up. It stops when `run`'s context ends. If the ServiceAccount CA can't be read (not in a cluster) or `BACKING_SERVICE_PORTS` doesn't parse, the reporter logs and is skipped. The relay still runs. - -### Embedded Tailscale forwarding (F-173 / #722) - -The maintainer chose embedded `tailscale.com/tsnet` for TCP and UDP; the decision is recorded in [OPEN-DECISIONS.md](../specs/done_018-v0-3-release-readiness/OPEN-DECISIONS.md#od-031-tailscale-game-forwarding-f-173--resolved-2026-10-21). No tailscaled executable, CLI, subnet router, exit node, Serve or Funnel configuration is used. - -- `tailscaleForwardPlan` accepts only the exact `..svc` host and explicitly advertised protocol/port pairs. Inbound bytes never select a backend address. TCP listens on both tailnet families; UDP binds each assigned tailnet IP because tsnet requires an explicit address. -- The ordinary Go network dialer resolves the Service for each new TCP connection or UDP session. Existing streams/sessions can fail during Service/backend replacement; reconnecting clients resolve the current Service. UDP sessions expire after 30 seconds without traffic in either direction; server-only updates keep an established session alive. -- A shared budget covers every port, protocol and address family. The default is 128 sessions and four queued UDP datagrams per peer (65,507 bytes each) plus one response buffer per UDP session. The operator supplies `TAILSCALE_MAX_SESSIONS` and `TAILSCALE_UDP_QUEUE`. Full budgets or queues drop incoming UDP and excess TCP connections close. Dials and UDP writes time out after five seconds. TCP sockets have five-minute activity timeouts. Shutdown closes listeners and sockets, cancels pending dials, then joins workers. See [relay capacity and measurements](../docs/relay-health.md#forwarding-capacity) for configuration bounds, counters and workload methodology. -- `tsnet.Server` receives the existing hostname, normalized requested tags and mounted auth key. There is no untagged fallback. The fixed state directory `/var/lib/gameplane-tailscale` uses a per-Pod EmptyDir owned through fsGroup 65532. Container restarts reuse identity. Pod replacement loses state and needs a reusable valid auth key; the Deployment uses Recreate. This is not durable identity across Pod replacement. Remove stale devices in the tailnet admin console to free the hostname. A suffixed/conflicting MagicDNS name cannot report the originally advertised name as ready. -- The operator validates tag syntax before creating the Deployment. Invalid tags remove a prior Deployment and report `TunnelReady=False/InvalidTailscaleTags` with correction guidance; fixing the tags resumes reconciliation. Authentication or tag-authorization failures still fail closed inside tsnet, with no registration attempt that omits requested tags. -- `Up` has a two-minute attempt deadline; failed attempts use the existing capped retry delay. After binding every listener, the binary polls local tailnet status every two seconds with a two-second deadline. Loss of online status, tags or hostname clears readiness. Address changes recreate listeners. Failed listeners close all forwarding sockets and retry. Credentials and interactive login URLs are excluded from logs. -- Tailscale retry escalation resets to one second only after one uninterrupted minute of confirmed online identity and bound listeners. An unhealthy observation, a new session, or a gap of ten seconds or more between observations starts a new healthy interval. Brief ready states do not reset escalation. The deterministic no-jitter schedule and 300-second cap remain unchanged; cancellation does not retry. -- HTTP `:8091/readyz` returns 200 only while that state is ready, otherwise 503. `/healthz` remains independent of tailnet availability. The operator probes every five seconds and requires a current observed Deployment generation with an updated ready replica. Legacy deployments without the forwarding probe cannot report `TunnelReady=True`. Tailscale endpoints are published only while ready. -- Readiness establishes local forwarding capacity and tailnet authentication. It does not prove a particular player's grant or game application health, and it deliberately remains ready while the game sleeps so traffic can reach the sentinel. Tailnet grants/ACLs still determine which peers may connect. Missing tags, denied registration, device approval and hostname conflicts require administrator repair. -- Upgrading from the former daemon implementation re-registers the Pod. Replace the auth key first if it was single-use. Coordinate operator and tunnel image upgrades; the new protocol-bearing port contract rejects old ambiguous entries. - -The disposable integration procedure in [tailscale-forwarding-integration.md](../docs/tailscale-forwarding-integration.md) covers actual tailnet TCP/UDP, denied grants, backend replacement and registration/restart outcomes. Unit transports use real local sockets; they do not establish live tailnet coverage. - -## Key Invariants - -1. **Tunnel pod never sleeps.** The tunnel Deployment persists for the full GameServer lifecycle, even when the server idles or suspends. The pod must remain running to hold the relay address so a connection attempt can trigger wake-on-connect. - -2. **Credentials are never passed via command-line.** frp embeds credentials in a private config file, playitd reads a secret file via `--secret-path`, and tsnet receives its key in memory. This guards against argv scraping and satisfies gosec's G204 (subprocess argument constant verification). - -3. **Exponential backoff is capped and unshed.** On transient failure, retry delays follow 2^n seconds (1s, 2s, 4s, ..., 256s) capped at 300 seconds (5 minutes). No jitter is added because each pod runs a single replica against its own relay connection; jitter spreads out a thundering herd, not a singleton. - -4. **Exit codes 126/127 and permission errors are unrecoverable.** Exit code 126 (permission denied) and 127 (command not found) indicate misconfiguration, missing binaries, or permission issues. Any error message containing "permission denied" is treated as unrecoverable. All other exit codes trigger backoff retry. - -5. **SIGTERM is forwarded for graceful shutdown.** When the pod is terminated, SIGTERM is sent to the relay child process. The relay has 10 seconds (cmd.WaitDelay) to shut down cleanly before SIGKILL is sent. Relay logs (stdout/stderr) flow through the pod's container logs. - -6. **Config file paths are compile-time constants.** To pass gosec's subprocess-argument verification, all config file paths are defined as package-level constants, not variables. This ensures `buildCommand` can pass `exec.CommandContext` with only literal or constant-resolved arguments. - -7. **Operator image selection per provider.** The operator injects provider-specific tunnel images via flags (`--tunnel-frp-image`, `--tunnel-tailscale-image`, `--tunnel-playit-image`), each with a `dev` default. Each pod runs exactly one provider's binary, selected by `TUNNEL_TYPE`. - -## Known Limits - -Tailscale identity survives container restarts but not Pod replacement; a reusable auth key and free MagicDNS hostname are required for re-registration. Live tailnet integration needs an explicitly provisioned disposable tailnet and is separate from ordinary unit CI. The prior registration-only F-173 gap is replaced by the embedded TCP/UDP bridge above. - -## CRD Integration - -The tunnel configuration is anchored in the `GameServer` CRD at `spec.networking.tunnel`: - -| Field | Type | Applies To | Notes | -|---|---|---|---| -| `enabled` | bool | All providers | Must be true to create a tunnel Deployment | -| `provider` | enum (frp\|tailscale\|playit) | All providers | Selects tunnel binary and config rendering strategy | -| `credentialsSecretRef` | SecretNameRef (optional) | All providers | Required if enabled=true (enforced by kubebuilder validation) | -| `frp` | FrpTunnelSpec (optional) | frp only | `serverAddr` (required), `serverPort` (optional, default 7000), `remotePorts[]` (required, min 1 item) | -| `tailscale` | TailscaleTunnelSpec (optional) | tailscale only | `hostname` (optional, defaults to GameServer name), `tags[]` (optional, max 8) | -| `playit` | PlayitTunnelSpec (optional) | playit only | `tunnelName` (optional, defaults to GameServer name) | - -The operator's `reconcileTunnel` reconciler materializes these fields into the tunnel Deployment's environment variables and Secret mount. - -## Operator Integration - -**Image Flags** (set at operator startup via `cmd/main.go`): -- `--tunnel-frp-image` (default: `ghcr.io/gameplanepanel/gameplane/tunnel-frp:dev`) -- `--tunnel-tailscale-image` (default: `ghcr.io/gameplanepanel/gameplane/tunnel-tailscale:dev`) -- `--tunnel-playit-image` (default: `ghcr.io/gameplanepanel/gameplane/tunnel-playit:dev`) - -**Deployment Structure** (per GameServer): -- Name: `-tunnel` -- Replicas: 1 (never zero during sleep); 0 while the operator refuses the credentials Secret (`TunnelReady=False`, reason `TunnelCredentialRefused`), so a tunnel already running with it stops -- Container name: `tunnel` -- Security context: uid 65532 (nonroot), runAsNonRoot=true, allowPrivilegeEscalation=false, ALL capabilities dropped -- Mounts: read-only Secret at `/etc/gameplane/tunnel-auth` (if credentialsSecretRef is set; the operator refuses to mount a Secret with no `ownerReference` to the GameServer — see operator/specs.md's TunnelReady condition) - -**RBAC** (playit provider only): -- ServiceAccount: `-tunnel` -- Role: `-tunnel-tunnel` (immutable naming) -- Permissions: `gameplane.local/gameservers/status patch` (narrow to the specific GameServer by resourceNames) - -The playit provider alone needs RBAC because it must patch the GameServer's status subresource to report discovered addresses. frp and tailscale use static/pre-configured addresses and do not need this grant. - -**NetworkPolicy** (all providers): -- A per-server egress policy (`-tunnel-egress`) admits outbound traffic from the tunnel pod to: - - DNS (UDP/TCP port 53, all destinations) - - Relay control plane ports (provider-specific: TCP 7000 for frp, TCP 443 + UDP 41641 for tailscale, playit: unrestricted egress (all ports, all protocols, any destination)) - - Container advertised ports (inbound relay traffic forwarded to the game) - -Without this policy, the default-deny egress rule in the games namespace would silently drop relay connections. - -## Supervision and Failure Handling - -### Backoff Strategy - -``` -retry 1: 1 second (2^0) -retry 2: 2 seconds (2^1) -retry 3: 4 seconds (2^2) -retry 4: 8 seconds (2^3) -... -retry N: min(2^(N-1), 300) seconds -``` - -Capping at 300 seconds (5 minutes) prevents arbitrarily long waits. No jitter or randomization (unnecessary for a singleton pod). - -### Exit Code Classification - -- **Unrecoverable (fatal):** Exit code 126, 127, or any error message containing "permission denied". Pod logs the error and exits immediately. -- **Transient (retry):** All other exit codes and errors. Pod computes backoff delay, sleeps, and spawns the relay binary again. -- **Graceful shutdown:** Context cancelled (e.g., pod termination). Pod sends SIGTERM to child, waits 10 seconds, then SIGKILL if needed. No retry. - -### Graceful Shutdown (SIGTERM → 10s grace → SIGKILL) - -When the pod receives SIGTERM (e.g., during cluster shutdown or pod deletion): -1. The signal handler cancels the context. -2. The main loop observes `ctx.Done()` and stops spawning new relay processes. -3. The currently-running relay process receives SIGTERM (via cmd.Cancel, which calls `cmd.Process.Signal(syscall.SIGTERM)`). -4. The relay process has 10 seconds (cmd.WaitDelay) to shut down. -5. If the relay doesn't exit within 10 seconds, exec.Cmd automatically sends SIGKILL. -6. The pod exits cleanly once the child is dead. - -## Dependencies - -**Internal:** None -**External:** `tailscale.com/tsnet` v1.104.2 and Go stdlib. The playit status patch uses plain `net/http` against the API server without adding client-go. -**Go version:** 1.27.3+ (the minimum required by Tailscale v1.104.2) - -The maintainer explicitly approved ending the stdlib-only policy for tsnet in #722. Version 1.104.2 preserves the upstream Tailscale security update while retaining the embedded TCP/UDP forwarding implementation. CI resolves the latest Go 1.27 patch; the workspace and tunnel module require at least Go 1.27.3, and tunnel image builders use Go 1.27.3. Track future tsnet/security updates through go.mod/go.sum. frpc and playitd remain external binaries. - -## Security Considerations - -1. **Secret mounting (read-only):** Credentials are mounted from Kubernetes Secrets into the pod at `/etc/gameplane/tunnel-auth` as a read-only VolumeMount. The credential files are accessed only after a path-containment check via `filepath.Rel` to ensure the resolved path does not escape the mount directory, providing defense-in-depth against directory traversal. - -2. **Credentials never on argv:** frp/playit accept secrets via private files; Tailscale receives the mounted key in memory. This ensures secrets don't appear in `/proc//cmdline`. - -3. **Hardened pod security context:** UID 65532 (nonroot), runAsNonRoot=true, allowPrivilegeEscalation=false, all capabilities dropped. No privileged escalation or host access. - -4. **Narrow RBAC for playit:** Only playit needs a Kubernetes grant (patch gameservers/status), and the Role is scoped to the single GameServer by resourceNames. frp and tailscale run without RBAC grants. - -5. **Network egress policy:** The tunnel pod's outbound traffic is controlled by a per-server NetworkPolicy. Without it, the games namespace's default-deny-egress would block relay connections. - -6. **Image provider isolation:** Provider images remain separate. The shared Go executable now links tsnet; all three tunnel images must be rebuilt for a dependency security update. - -7. **No credential validation at tunnel pod level:** The tunnel supervisor does not validate frp tokens, Tailscale auth keys, or playit secret keys. Validation happens at the provider's server. Invalid credentials manifest as authentication failures on the provider side. - -## Testing & Coverage - -**Test structure:** - -- **Config loading:** `TestLoadConfigFrp`, `TestLoadConfigTailscale`, `TestLoadConfigPlayit` verify environment variable parsing and provider-specific validation (required fields per provider, default values). -- **Config validation errors:** `TestLoadConfigMissingRequired`, `TestLoadConfigFrpMissingAddress`, `TestLoadConfigInvalidFrpPort`, `TestLoadConfigTailscaleMissingHostname`, `TestLoadConfigPlayitMissingTunnelName` verify that missing or invalid required fields are fatal with clear error messages. -- **Credential reading:** `TestReadCredentialsSuccess`, `TestReadCredentialsMissingFile`, `TestReadCredentialsKeyNames`, `TestReadCredentialsUnknownTunnelType` verify credential path isolation (defense-in-depth `filepath.Rel` check) and per-provider key names. -- **Config rendering:** frp and playit tests verify private file formats, escaping, credential delivery and invalid mappings. -- **Command building:** frp/playit tests check argv and fixed paths. -- **Tailscale:** local socket regressions cover bidirectional TCP/UDP, peer isolation, shared session limits, idle eviction and shutdown. Lifecycle tests cover hostname/tag configuration, denied registration/tags, dual-stack listener creation, partial bind cleanup, online/offline readiness and hostname collisions. Operator tests verify protocol projection, readiness generation/probe requirements, unsupported protocols and EmptyDir/Recreate deployment wiring. -- **Exponential backoff:** `TestExponentialBackoff`, `TestExponentialBackoffCap` verify delay calculations and the 300-second cap. -- **Tailnet retry health:** production and retry regressions share `tailnetRetryObserver`. Tests verify failed authentication, denied tags and listener failures never record a ready observation or reset escalation, and only continuous fresh health resets the delay. -- **Tailscale retry recovery:** `TestTailnetRetryHealthRequiresContinuousConfirmation`, `TestTailnetRetryObserverConfirmedSessionClosesListeners`, and `TestTailnetFailedAttemptsCannotResetRetryEscalation` cover sustained health, short sessions, offline interruptions, stale observations, failed registration/listener setup, and cancellation with listener teardown. Observation times are explicit, so the one-minute reset contract does not require a wall-clock minute in CI. -- **Error classification:** `TestIsUnrecoverable` verifies that exit codes 126/127 and "permission denied" errors are unrecoverable, and that other errors trigger retry. -- **Supervision lifecycle:** `TestRunContextCancellation`, `TestRunTransientFailureBacksOffThenCancels`, `TestRunRenderConfigFailure`, `TestRunReadCredentialsFailure`, `TestRunPlayitConfigDispatch` verify clean context cancellation, backoff retry, and error path handling. -- **Playit address reporting** (`playit_reporter_test.go`): a fake playitd IPC server on a Unix socket speaks the v1.0.10 wire format. `TestQueryPlayitState*` cover running/starting/error lifecycles, skipped event frames, protocol errors (wrong IPC version, missing hello, service error, mismatched request id, blank frame), a missing socket and a context timeout. `TestParseBackingPorts` and `TestPlayitEndpoints*` cover the port-name mapping, the single-port fallback, portless addresses, dedup and the 32-entry cap. `TestKubeStatusPatcher*` and `TestNewInClusterStatusPatcher` run against an `httptest` TLS server and check the merge-patch path, headers, body and `null` clear. `TestRunPlayitReporter*` check backoff, patching only on change, the initial empty clear, and shutdown on context end. -- **Process execution:** `TestRunCommandSuccess`, `TestRunCommandNonZeroExit`, `TestRunCommandStartError`, `TestRunCommandContextCancellation` verify command spawning, exit code propagation, and graceful SIGTERM shutdown with 10-second grace period. - -**Test doubles:** - -- **`withCredentialsDir`:** Temporary directory helper that repoints the package-level `credentialsDir` var at `t.TempDir()` for the duration of a test, allowing credential reads to be exercised without touching the real mount point. -- **`fakeTailnetNode`:** controls registration/status outcomes while opening real local listeners; no provider credentials are needed. -- **Real system binaries in some tests:** `TestRunCommandContextCancellation` uses the real `sleep` command (no relay binary needed) to verify that context cancellation triggers SIGTERM forwarding, allowing the child to exit cleanly within the 10-second grace period. - -**Coverage gate:** 70% per `.testcoverage.yml`. Uncovered paths include error cases in relay binary spawning (operator-level validation and pod constraints already catch most configuration issues before the tunnel binary runs) and platform-specific signal handling edge cases. - -**Coverage rationale:** The tunnel supervisor's primary responsibility is configuration management and child process supervision. Tests cover all config parsing, credential reading, config rendering, command building, and supervision loop paths. frpc/playitd and the embedded tsnet library are third-party; local socket tests cover Gameplane's bridge. The tunnel pod's job is to correctly invoke them and restart on failure; actual relay functionality is end-to-end tested at the e2e suite level. - -## References - -- **Architecture:** `docs/tunnels.md` (tunnel provider setup, wake-on-connect interaction, troubleshooting) -- **CRD & operator integration:** `operator/internal/controller/gameserver_tunnel.go` (deployment creation, env var composition), `operator/internal/controller/tunnel_rbac.go` (RBAC for playit), `operator/api/v1alpha1/gameserver_types.go` (CRD fields) -- **Consumers:** Operator (operator/internal/controller/gameserver_controller.go invokes planTunnel and reconcileTunnel), API (api/internal/handlers may report tunnel endpoints to dashboard) -- **Related specs:** `operator/specs.md` (CRD reconciliation), `api/specs.md` (endpoint reporting) -- **CLAUDE.md:** "K8s-native by default" (rule 9) and "Operator is authoritative" (rule 10) - -## Relay health and identity contract (#721, #723) - -`relay_health.go` owns the frp/Playit wrapper health interface and supervised -attempt lifecycle. `/healthz`, `/readyz` and `/status` listen on Pod TCP 8091. -The startup probe checks wrapper liveness; frp's readiness probe requires actual -provider evidence. Playit Pod readiness uses `/healthz`, independently of its -unknown relay connection. No liveness probe restarts a healthy wrapper for a provider -outage. Each attempt owns its monitor, cancels and joins it on exit, then clears -readiness so a late response cannot resurrect the exited child. Queries have a -two-second deadline and two-second cadence. Observations expire after ten -seconds. All health responses use closed-set state; raw provider errors and -credentials are not exposed. - -Tailscale reports observed failures as unavailable. While no forwarding attempt -is serving, including retry backoff and replacement registration, the supervisor -retains that known unavailable state without a provider-observation timestamp. -This local lifecycle fact does not expire. Once forwarding is established, fresh -provider observations replace it and retain the ten-second staleness limit. -The served health handler and metrics are checked after a real listener failure, -during a blocked replacement join, and after recovery in the regression source. - -frpc's authenticated loopback API `/api/status` on 127.0.0.1:7400 must confirm -every configured proxy is running without error, with the expected protocol. -The generated `user` is the GameServer UID, preserving advertised proxy names -while making their wire identities unique. Heartbeat interval/timeout are 5/15 -seconds and multiplex keepalive is five seconds. frp and Playit Deployments use -Recreate and a single replica to avoid simultaneous owners of an identity. - -Playit v1.0.10 IPC has no relay heartbeat: `Running` and addresses are cached API -data that survive refresh errors. Assignment remains reportable, but connection -readiness stays unknown and `/readyz` fails closed. The Kubernetes probe instead -uses `/healthz` so the Pod can become ready. The operator reports -`RelayConnectionUnknown`, or `AwaitingAddress` before assignment. Future positive -readiness needs a provider interface with fresh connection evidence. Never infer -it from process lifetime or repeated reads of a cached address. - -Backoff has no jitter and remains capped at 300 seconds. Both nonzero and clean -unexpected exits back off. It resets to one second only after one uninterrupted -minute of confirmed, non-stale readiness. Resource configuration retains #724's -`TunnelResources` interface (nil defaults 25m/64Mi requests, non-nil overrides, -empty object clears). See [relay health and upgrade guidance](../docs/relay-health.md) -for migration and integration coverage. Tests run in CI only. diff --git a/tunnel/system-deps.toml b/tunnel/system-deps.toml deleted file mode 100644 index e54877b4f..000000000 --- a/tunnel/system-deps.toml +++ /dev/null @@ -1,15 +0,0 @@ -# System dependencies for tunnel (spec 026). Language libraries stay in go.mod/package.json. - -component = "tunnel" - -[[dep]] -name = "go" -kind = "toolchain" -version = "go" -reason = "Compiles and tests the tunnel module (go.work:3-21; inventory 2.1; nested frpc module is outside go.work, tunnel/frpc/go.mod)." - -[[dep]] -name = "golangci-lint" -kind = "cli" -version = "golangci_lint" -reason = "make lint-go runs golangci-lint in this module (Makefile:302-305; GO_MODULES at Makefile:43)." diff --git a/tunnel/tailscale.go b/tunnel/tailscale.go deleted file mode 100644 index 4afc49ece..000000000 --- a/tunnel/tailscale.go +++ /dev/null @@ -1,237 +0,0 @@ -package main - -import ( - "context" - "errors" - "fmt" - "log" - "net" - "net/http" - "net/netip" - "slices" - "strings" - "sync/atomic" - "time" - - "tailscale.com/ipn/ipnstate" - "tailscale.com/tsnet" -) - -const tailscaleStateDir = "/var/lib/gameplane-tailscale" - -type tailnetNode interface { - Up(context.Context) (*ipnstate.Status, error) - Status(context.Context) (*ipnstate.Status, error) - Listen(string, string) (net.Listener, error) - ListenPacket(string, string) (net.PacketConn, error) -} - -type embeddedTailnet struct{ *tsnet.Server } - -func (s embeddedTailnet) Up(ctx context.Context) (*ipnstate.Status, error) { - status, err := s.Server.Up(ctx) - if err != nil { - return nil, err - } - return checkTailnetHostname(status, s.Hostname) -} - -func (s embeddedTailnet) Status(ctx context.Context) (*ipnstate.Status, error) { - client, err := s.LocalClient() - if err != nil { - return nil, err - } - status, err := client.StatusWithoutPeers(ctx) - if err != nil { - return nil, err - } - return checkTailnetHostname(status, s.Hostname) -} - -func checkTailnetHostname(status *ipnstate.Status, hostname string) (*ipnstate.Status, error) { - if status == nil || status.Self == nil { - return nil, errors.New("tailnet identity unavailable") - } - name, _, _ := strings.Cut(status.Self.DNSName, ".") - if name != hostname { - return nil, errors.New("tailnet hostname differs from advertised endpoint; enable MagicDNS and remove conflicting device names") - } - return status, nil -} - -func tailscaleServer(cfg Config, authKey string) (*tsnet.Server, []string, error) { - tags, err := parseTailscaleTags(cfg.TailscaleTags) - if err != nil { - return nil, nil, fmt.Errorf("tailscale tags: %w", err) - } - if cfg.TailscaleHostname == "" || authKey == "" { - return nil, nil, errors.New("tailscale hostname and authKey are required") - } - return &tsnet.Server{Hostname: cfg.TailscaleHostname, AuthKey: authKey, AdvertiseTags: tags, Dir: tailscaleStateDir, - // Neither verbose daemon logs nor interactive login URLs belong in pod - // logs. Readiness and sanitized retry messages expose failure instead. - Logf: func(string, ...any) {}, UserLogf: func(string, ...any) {}, - }, tags, nil -} - -func runTailscale(ctx context.Context, cfg Config, authKey string) error { - ports, err := tailscaleForwardPlan(cfg) - if err != nil { - return err - } - var ready atomic.Bool - healthHistory := &relayHealth{forwarding: &forwardTelemetry{limits: cfg.ForwardLimits}} - listener, err := (&net.ListenConfig{}).Listen(ctx, "tcp", ":8091") - if err != nil { - return fmt.Errorf("tailscale health listener: %w", err) - } - health := &http.Server{Handler: relayHealthHandler(healthHistory), ReadHeaderTimeout: 2 * time.Second, ReadTimeout: 5 * time.Second, WriteTimeout: 5 * time.Second, IdleTimeout: 10 * time.Second} - healthDone := make(chan error, 1) - go func() { healthDone <- health.Serve(listener) }() - defer func() { _ = health.Close() }() - backoff := &exponentialBackoff{} - for ctx.Err() == nil { - server, tags, err := tailscaleServer(cfg, authKey) - if err != nil { - return err - } - err = serveTailnetWithHealth(ctx, embeddedTailnet{server}, tags, ports, &ready, 2*time.Second, healthHistory, backoff) - ready.Store(false) - _ = server.Close() - if ctx.Err() != nil { - return nil - } - // Up errors may embed registration responses. Keep credentials and - // login URLs out of logs; the operator exposes a pending condition. - if err != nil { - log.Print("Tailscale forwarding unavailable; check credentials, requested tagOwners, device approval, unique hostname, MagicDNS and tailnet connectivity") - } - if err := waitTailnetRetry(ctx, healthDone, backoff.next()); err != nil { - if ctx.Err() != nil { - return nil - } - return err - } - } - return nil -} - -func waitTailnetRetry(ctx context.Context, healthDone <-chan error, delay time.Duration) error { - timer := time.NewTimer(delay) - defer timer.Stop() - select { - case <-ctx.Done(): - return ctx.Err() - case err := <-healthDone: - return fmt.Errorf("tailscale health server: %w", err) - case <-timer.C: - return nil - } -} - -// serveTailnetWithHealth preserves a known outage while a replacement joins -// and after an attempt exits, until serving forwards provide fresh evidence. -func serveTailnetWithHealth(ctx context.Context, node tailnetNode, tags []string, ports []forwardPort, ready *atomic.Bool, poll time.Duration, history *relayHealth, backoff *exponentialBackoff) error { - history.markUnavailable() - defer history.markUnavailable() - return serveTailnetObserved(ctx, node, tags, ports, ready, poll, history.forwarding, tailnetRetryObserver(history, backoff, time.Now)) -} - -func tailnetRetryObserver(history *relayHealth, backoff *exponentialBackoff, now func() time.Time) func(bool) { - return func(healthy bool) { - history.observe(now(), tailnetHealthObservation(healthy), backoff) - } -} - -func tailnetHealthObservation(healthy bool) relayObservation { - if healthy { - return relayObservation{Connection: "connected", Forwards: true, Assigned: true} - } - // Unlike Playit's cached assignment, tsnet provides an observed failure. - // Keep it known so an outage raises the unavailable alert. - return relayObservation{Connection: "unavailable"} -} - -func tailnetReady(status *ipnstate.Status, tags []string) bool { - if status == nil || status.BackendState != "Running" || status.Self == nil || !status.Self.Online || len(status.TailscaleIPs) == 0 { - return false - } - for _, tag := range tags { - if status.Self.Tags == nil || !slices.Contains(status.Self.Tags.AsSlice(), tag) { - return false - } - } - return true -} - -func serveTailnet(ctx context.Context, node tailnetNode, tags []string, ports []forwardPort, ready *atomic.Bool, poll time.Duration) error { - return serveTailnetObserved(ctx, node, tags, ports, ready, poll, nil, nil) -} - -func serveTailnetObserved(ctx context.Context, node tailnetNode, tags []string, ports []forwardPort, ready *atomic.Bool, poll time.Duration, telemetry *forwardTelemetry, observe func(bool)) error { - ready.Store(false) - defer ready.Store(false) - if observe != nil { - defer observe(false) - } - upCtx, cancel := context.WithTimeout(ctx, 2*time.Minute) - status, err := node.Up(upCtx) - cancel() - if err != nil { - return fmt.Errorf("join tailnet: %w", err) - } - if !tailnetReady(status, tags) { - return errors.New("tailnet is not online with the requested tags") - } - ips := append([]netip.Addr(nil), status.TailscaleIPs...) - if telemetry == nil { - telemetry = &forwardTelemetry{limits: defaultForwardLimits} - } - f := newForwarder(ctx, telemetry) - defer f.Close() - for _, port := range ports { - if port.network == "tcp" { - listener, err := node.Listen("tcp", ":"+port.port) - if err != nil { - return fmt.Errorf("TCP listener %s: %w", port.port, err) - } - f.serveTCP(listener, port.target) - } else { - // tsnet requires an explicit IP for UDP. Bind both families so - // MagicDNS choosing IPv6 cannot bypass the advertised datapath. - for _, ip := range ips { - listener, err := node.ListenPacket("udp", net.JoinHostPort(ip.String(), port.port)) - if err != nil { - return fmt.Errorf("UDP listener %s: %w", port.port, err) - } - f.serveUDP(listener, port.target) - } - } - } - ready.Store(true) - if observe != nil { - observe(true) - } - ticker := time.NewTicker(poll) - defer ticker.Stop() - for { - select { - case <-ctx.Done(): - return nil - case err := <-f.failed: - return err - case <-ticker.C: - statusCtx, cancel := context.WithTimeout(ctx, 2*time.Second) - status, err := node.Status(statusCtx) - cancel() - healthy := err == nil && tailnetReady(status, tags) - ready.Store(healthy) - if observe != nil { - observe(healthy) - } - if err == nil && status != nil && !slices.Equal(status.TailscaleIPs, ips) { - return errors.New("tailnet addresses changed; recreating forwarding listeners") - } - } - } -} diff --git a/tunnel/tailscale_forward.go b/tunnel/tailscale_forward.go deleted file mode 100644 index 0d21ab4e0..000000000 --- a/tunnel/tailscale_forward.go +++ /dev/null @@ -1,288 +0,0 @@ -package main - -import ( - "context" - "errors" - "fmt" - "io" - "net" - "strconv" - "strings" - "sync" - "time" -) - -type forwardPort struct{ network, port, target string } - -// The operator supplies only advertised ports and this exact Service. No client -// packet can choose a destination, and this node never advertises subnet routes. -func tailscaleForwardPlan(cfg Config) ([]forwardPort, error) { - if cfg.GameServerName == "" || cfg.GameServerNamespace == "" || cfg.BackingServiceDNS != cfg.GameServerName+"."+cfg.GameServerNamespace+".svc" { - return nil, errors.New("tailscale target must be the GameServer's backing Service DNS") - } - entries := strings.Split(cfg.BackingServicePorts, ",") - if len(entries) > 32 { - return nil, errors.New("tailscale supports at most 32 advertised ports") - } - ports := make([]forwardPort, 0, len(entries)) - seen := map[string]bool{} - for _, entry := range entries { - parts := strings.Split(entry, ":") - if len(parts) != 3 || parts[0] == "" { - return nil, fmt.Errorf("tailscale port %q must be name:port:tcp or name:port:udp; update the operator and tunnel images together", entry) - } - port, err := strconv.Atoi(parts[1]) - if err != nil || port < 1 || port > 65535 { - return nil, fmt.Errorf("invalid Tailscale port %q", entry) - } - if parts[2] != "tcp" && parts[2] != "udp" { - return nil, fmt.Errorf("unsupported Tailscale protocol %q; only TCP and UDP can be forwarded", parts[2]) - } - key := parts[2] + ":" + strconv.Itoa(port) - if seen[key] { - return nil, fmt.Errorf("duplicate Tailscale listener %s", key) - } - seen[key] = true - ports = append(ports, forwardPort{network: parts[2], port: strconv.Itoa(port), target: net.JoinHostPort(cfg.BackingServiceDNS, strconv.Itoa(port))}) - } - return ports, nil -} - -type forwardLimits struct { - sessions, udpQueue int - idle, dial time.Duration -} - -// The budget is shared by all listeners, protocols and address families. -// By default 128 sessions, four queued UDP packets each and one 64KiB response -// buffer per UDP session bound memory independent of client fan-out. -var defaultForwardLimits = forwardLimits{sessions: 128, udpQueue: 4, idle: 30 * time.Second, dial: 5 * time.Second} - -type forwarder struct { - ctx context.Context - cancel context.CancelFunc - telemetry *forwardTelemetry - limits forwardLimits - slots chan struct{} - wg sync.WaitGroup - listeners []io.Closer // registered before Close; no concurrent additions - closeOnce sync.Once - failed chan error -} - -func newForwarder(ctx context.Context, telemetry *forwardTelemetry) *forwarder { - ctx, cancel := context.WithCancel(ctx) - limits := telemetry.limits - return &forwarder{telemetry: telemetry, ctx: ctx, cancel: cancel, limits: limits, slots: make(chan struct{}, limits.sessions), failed: make(chan error, 1)} -} - -func (f *forwarder) Close() { - f.closeOnce.Do(func() { - f.cancel() - for _, listener := range f.listeners { - _ = listener.Close() - } - f.wg.Wait() - }) -} - -func (f *forwarder) fail(err error) { - if f.ctx.Err() == nil { - select { - case f.failed <- err: - default: - } - } -} - -func (f *forwarder) acquire(protocol *flowCounts) bool { - select { - case f.slots <- struct{}{}: - protocol.active.Add(1) - return true - default: - protocol.rejected.Add(1) - return false - } -} - -func (f *forwarder) serveTCP(listener net.Listener, target string) { - f.listeners = append(f.listeners, listener) - f.wg.Add(1) - go func() { - defer f.wg.Done() - for { - client, err := listener.Accept() - if err != nil { - f.fail(fmt.Errorf("TCP listener: %w", err)) - return - } - if !f.acquire(&f.telemetry.tcp) { - _ = client.Close() - continue - } - f.wg.Add(1) - go func() { - defer f.wg.Done() - defer f.release(&f.telemetry.tcp) - f.proxyTCP(client, target) - }() - } - }() -} - -func (f *forwarder) proxyTCP(client net.Conn, target string) { - defer func() { _ = client.Close() }() - stopClient := context.AfterFunc(f.ctx, func() { _ = client.Close() }) - defer stopClient() - upstream, err := (&net.Dialer{Timeout: f.limits.dial}).DialContext(f.ctx, "tcp", target) - if err != nil { - return - } - defer func() { _ = upstream.Close() }() - stopUpstream := context.AfterFunc(f.ctx, func() { _ = upstream.Close() }) - defer stopUpstream() - // Activity in either direction refreshes each socket's idle timeout. - a := &idleConn{Conn: client, idle: 5 * time.Minute} - b := &idleConn{Conn: upstream, idle: 5 * time.Minute} - done := make(chan struct{}) - go func() { _, _ = io.CopyBuffer(b, a, make([]byte, 32*1024)); closeWrite(upstream); close(done) }() - _, _ = io.CopyBuffer(a, b, make([]byte, 32*1024)) - closeWrite(client) - _ = upstream.Close() - _ = client.Close() - <-done -} - -func closeWrite(conn net.Conn) { - if half, ok := conn.(interface{ CloseWrite() error }); ok { - _ = half.CloseWrite() - } -} - -type idleConn struct { - net.Conn - idle time.Duration -} - -func (c *idleConn) Read(p []byte) (int, error) { - _ = c.SetDeadline(time.Now().Add(c.idle)) - return c.Conn.Read(p) -} -func (c *idleConn) Write(p []byte) (int, error) { - _ = c.SetDeadline(time.Now().Add(c.idle)) - return c.Conn.Write(p) -} - -func (f *forwarder) release(protocol *flowCounts) { - protocol.active.Add(-1) - <-f.slots -} - -type udpPacket struct { - data []byte - received time.Time -} - -type udpForwardSession struct{ packets chan udpPacket } - -func (f *forwarder) enqueue(s *udpForwardSession, p []byte, received time.Time) { - // Only the receive loop enqueues. Check space before copying the payload. - if len(s.packets) == cap(s.packets) { - f.telemetry.queueDrops.Add(1) - return - } - s.packets <- udpPacket{data: append([]byte(nil), p...), received: received} -} - -func (f *forwarder) serveUDP(listener net.PacketConn, target string) { - f.listeners = append(f.listeners, listener) - f.wg.Add(1) - go func() { - defer f.wg.Done() - var mu sync.Mutex - sessions := map[string]*udpForwardSession{} - buf := make([]byte, 65536) - for { - n, peer, err := listener.ReadFrom(buf) - if err != nil { - f.fail(fmt.Errorf("UDP listener: %w", err)) - return - } - if n > 65507 || f.ctx.Err() != nil { - continue - } - received := time.Now() - key := peer.String() - mu.Lock() - session := sessions[key] - if session == nil && f.acquire(&f.telemetry.udp) { - session = &udpForwardSession{packets: make(chan udpPacket, f.limits.udpQueue)} - sessions[key] = session - f.wg.Add(1) - go func(session *udpForwardSession, peer net.Addr, key string) { - defer f.wg.Done() - defer func() { - mu.Lock() - delete(sessions, key) - f.release(&f.telemetry.udp) - mu.Unlock() - }() - f.proxyUDP(listener, peer, session.packets, target) - }(session, peer, key) - } - if session != nil { - f.enqueue(session, buf[:n], received) - } - mu.Unlock() - } - }() -} - -func (f *forwarder) proxyUDP(listener net.PacketConn, peer net.Addr, packets <-chan udpPacket, target string) { - upstream, err := (&net.Dialer{Timeout: f.limits.dial}).DialContext(f.ctx, "udp", target) - if err != nil { - return - } - stop := context.AfterFunc(f.ctx, func() { _ = upstream.Close() }) - defer stop() - done := make(chan struct{}) - _ = upstream.SetReadDeadline(time.Now().Add(f.limits.idle)) - go func() { - defer close(done) - buf := make([]byte, 65536) - for { - n, err := upstream.Read(buf) - if err != nil { - return - } - received := time.Now() - // Server-originated traffic is activity too, even when the client - // sends nothing after joining this UDP session. - _ = upstream.SetReadDeadline(time.Now().Add(f.limits.idle)) - if n <= 65507 { - _ = listener.SetWriteDeadline(time.Now().Add(f.limits.dial)) - if _, err := listener.WriteTo(buf[:n], peer); err != nil { - return - } - f.telemetry.toClient.observe(time.Since(received)) - } - } - }() - defer func() { _ = upstream.Close(); <-done }() - for { - select { - case <-f.ctx.Done(): - return - case <-done: - return - case packet := <-packets: - _ = upstream.SetWriteDeadline(time.Now().Add(f.limits.dial)) - _ = upstream.SetReadDeadline(time.Now().Add(f.limits.idle)) - if _, err := upstream.Write(packet.data); err != nil { - return - } - f.telemetry.toBackend.observe(time.Since(packet.received)) - } - } -} diff --git a/tunnel/tailscale_forward_test.go b/tunnel/tailscale_forward_test.go deleted file mode 100644 index ddf9fec11..000000000 --- a/tunnel/tailscale_forward_test.go +++ /dev/null @@ -1,277 +0,0 @@ -package main - -import ( - "context" - "encoding/json" - "io" - "net" - "net/http/httptest" - "strconv" - "strings" - "testing" - "time" - - "github.com/GameplanePanel/gameplane/tunnel/internal/relayload" -) - -func TestTailscaleForwardSaturationMetrics(t *testing.T) { - m := &forwardTelemetry{limits: forwardLimits{sessions: 1, udpQueue: 1}} - f := newForwarder(t.Context(), m) - defer f.Close() - if !f.acquire(&m.udp) || f.acquire(&m.tcp) { - t.Fatal("TCP accepted after UDP used the shared slot") - } - defer f.release(&m.udp) - session := &udpForwardSession{packets: make(chan udpPacket, 1)} - f.enqueue(session, []byte("first"), time.Now()) - f.enqueue(session, []byte("second"), time.Now()) - if p := <-session.packets; string(p.data) != "first" { - t.Fatal("dropped the queued datagram") - } - m.toBackend.observe(2 * time.Millisecond) - m.toClient.observe(200 * time.Microsecond) - w := httptest.NewRecorder() - relayMetrics(&relayHealth{forwarding: m}).ServeHTTP(w, httptest.NewRequestWithContext(t.Context(), "GET", "/metrics", nil)) - for _, expect := range []string{ - "gameplane_tunnel_forward_metrics_supported 1", - "gameplane_tunnel_active_flows{protocol=\"udp\"} 1", - "gameplane_tunnel_flow_rejections_total{protocol=\"tcp\"} 1", - "gameplane_tunnel_udp_queue_drops_total 1", - "gameplane_tunnel_udp_forward_duration_seconds_bucket{direction=\"to_backend\",le=\"0.001\"} 0", - "gameplane_tunnel_udp_forward_duration_seconds_bucket{direction=\"to_backend\",le=\"0.005\"} 1", - "gameplane_tunnel_udp_forwarded_packets_total{direction=\"to_client\"} 1", - } { - if !strings.Contains(w.Body.String(), expect+"\n") { - t.Errorf("scrape missing %s", expect) - } - } -} - -// Shared workload for CI CPU/allocation profiles and external provider trials. -// Loopback isolates the supervisor's forwarding path from tsnet and WAN cost. -func TestRelayLoadForwardingProfile(t *testing.T) { - ctx := t.Context() - backend, err := (&net.ListenConfig{}).ListenPacket(ctx, "udp", "127.0.0.1:0") - if err != nil { - t.Fatal(err) - } - defer backend.Close() - go func() { - buf := make([]byte, 1500) - for { - n, peer, err := backend.ReadFrom(buf) - if err != nil { - return - } - _, _ = backend.WriteTo(buf[:n], peer) - } - }() - listener, err := (&net.ListenConfig{}).ListenPacket(ctx, "udp", "127.0.0.1:0") - if err != nil { - t.Fatal(err) - } - f := newForwarder(ctx, &forwardTelemetry{limits: defaultForwardLimits}) - defer f.Close() - f.serveUDP(listener, backend.LocalAddr().String()) - profile := relayload.Profile{Clients: 32, Hz: 128, Bytes: 256, Seconds: 2} - for _, endpoint := range []string{backend.LocalAddr().String(), listener.LocalAddr().String()} { - result, err := relayload.Measure(ctx, endpoint, profile) - if err != nil || result.Received == 0 { - t.Fatalf("no measured replies: %+v %v", result, err) - } - raw, err := json.Marshal(result) - if err != nil { - t.Fatal(err) - } - t.Log(string(raw)) - } -} - -func TestTailscaleForwardPlanRestrictsDestinations(t *testing.T) { - cfg := Config{GameServerName: "game", GameServerNamespace: "games", BackingServiceDNS: "game.games.svc", BackingServicePorts: "java:25565:tcp,bedrock:19132:udp"} - ports, err := tailscaleForwardPlan(cfg) - if err != nil || len(ports) != 2 || ports[0].target != "game.games.svc:25565" || ports[1].network != "udp" { - t.Fatalf("plan: %+v, %v", ports, err) - } - for _, bad := range []string{"other.games.svc", "127.0.0.1", "game.games.svc:80", "http://game.games.svc"} { - cfg.BackingServiceDNS = bad - if _, err := tailscaleForwardPlan(cfg); err == nil { - t.Fatalf("accepted unrelated target %q", bad) - } - } - cfg.BackingServiceDNS = "game.games.svc" - for _, bad := range []string{"game:25565", "game:0:tcp", "game:65536:udp", "game:22:sctp", "game:22:tcp,other:22:tcp", strings.Repeat("p:1:tcp,", 33)} { - cfg.BackingServicePorts = bad - if _, err := tailscaleForwardPlan(cfg); err == nil { - t.Fatalf("accepted invalid ports %q", bad) - } - } -} - -func TestTailscaleTCPForwardAndShutdown(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - backend, err := (&net.ListenConfig{}).Listen(ctx, "tcp", "127.0.0.1:0") - if err != nil { - t.Fatal(err) - } - defer backend.Close() - go func() { - c, e := backend.Accept() - if e == nil { - defer c.Close() - _, _ = io.Copy(c, c) - } - }() - listener, err := (&net.ListenConfig{}).Listen(ctx, "tcp", "127.0.0.1:0") - if err != nil { - t.Fatal(err) - } - f := newForwarder(ctx, &forwardTelemetry{limits: forwardLimits{sessions: 2, udpQueue: 2, idle: time.Second, dial: time.Second}}) - f.serveTCP(listener, backend.Addr().String()) - defer f.Close() - conn, err := (&net.Dialer{}).DialContext(ctx, "tcp", listener.Addr().String()) - if err != nil { - t.Fatal(err) - } - defer conn.Close() - _ = conn.SetDeadline(time.Now().Add(3 * time.Second)) - _, _ = conn.Write([]byte("gameplay")) - buf := make([]byte, 8) - if _, err := io.ReadFull(conn, buf); err != nil || string(buf) != "gameplay" { - t.Fatalf("TCP reply %q: %v", buf, err) - } - f.Close() - if _, err := conn.Read(buf); err == nil { - t.Fatal("connection survived forwarding shutdown") - } -} - -func TestTailscaleUDPForwardIsolationLimitAndExpiry(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - backend, err := (&net.ListenConfig{}).ListenPacket(ctx, "udp", "127.0.0.1:0") - if err != nil { - t.Fatal(err) - } - defer backend.Close() - go func() { - buf := make([]byte, 65536) - for { - n, peer, e := backend.ReadFrom(buf) - if e != nil { - return - } - _, _ = backend.WriteTo(buf[:n], peer) - } - }() - listener, err := (&net.ListenConfig{}).ListenPacket(ctx, "udp", "127.0.0.1:0") - if err != nil { - t.Fatal(err) - } - f := newForwarder(ctx, &forwardTelemetry{limits: forwardLimits{sessions: 2, udpQueue: 2, idle: time.Second, dial: time.Second}}) - f.serveUDP(listener, backend.LocalAddr().String()) - defer f.Close() - var clients []net.Conn - for i := 0; i < 3; i++ { - c, e := (&net.Dialer{}).DialContext(ctx, "udp", listener.LocalAddr().String()) - if e != nil { - t.Fatal(e) - } - defer c.Close() - clients = append(clients, c) - } - for i := 0; i < 2; i++ { - _ = clients[i].SetDeadline(time.Now().Add(time.Second)) - payload := "peer-" + strconv.Itoa(i) - _, _ = clients[i].Write([]byte(payload)) - buf := make([]byte, 32) - n, e := clients[i].Read(buf) - if e != nil || string(buf[:n]) != payload { - t.Fatalf("peer %d reply %q: %v", i, buf[:n], e) - } - } - _ = clients[2].SetDeadline(time.Now().Add(50 * time.Millisecond)) - _, _ = clients[2].Write([]byte("over limit")) - if _, err := clients[2].Read(make([]byte, 32)); err == nil { - t.Fatal("UDP session limit not enforced") - } - if got := f.telemetry.udp.rejected.Load(); got != 1 { - t.Fatalf("one client-side loss, got %d rejected UDP datagrams", got) - } - if got := f.telemetry.udp.active.Load(); got != 2 { - t.Fatalf("active UDP sessions = %d", got) - } - deadline := time.Now().Add(3 * time.Second) - for len(f.slots) != 0 && time.Now().Before(deadline) { - time.Sleep(10 * time.Millisecond) - } - if len(f.slots) != 0 { - t.Fatal("idle UDP sessions were not reclaimed") - } - _ = clients[2].SetDeadline(time.Now().Add(time.Second)) - _, _ = clients[2].Write([]byte("new session")) - buf := make([]byte, 32) - n, err := clients[2].Read(buf) - if err != nil || string(buf[:n]) != "new session" { - t.Fatalf("session after expiry: %q %v", buf[:n], err) - } - f.Close() - if len(f.slots) != 0 || f.telemetry.udp.active.Load() != 0 { - t.Fatal("shutdown leaked sessions") - } -} - -func TestTailscaleUDPServerTrafficKeepsSessionAlive(t *testing.T) { - t.Parallel() - ctx, cancel := context.WithCancel(t.Context()) - defer cancel() - backend, err := (&net.ListenConfig{}).ListenPacket(ctx, "udp", "127.0.0.1:0") - if err != nil { - t.Fatal(err) - } - defer backend.Close() - listener, err := (&net.ListenConfig{}).ListenPacket(ctx, "udp", "127.0.0.1:0") - if err != nil { - t.Fatal(err) - } - f := newForwarder(ctx, &forwardTelemetry{limits: forwardLimits{sessions: 1, udpQueue: 1, idle: 400 * time.Millisecond, dial: time.Second}}) - f.serveUDP(listener, backend.LocalAddr().String()) - defer f.Close() - client, err := (&net.Dialer{}).DialContext(ctx, "udp", listener.LocalAddr().String()) - if err != nil { - t.Fatal(err) - } - defer client.Close() - if _, err := client.Write([]byte("join")); err != nil { - t.Fatal(err) - } - _ = backend.SetReadDeadline(time.Now().Add(3 * time.Second)) - buffer := make([]byte, 32) - _, peer, err := backend.ReadFrom(buffer) - if err != nil { - t.Fatal(err) - } - // No more client packets: server updates alone must extend the same session - // for several idle windows, then complete silence must still reclaim it. - ticker := time.NewTicker(80 * time.Millisecond) - defer ticker.Stop() - for i := 0; i < 15; i++ { - <-ticker.C - if _, err := backend.WriteTo([]byte("update"), peer); err != nil { - t.Fatal(err) - } - _ = client.SetReadDeadline(time.Now().Add(time.Second)) - n, err := client.Read(buffer) - if err != nil || string(buffer[:n]) != "update" { - t.Fatalf("server update %d lost: %q %v", i, buffer[:n], err) - } - } - deadline := time.Now().Add(3 * time.Second) - for len(f.slots) != 0 && time.Now().Before(deadline) { - time.Sleep(10 * time.Millisecond) - } - if len(f.slots) != 0 { - t.Fatal("silent session did not expire") - } -} diff --git a/tunnel/tailscale_retry_test.go b/tunnel/tailscale_retry_test.go deleted file mode 100644 index 0db8999b3..000000000 --- a/tunnel/tailscale_retry_test.go +++ /dev/null @@ -1,150 +0,0 @@ -package main - -import ( - "context" - "errors" - "sync/atomic" - "testing" - "time" -) - -func TestTailnetRetryHealthRequiresContinuousConfirmation(t *testing.T) { - t.Parallel() - for _, scenario := range []string{"short session", "healthy interval", "offline interruption", "stale gap"} { - t.Run(scenario, func(t *testing.T) { - t.Parallel() - backoff := &exponentialBackoff{} - for _, want := range []time.Duration{1, 2, 4, 8, 16, 32, 64, 128, 256, 300, 300} { - if got := backoff.next(); got != want*time.Second { - t.Fatalf("failure delay=%v, want %v", got, want*time.Second) - } - } - history := &relayHealth{} - start := time.Unix(100, 0) - now := start - observer := tailnetRetryObserver(history, backoff, func() time.Time { return now }) - observe := func(seconds int, healthy bool) { - now = start.Add(time.Duration(seconds) * time.Second) - observer(healthy) - } - for seconds := 0; seconds <= 58; seconds += 2 { - observe(seconds, true) - } - if got := backoff.next(); got != 300*time.Second { - t.Fatalf("short healthy session reset delay: %v", got) - } - switch scenario { - case "short session": - observe(59, false) - if got := backoff.next(); got != 300*time.Second { - t.Fatalf("session exit reset delay: %v", got) - } - return - case "healthy interval": - observe(60, true) - case "offline interruption": - observe(60, false) - for seconds := 62; seconds <= 120; seconds += 2 { - observe(seconds, true) - } - if got := backoff.next(); got != 300*time.Second { - t.Fatalf("offline interruption counted as healthy time: %v", got) - } - observe(122, true) - case "stale gap": - // Exactly ten seconds without an observation breaks continuity. - for seconds := 68; seconds <= 126; seconds += 2 { - observe(seconds, true) - } - if got := backoff.next(); got != 300*time.Second { - t.Fatalf("stale observation gap counted as healthy time: %v", got) - } - observe(128, true) - } - observe(130, false) - if got := backoff.next(); got != time.Second { - t.Fatalf("confirmed healthy interval did not reset: %v", got) - } - if got := backoff.next(); got != 2*time.Second { - t.Fatalf("subsequent failure did not escalate: %v", got) - } - }) - } -} - -func TestTailnetRetryObserverConfirmedSessionClosesListeners(t *testing.T) { - t.Parallel() - ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) - defer cancel() - node := &fakeTailnetNode{status: onlineTailnet()} - backoff := &exponentialBackoff{} - for i := 0; i < 12; i++ { - backoff.next() - } - history := &relayHealth{} - var ready atomic.Bool - confirmed := 0 - start := time.Unix(100, 0) - observe := tailnetRetryObserver(history, backoff, func() time.Time { - return start.Add(time.Duration(confirmed) * 2 * time.Second) - }) - err := serveTailnetObserved(ctx, node, nil, []forwardPort{{network: "tcp", port: "25565", target: "127.0.0.1:1"}}, &ready, time.Millisecond, nil, func(healthy bool) { - observe(healthy) - if healthy { - confirmed++ - if confirmed == 31 { - cancel() - } - } - }) - if err != nil { - t.Fatal(err) - } - if confirmed < 31 || ready.Load() { - t.Fatalf("confirmed=%d ready=%v", confirmed, ready.Load()) - } - if got := backoff.next(); got != time.Second { - t.Fatalf("confirmed tailnet health did not reset backoff: %v", got) - } - for _, listener := range node.listeners { - if _, err := listener.Accept(); err == nil { - t.Fatal("listener survives cancellation") - } - } -} - -func TestTailnetFailedAttemptsCannotResetRetryEscalation(t *testing.T) { - t.Parallel() - for _, scenario := range []string{"authentication", "denied tag", "listener"} { - t.Run(scenario, func(t *testing.T) { - t.Parallel() - node := &fakeTailnetNode{status: onlineTailnet()} - tags := []string{"tag:game"} - switch scenario { - case "authentication": - node.upErr = errors.New("unauthorized") - case "denied tag": - tags = []string{"tag:ungranted"} - case "listener": - node.listenErr = true - } - backoff := &exponentialBackoff{} - backoff.next() - history := &relayHealth{} - var ready atomic.Bool - confirmed := false - observe := tailnetRetryObserver(history, backoff, func() time.Time { return time.Unix(100, 0) }) - err := serveTailnetObserved(t.Context(), node, tags, []forwardPort{{network: "udp", port: "19132", target: "127.0.0.1:1"}}, &ready, time.Millisecond, nil, func(healthy bool) { - confirmed = confirmed || healthy - observe(healthy) - }) - snapshot := history.snapshot(time.Unix(100, 0)) - if err == nil || ready.Load() || confirmed || snapshot.Ready { - t.Fatalf("failed attempt reported health: err=%v ready=%v confirmed=%v snapshot=%+v", err, ready.Load(), confirmed, snapshot) - } - if got := backoff.next(); got != 2*time.Second { - t.Fatalf("failed attempt reset delay: %v", got) - } - }) - } -} diff --git a/tunnel/tailscale_test.go b/tunnel/tailscale_test.go deleted file mode 100644 index 872eeecc7..000000000 --- a/tunnel/tailscale_test.go +++ /dev/null @@ -1,384 +0,0 @@ -package main - -import ( - "context" - "errors" - "net" - "net/http" - "net/http/httptest" - "net/netip" - "strings" - "sync" - "sync/atomic" - "testing" - "time" - - "tailscale.com/ipn/ipnstate" - "tailscale.com/types/views" -) - -func TestTailscaleServerPreservesIdentityAndTags(t *testing.T) { - cfg := Config{TailscaleHostname: "my-game", TailscaleTags: "game,tag:game,tag:friends"} - s, tags, err := tailscaleServer(cfg, "test-auth-key") - if err != nil { - t.Fatal(err) - } - if s.Hostname != "my-game" || s.AuthKey != "test-auth-key" || s.Dir != tailscaleStateDir || s.Ephemeral || len(tags) != 2 || !equalArgs(tags, s.AdvertiseTags) { - t.Fatalf("server lost identity or tags: %+v", tags) - } - cfg.TailscaleTags = "tag:bad tag" - if _, _, err := tailscaleServer(cfg, "key"); err == nil { - t.Fatal("invalid tags silently dropped") - } - cfg.TailscaleTags = "" - cfg.TailscaleHostname = "" - if _, _, err := tailscaleServer(cfg, "key"); err == nil { - t.Fatal("empty hostname accepted") - } - cfg.TailscaleHostname = "my-game" - if _, _, err := tailscaleServer(cfg, ""); err == nil { - t.Fatal("empty auth key accepted") - } -} - -func onlineTailnet() *ipnstate.Status { - tags := views.SliceOf([]string{"tag:game"}) - return &ipnstate.Status{BackendState: "Running", TailscaleIPs: []netip.Addr{netip.MustParseAddr("100.64.0.1"), netip.MustParseAddr("fd7a:115c:a1e0::1")}, Self: &ipnstate.PeerStatus{Online: true, Tags: &tags}} -} - -func TestTailscaleHostnameMustMatchAdvertisedEndpoint(t *testing.T) { - status := onlineTailnet() - status.Self.DNSName = "game.tailnet.ts.net." - if _, err := checkTailnetHostname(status, "game"); err != nil { - t.Fatal(err) - } - status.Self.DNSName = "game-1.tailnet.ts.net." - if _, err := checkTailnetHostname(status, "game"); err == nil { - t.Fatal("colliding hostname advertised as ready") - } -} - -type fakeTailnetNode struct { - mu sync.Mutex - status *ipnstate.Status - upErr error - upCalls int - listenErr bool - listened []string - listeners []net.Listener - packets []net.PacketConn -} - -func (f *fakeTailnetNode) Up(ctx context.Context) (*ipnstate.Status, error) { - f.upCalls++ - if f.upErr != nil { - return nil, f.upErr - } - return f.Status(ctx) -} -func (f *fakeTailnetNode) Status(_ context.Context) (*ipnstate.Status, error) { - f.mu.Lock() - defer f.mu.Unlock() - return f.status, nil -} -func (f *fakeTailnetNode) Listen(network, addr string) (net.Listener, error) { - f.listened = append(f.listened, network+addr) - l, err := (&net.ListenConfig{}).Listen(context.Background(), network, "127.0.0.1:0") - if err == nil { - f.listeners = append(f.listeners, l) - } - return l, err -} -func (f *fakeTailnetNode) ListenPacket(network, addr string) (net.PacketConn, error) { - f.listened = append(f.listened, network+addr) - if f.listenErr { - return nil, errors.New("bind failed") - } - l, err := (&net.ListenConfig{}).ListenPacket(context.Background(), network, "127.0.0.1:0") - if err == nil { - f.packets = append(f.packets, l) - } - return l, err -} - -func awaitTailnetReady(t *testing.T, ready *atomic.Bool, want bool) { - t.Helper() - deadline := time.Now().Add(3 * time.Second) - for ready.Load() != want && time.Now().Before(deadline) { - time.Sleep(time.Millisecond) - } - if ready.Load() != want { - t.Fatalf("readiness=%v want %v", ready.Load(), want) - } -} - -func TestTailnetReadinessTracksAuthenticationListenersAndDisconnect(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - node := &fakeTailnetNode{status: onlineTailnet()} - var ready atomic.Bool - ports := []forwardPort{{network: "tcp", port: "25565", target: "127.0.0.1:1"}, {network: "udp", port: "19132", target: "127.0.0.1:2"}} - done := make(chan error, 1) - go func() { done <- serveTailnet(ctx, node, []string{"tag:game"}, ports, &ready, time.Millisecond) }() - awaitTailnetReady(t, &ready, true) - if len(node.listened) != 3 || node.listened[0] != "tcp:25565" || node.listened[1] != "udp100.64.0.1:19132" || node.listened[2] != "udp[fd7a:115c:a1e0::1]:19132" { - t.Fatalf("unexpected port/family exposure: %v", node.listened) - } - node.mu.Lock() - offline := onlineTailnet() - offline.Self.Online = false - node.status = offline - node.mu.Unlock() - awaitTailnetReady(t, &ready, false) - node.mu.Lock() - node.status = onlineTailnet() - node.mu.Unlock() - awaitTailnetReady(t, &ready, true) - cancel() - select { - case err := <-done: - if err != nil { - t.Fatal(err) - } - case <-time.After(time.Second): - t.Fatal("shutdown stalled") - } - if ready.Load() { - t.Fatal("readiness survives shutdown") - } - for _, listener := range node.listeners { - if _, err := listener.Accept(); err == nil { - t.Fatal("listener survives shutdown") - } - } -} - -func TestTailnetFailuresNeverBecomeReady(t *testing.T) { - for _, scenario := range []string{"authentication", "denied tag", "listener"} { - t.Run(scenario, func(t *testing.T) { - node := &fakeTailnetNode{status: onlineTailnet()} - tags := []string{"tag:game"} - switch scenario { - case "authentication": - node.upErr = errors.New("unauthorized") - case "denied tag": - tags = []string{"tag:ungranted"} - case "listener": - node.listenErr = true - } - var ready atomic.Bool - err := serveTailnet(context.Background(), node, tags, []forwardPort{{network: "tcp", port: "1", target: "127.0.0.1:1"}, {network: "udp", port: "2", target: "127.0.0.1:2"}}, &ready, time.Millisecond) - if err == nil || ready.Load() { - t.Fatalf("failure became ready: %v", err) - } - if node.upCalls != 1 { - t.Fatalf("failed registration retried without requested tags: %d attempts", node.upCalls) - } - for _, listener := range node.listeners { - if _, err := listener.Accept(); err == nil { - t.Fatal("partially opened listener leaked") - } - } - }) - } -} - -func TestTailscaleRetryBackoffCancelsImmediately(t *testing.T) { - t.Parallel() - ctx, cancel := context.WithCancel(t.Context()) - healthDone := make(chan error) - done := make(chan error, 1) - go func() { done <- waitTailnetRetry(ctx, healthDone, time.Hour) }() - cancel() - select { - case err := <-done: - if !errors.Is(err, context.Canceled) { - t.Fatalf("cancelled retry: %v", err) - } - case <-time.After(time.Second): - t.Fatal("retry backoff ignored cancellation") - } -} - -func TestTailnetListenerFailureClearsReady(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - node := &fakeTailnetNode{status: onlineTailnet()} - var ready atomic.Bool - done := make(chan error, 1) - go func() { - done <- serveTailnet(ctx, node, nil, []forwardPort{{network: "tcp", port: "25565", target: "127.0.0.1:1"}}, &ready, time.Millisecond) - }() - awaitTailnetReady(t, &ready, true) - _ = node.listeners[0].Close() - select { - case err := <-done: - if err == nil { - t.Fatal("failed listener was not reported") - } - case <-time.After(time.Second): - t.Fatal("failed listener did not stop forwarding") - } - if ready.Load() { - t.Fatal("failed forwarding listener still ready") - } -} - -type gatedTailnetNode struct { - *fakeTailnetNode - started chan struct{} - release chan struct{} -} - -func (n *gatedTailnetNode) Up(ctx context.Context) (*ipnstate.Status, error) { - close(n.started) - select { - case <-ctx.Done(): - return nil, ctx.Err() - case <-n.release: - return n.fakeTailnetNode.Up(ctx) - } -} - -func TestTailnetFailedAttemptRemainsKnownDuringRetry(t *testing.T) { - ctx, cancel := context.WithCancel(t.Context()) - defer cancel() - history := &relayHealth{} - handler := relayHealthHandler(history) - ports := []forwardPort{{network: "tcp", port: "25565", target: "127.0.0.1:1"}} - node := &fakeTailnetNode{status: onlineTailnet()} - var ready atomic.Bool - done := make(chan error, 1) - go func() { - done <- serveTailnetWithHealth(ctx, node, nil, ports, &ready, time.Millisecond, history, nil) - }() - awaitTailnetReady(t, &ready, true) - if err := node.listeners[0].Close(); err != nil { - t.Fatal(err) - } - select { - case err := <-done: - if err == nil { - t.Fatal("failed listener was not reported") - } - case <-time.After(time.Second): - t.Fatal("failed attempt did not finish") - } - assertUnavailable := func() { - t.Helper() - // Advance beyond the maximum retry delay without sleeping: absence of - // a serving attempt is a local fact, not a stale provider observation. - if got := history.snapshot(time.Now().Add(6 * time.Minute)); got.Connection != "unavailable" || got.Ready { - t.Fatalf("retry forgot the known outage: %+v", got) - } - rec := httptest.NewRecorder() - handler.ServeHTTP(rec, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/readyz", nil)) - if rec.Code != http.StatusServiceUnavailable { - t.Fatalf("failed attempt readyz=%d", rec.Code) - } - metrics := httptest.NewRecorder() - handler.ServeHTTP(metrics, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/metrics", nil)) - for _, want := range []string{"gameplane_tunnel_connection_known 1\n", "gameplane_tunnel_connected 0\n", "gameplane_tunnel_ready 0\n"} { - if !strings.Contains(metrics.Body.String(), want) { - t.Fatalf("failed attempt missing %q: %s", want, metrics.Body.String()) - } - } - if strings.Contains(metrics.Body.String(), "gameplane_tunnel_observation_timestamp_seconds") { - t.Fatalf("supervisor outage invented a provider observation timestamp: %s", metrics.Body.String()) - } - } - assertUnavailable() - - // A new registration attempt must retain that state until forwarding is - // actually established, even if its Up call takes longer than the lease. - retry := &gatedTailnetNode{fakeTailnetNode: &fakeTailnetNode{status: onlineTailnet()}, started: make(chan struct{}), release: make(chan struct{})} - go func() { - done <- serveTailnetWithHealth(ctx, retry, nil, ports, &ready, time.Millisecond, history, nil) - }() - select { - case <-retry.started: - case <-time.After(time.Second): - t.Fatal("retry did not start") - } - assertUnavailable() - close(retry.release) - awaitTailnetReady(t, &ready, true) - deadline := time.Now().Add(time.Second) - for !history.snapshot(time.Now()).Ready && time.Now().Before(deadline) { - time.Sleep(time.Millisecond) - } - if got := history.snapshot(time.Now()); got.Connection != "connected" || !got.Ready { - t.Fatalf("recovered forwarding did not restore health: %+v", got) - } - if got := history.snapshot(time.Now().Add(2 * healthStaleAfter)); got.Connection != "unknown" || got.Ready { - t.Fatalf("live provider observations no longer expire: %+v", got) - } - cancel() - select { - case err := <-done: - if err != nil { - t.Fatal(err) - } - case <-time.After(time.Second): - t.Fatal("retry shutdown stalled") - } -} - -func TestTailnetHealthNeedsForwardingReadiness(t *testing.T) { - history := &relayHealth{} - handler := relayHealthHandler(history) - for _, check := range []struct { - path string - ready bool - want int - }{{"/readyz", false, 503}, {"/healthz", false, 200}, {"/readyz", true, 200}, {"/readyz", false, 503}} { - history.observe(time.Now(), tailnetHealthObservation(check.ready), nil) - rec := httptest.NewRecorder() - handler.ServeHTTP(rec, httptest.NewRequestWithContext(context.Background(), http.MethodGet, check.path, nil)) - if rec.Code != check.want { - t.Fatalf("%s=%d want%d", check.path, rec.Code, check.want) - } - } - metrics := httptest.NewRecorder() - handler.ServeHTTP(metrics, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/metrics", nil)) - for _, want := range []string{"gameplane_tunnel_connection_known 1\n", "gameplane_tunnel_connected 0\n", "gameplane_tunnel_ready 0\n"} { - if !strings.Contains(metrics.Body.String(), want) { - t.Fatalf("confirmed tailnet failure missing %q: %s", want, metrics.Body.String()) - } - } -} - -func TestTailnetConfirmedObservationsResetRetryEscalation(t *testing.T) { - t.Parallel() - ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) - defer cancel() - node := &fakeTailnetNode{status: onlineTailnet()} - backoff := &exponentialBackoff{} - for i := 0; i < 12; i++ { - backoff.next() - } - history := &relayHealth{} - var ready atomic.Bool - confirmed := 0 - start := time.Unix(100, 0) - err := serveTailnetObserved(ctx, node, nil, []forwardPort{{network: "tcp", port: "25565", target: "127.0.0.1:1"}}, &ready, time.Millisecond, nil, func(healthy bool) { - if !healthy { - history.observe(start.Add(time.Duration(confirmed)*healthPollInterval), relayObservation{Connection: "unknown"}, backoff) - return - } - history.observe(start.Add(time.Duration(confirmed)*healthPollInterval), relayObservation{Connection: "connected", Forwards: true, Assigned: true}, backoff) - confirmed++ - if time.Duration(confirmed-1)*healthPollInterval >= healthyResetAfter { - cancel() - } - }) - if err != nil { - t.Fatal(err) - } - if confirmed < 31 || ready.Load() { - t.Fatalf("confirmed=%d ready=%v", confirmed, ready.Load()) - } - if got := backoff.next(); got != time.Second { - t.Fatalf("confirmed tailnet health did not reset backoff: %v", got) - } -} From eec775995be3e68cd4413f9e1adbe18a1a44eebd Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 00:32:51 +0000 Subject: [PATCH 2/8] docs: describe the split component submodules and drop svcutil AGENTS.md, README, contributing, dependencies, layout, agent and architecture docs, the ci-triager agent, the submodule-bump skill and CodeRabbit path rules now describe audit-syslog-bridge, tunnel and capture-sidecar as submodules like mcp-server, with hack/submodules.sh and the shared go-component workflow. Links into the moved folders that the doc gates audit point at the component repos on GitHub. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Claude --- .claude/agents/ci-triager.md | 7 +++-- .claude/skills/submodule-bump/SKILL.md | 8 +++--- .coderabbit.yaml | 4 +-- AGENTS.md | 24 ++++++++-------- FEATURES.md | 2 +- README.md | 18 ++++++------ docs/agent-architecture.md | 7 ++--- docs/architecture.md | 2 +- docs/contributing.md | 27 ++++++++---------- docs/dependencies.md | 39 ++++++++++---------------- docs/install.md | 2 +- docs/layout.md | 9 +++--- docs/relay-health.md | 6 ++-- 13 files changed, 70 insertions(+), 85 deletions(-) diff --git a/.claude/agents/ci-triager.md b/.claude/agents/ci-triager.md index a43fe35b6..9f79f6ffe 100644 --- a/.claude/agents/ci-triager.md +++ b/.claude/agents/ci-triager.md @@ -37,13 +37,14 @@ gh pr view - `capture-sidecar-setcap-proof` → verifies file capabilities survived the multi-stage Dockerfile (Go modules only, uses sudo/tar/getcap) **Unit + lint stage**: -- `lint` (matrix: netguard, gameaction, gameproto, operator, api, agent, sentinel, audit-syslog-bridge, telemetry-receiver, capture-sidecar, svcutil, tunnel, test/e2e) +- `lint` (matrix: netguard, gameaction, gameproto, operator, api, agent, sentinel, telemetry-receiver, test/e2e) - Runs golangci-lint (with `envtest` tag for operator/api, `e2e` tag for test/e2e), checks specs compliance (once per run on netguard matrix entry) - Coverage thresholds per module (from CLAUDE.md rule 11): - - netguard: 91%, gameaction: 91%, gameproto: 90%, operator: 72%, api: 80%, agent: 90%, audit-syslog-bridge: 70%, telemetry-receiver: 70%, sentinel: 70%, capture-sidecar: 70%, svcutil: 90%, tunnel: 70% -- `go` (matrix: 15 modules × 2 archs [amd64, arm64]) + - netguard: 91%, gameaction: 91%, gameproto: 90%, operator: 72%, api: 80%, agent: 90%, telemetry-receiver: 70%, sentinel: 70% +- `go` (matrix: 11 modules × 2 archs [amd64, arm64]) - Unit tests + envtest (operator/api only) + coverage profile merge + threshold gate - Arm64 runs on `ubuntu-24.04-arm`; amd64 on `ubuntu-latest` +- Split components (mcp-server, audit-syslog-bridge, tunnel, capture-sidecar) are linted/tested in their own repos via `.github/workflows/go-component.yaml`; here `submodule freshness` also runs `hack/submodules.sh check`. - `web` → eslint, build, vitest + coverage (lines 92%, functions 76%, branches 82%, statements 92%), reports to commit status - `web-e2e-mock` → Playwright mock tests (msw-mocked API) diff --git a/.claude/skills/submodule-bump/SKILL.md b/.claude/skills/submodule-bump/SKILL.md index ff89fae08..c0757a3a4 100644 --- a/.claude/skills/submodule-bump/SKILL.md +++ b/.claude/skills/submodule-bump/SKILL.md @@ -1,9 +1,9 @@ --- name: submodule-bump -description: "Use after a modules or website submodule PR has merged to its main branch, to bump the submodule pointer in the main Gameplane repo. Takes one argument: modules, website or mcp-server." +description: "Use after a modules, website or component submodule PR has merged to its main branch, to bump the submodule pointer in the main Gameplane repo. Takes one argument: modules, website, mcp-server, audit-syslog-bridge, tunnel or capture-sidecar." --- -Argument: `modules`, `website` or `mcp-server`. From `.gitmodules`: `modules` is GameplanePanel/module (branch `main`), `website` is GameplanePanel/website (branch `main`, has its own CLAUDE.md and AGENTS.md), `mcp-server` is GameplanePanel/mcp (branch `main`). +Argument: `modules`, `website`, or a component submodule from `.gitmodules` (`mcp-server`, `audit-syslog-bridge`, `tunnel`, `capture-sidecar`). From `.gitmodules`: `modules` is GameplanePanel/module (branch `main`), `website` is GameplanePanel/website (branch `main`, has its own CLAUDE.md and AGENTS.md). Repo mapping: `mcp-server` -> GameplanePanel/mcp; every other component -> GameplanePanel/ (branch `main`). ## Preconditions @@ -11,7 +11,7 @@ Argument: `modules`, `website` or `mcp-server`. From `.gitmodules`: `modules` is ```sh gh pr view --repo GameplanePanel/module --json state,mergeCommit ``` - For website, use `--repo GameplanePanel/website`; for mcp-server use `--repo GameplanePanel/mcp`. Stop unless `state` is `MERGED`. + For website, use `--repo GameplanePanel/website`; for mcp-server use `--repo GameplanePanel/mcp`; for other components use `--repo GameplanePanel/`. Stop unless `state` is `MERGED`. 2. Check for a pending bump owned by another thread: ```sh gh pr list --repo GameplanePanel/Gameplane --state open --search "bump submodule" @@ -60,7 +60,7 @@ Argument: `modules`, `website` or `mcp-server`. From `.gitmodules`: `modules` is 9. Open the PR with a short Summary (the submodule PRs included) and a Test plan. Labels: - `modules`: `type: chore` + `area: modules` - `website`: `type: docs` + `area: shared` - - `mcp-server`: `type: chore` + `area: optional-components` + - `mcp-server`, `audit-syslog-bridge`, `tunnel`, `capture-sidecar`: `type: chore` + `area: optional-components` Add them via REST, as in `ship-branch` step 7: ```sh diff --git a/.coderabbit.yaml b/.coderabbit.yaml index 0b4067122..52341aa36 100644 --- a/.coderabbit.yaml +++ b/.coderabbit.yaml @@ -262,9 +262,9 @@ reviews: - label: "area: specs" instructions: Apply when changes touch specs/ or spec.md files (specs/done_008-hardened-github-actions/, design contracts, decision records). - label: "area: shared" - instructions: Apply when changes touch shared Go packages (netguard/, gameaction/, gameproto/, svcutil/, telemetryschema/) used by operator, api, agent, and telemetry-receiver. + instructions: Apply when changes touch shared Go packages (netguard/, gameaction/, gameproto/, telemetryschema/) used by operator, api, agent, and telemetry-receiver. - label: "area: optional-components" - instructions: Apply when changes touch optional or sidecar components (sentinel/, capture-sidecar/, mcp-server/ (submodule, pointer bumps only), tunnel/, audit-syslog-bridge/, telemetry-receiver/). + instructions: Apply when changes touch optional or sidecar components (sentinel/, telemetry-receiver/, and the submodules capture-sidecar/, mcp-server/, tunnel/, audit-syslog-bridge/ (pointer bumps only)). - label: "breaking" instructions: Apply when the PR introduces a breaking change (CRD schema incompatibility, REST API contract change, Helm chart value renamed/removed, database migration backward-incompatible). diff --git a/AGENTS.md b/AGENTS.md index 55a0abe6e..6fdc0d420 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -33,13 +33,12 @@ operator/ controller-runtime operator api/ REST + WebSocket gateway (chi); cmd/main.go: `serve`, `bootstrap-admin` internal/{handlers,auth,db,kube,notify,rbac,ws}/ agent/ in-pod sidecar; internal/{auth,console,files,heartbeat,logs,players,rcon,quiesce}/ -audit-syslog-bridge/ RFC 5424 HTTP→syslog forwarder +audit-syslog-bridge/ SUBMODULE GameplanePanel/audit-syslog-bridge (RFC 5424 HTTP→syslog forwarder; own go.mod, not in go.work; image still built here) telemetry-receiver/ usage telemetry ingest sentinel/ wake-on-connect proxy for sleeping pods -capture-sidecar/ AF_PACKET BPF capture sidecar +capture-sidecar/ SUBMODULE GameplanePanel/capture-sidecar (AF_PACKET BPF capture sidecar; own go.mod, not in go.work; image still built here) mcp-server/ SUBMODULE GameplanePanel/mcp (read-only MCP server; own go.mod, not in go.work; image still built here) -svcutil/ env parsing + graceful shutdown helpers -tunnel/ relay client supervisor (frp, Tailscale, playit) +tunnel/ SUBMODULE GameplanePanel/tunnel (relay client supervisor: frp, Tailscale, playit; own go.mod, not in go.work; image still built here) web/ React 19 + strict TS + Vite dashboard; src/{routes,components,lib,router,styles,test}/ modules/ SUBMODULE GameplanePanel/module (OCI game templates) website/ SUBMODULE GameplanePanel/website (Astro docs/marketing; has its own CLAUDE.md and AGENTS.md) @@ -50,23 +49,23 @@ docs/ architecture, security, modules; layout.md (target folder s design.pen canonical Pencil dashboard design signing/ cosign public keys, dated legacy key + cross-signature (image + module) .devcontainer/ dev container profiles, generated by hack/gen-devcontainers.py from versions.toml, profiles.toml, devcontainer-lock.json (full profile's feature lock), setup.sh (shared setup script, copied into the submodule copies) and each folder's system-deps.toml -go.work links all 16 Go modules (incl. test/e2e) +go.work links all 12 Go modules (incl. test/e2e) Makefile canonical task runner ``` -After cloning: `git submodule update --init modules mcp-server` (both required for `make dev-up`, which builds the mcp-server image); add `git submodule update --init website` only when working on the website. +After cloning: `git submodule update --init modules` (required for `make dev-up`) and `hack/submodules.sh init` (the split component submodules mcp-server, audit-syslog-bridge, tunnel, capture-sidecar; `make images`/`make dev-up` also init them on demand); add `git submodule update --init website` only when working on the website. ## Commands (via Makefile; compile checks excepted, see rule 8) - **Dev:** `make dev-up` (Kind + OCI registry :5001 + Helm), `make web-dev` (Vite, proxies in-cluster API), `make dev-load` (load built images; run `make images` first), `make dev-install` (Helm upgrade), `make dev-down`. -- **Build:** `make build` (all Go + web), `make build-go` (15 modules in GO_MODULES, all but test/e2e), `make build-web` (`npm ci && npm run build`), `make images`. +- **Build:** `make build` (all Go + web), `make build-go` (11 modules in GO_MODULES, all but test/e2e), `make build-web` (`npm ci && npm run build`), `make images`. - **Codegen:** `make generate` (deepcopy), `make manifests` (CRD/RBAC YAML, synced to `charts/gameplane/charts/gameplane-crds/crds/` and `charts/gameplane/crd-manifests/`), `make modules-push`, `make tidy`. - **Dev containers:** `make devcontainers` (regenerate every profile and the `website/` and `modules/` copies after editing `.devcontainer/versions.toml`, `.devcontainer/profiles.toml`, `.devcontainer/devcontainer-lock.json`, `.devcontainer/setup.sh` or a `system-deps.toml`), `make check-devcontainers` (drift check). Profile table: `docs/contributing.md`. - **Tests (CI only — never run locally, see Rule 8):** `make test`, `make test-integration` (envtest operator+api), `make test-e2e` (~10–20 min), `make test-e2e-bucket BUCKET=(operator|api-auth|api-roles|api-rbac|api-agent|api-mods|ratelimit|bot-fast|bot-heavy|multicluster|upgrade)`. - **E2E conventions:** register new tests in `test/e2e/buckets.sh`; `t.Parallel()` + unique names; guard shared resources (`ociPushMu` for module pushes, `ensureResticRepo(t)` for shared backup repos). Rate limits per cluster: IP burst 10 (5/min), user burst 6 (3/min) — cap an API bucket at ~7 admin logins. - **Lint:** `make lint` = gofmt, go vet, golangci-lint, ESLint, Oxlint, `check-specs`, `check-doc-versions`, `check-links`. -**Coverage minimums:** netguard 91, gameaction 91, gameproto 90, telemetryschema 90, i18n 90, gp-module 80, operator 72, api 80, agent 90, svcutil 90; audit-syslog-bridge, telemetry-receiver, sentinel, capture-sidecar, tunnel 70; web 92 lines / 76 functions / 82 branches / 92 statements. +**Coverage minimums:** netguard 91, gameaction 91, gameproto 90, telemetryschema 90, i18n 90, gp-module 80, operator 72, api 80, agent 90; telemetry-receiver, sentinel 70; web 92 lines / 76 functions / 82 branches / 92 statements. ## Core rules @@ -110,14 +109,13 @@ After cloning: `git submodule update --init modules mcp-server` (both required f | telemetryschema | Go | stdlib-only shared telemetry report contract: types, strict decode, official module catalog, report signing (api, telemetry-receiver) | | i18n | Go | shared language packs (`go:embed`), ICU MessageFormat subset, pack validator, `i18n-check` CI tool (api, web, operator, gp-module) | | gp-module | Go | module CLI: scaffold, offline validate, dry-run preview, OCI package | -| svcutil | Go | stdlib-only env + graceful shutdown (`RunHTTP`) | | operator | Go, controller-runtime | authoritative reconciler for 9 CRDs (`GameServer`, `GameTemplate`, …) | | api | Go, chi | REST/WS UX gateway; SQLite, experimental PostgreSQL | | agent | Go | pod sidecar: console (PTY/RCON), files, logs, heartbeats | -| audit-syslog-bridge | Go | webhook audit events → RFC 5424 syslog | +| audit-syslog-bridge | Go (submodule GameplanePanel/audit-syslog-bridge) | webhook audit events → RFC 5424 syslog | | telemetry-receiver | Go | opt-in anonymous usage stats | | sentinel | Go | holds ports while asleep, wakes pods on connect | -| capture-sidecar | Go | ephemeral BPF packet capture | +| capture-sidecar | Go (submodule GameplanePanel/capture-sidecar) | ephemeral BPF packet capture | | mcp-server | Go (submodule GameplanePanel/mcp) | read-only MCP daemon (stdio) for cluster debugging | | web | React 19, Vite, TS | dashboard (TanStack Router/Query, Tailwind, HeroUI v3) | | modules/ | OCI / oras | game templates (Minecraft, Terraria, Valheim, …) | @@ -129,11 +127,11 @@ After cloning: `git submodule update --init modules mcp-server` (both required f - **Dashboard screen:** design in `design.pen` + export to `assets/design-export/` → `web/src/routes/.tsx`, register in `web/src/router/tree.tsx` → data via `web/src/lib/api.ts` + TanStack Query → `web/src/routes/.test.tsx`. - **Game module:** edit `modules//` (`module.yaml`, `template.yaml`, `README.md`) → `make modules-push` → commit in `GameplanePanel/module` → `git add modules` + commit pointer bump in root. - **Website:** design in `website/website.pen` + export to `website/website-export/` → change `website/` per its own CLAUDE.md and AGENTS.md → commit/push/PR in `GameplanePanel/website` (default branch `main`) → `git add website` + commit pointer bump in root. -- **MCP server:** change `mcp-server/` per the mcp repo's own docs → commit/push/PR in `GameplanePanel/mcp` (default branch `main`) → after it merges, `git -C mcp-server fetch origin main && git -C mcp-server checkout ` → `git add mcp-server` + commit pointer bump in root. +- **Split component** (`mcp-server/`, `audit-syslog-bridge/`, `tunnel/`, `capture-sidecar/`): change it per that repo's own docs → commit/push/PR in `GameplanePanel/` (`mcp` for mcp-server; default branch `main`; CI there is the shared `.github/workflows/go-component.yaml`) → after it merges, `git -C fetch origin main && git -C checkout ` → `git add ` + commit pointer bump in root. A new split = one `.gitmodules` entry with `component = true` plus the path filters `hack/submodules.sh check` asks for. - **DB migration:** new sequential `api/internal/db/migrations/common/_.sql` (013 onward) — portable SQL both SQLite and PostgreSQL run unchanged (no `datetime('now')`/`strftime`, `AUTOINCREMENT`, `INSERT OR …`, `COLLATE NOCASE`; bind timestamps from Go). `migrations/sqlite/` and `migrations/postgres/` hold the frozen per-dialect 001–012 sets; see `api/internal/db/migrations/README.md`. Append-only, applied on API startup. ## Reference docs - `docs/agent-architecture.md` — read before editing code; maps tasks/features to docs (use instead of repo-wide greps). -- `docs/architecture.md`, `docs/security.md` (threat model); `docs/module-authoring.md`; [`GameplanePanel/mcp` README](https://github.com/GameplanePanel/mcp/blob/main/README.md); `audit-syslog-bridge/README.md`. +- `docs/architecture.md`, `docs/security.md` (threat model); `docs/module-authoring.md`; [`GameplanePanel/mcp` README](https://github.com/GameplanePanel/mcp/blob/main/README.md); [`GameplanePanel/audit-syslog-bridge` README](https://github.com/GameplanePanel/audit-syslog-bridge/blob/main/README.md). - Configs: `.golangci.yml`, `web/eslint.config.js`, `web/.oxlintrc.json`, `.editorconfig`. diff --git a/FEATURES.md b/FEATURES.md index af5d5b541..493afade0 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -182,7 +182,7 @@ See [docs/roadmap.md](docs/roadmap.md) for what is planned and in progress. | Record and page through the audit log | stable | on | Each mutating API request writes an audit event to the audit_events table that the dashboard serves, and GET /admin/audit pages and filters the events. | [install](docs/install.md#audit-log) | | Export the audit trail and verify its hash chain | beta | on | GET /admin/audit/export downloads the full trail as CSV or JSON, and GET /admin/audit/verify re-walks the SHA-256 chain and reports the first broken link. | [security](docs/security.md#audit-log-integrity) | | Forward audit events to stdout or a webhook | beta | off | Mirrors each event as a structured JSON log line when api.audit.stdout is set, and POSTs each event as JSON from a bounded best-effort buffer when api.audit.webhook.url is set, with an optional Authorization header read from a Secret. | [install](docs/install.md#audit-log) | -| Ship audit events to syslog or S3-compatible storage | beta | off | The bundled audit-syslog-bridge turns events into RFC 5424 records sent over TCP, TCP with TLS or UDP, with TCP recommended, and api.audit.s3 batches NDJSON objects flushed at 100 events, 1 MiB or 5 seconds. | [audit-syslog-bridge](audit-syslog-bridge/README.md#transport-prefer-tcp) | +| Ship audit events to syslog or S3-compatible storage | beta | off | The bundled audit-syslog-bridge turns events into RFC 5424 records sent over TCP, TCP with TLS or UDP, with TCP recommended, and api.audit.s3 batches NDJSON objects flushed at 100 events, 1 MiB or 5 seconds. | [audit-syslog-bridge](https://github.com/GameplanePanel/audit-syslog-bridge/blob/main/README.md#transport-prefer-tcp) | | Prune audit events past a retention age | beta | off | api.audit.retentionDays removes events older than N days, and the default of 0 keeps events forever. | [install](docs/install.md#audit-log) | | Resolve client IPs through trusted proxies | beta | on | The API reads X-Forwarded-For only from peers inside api.trustedProxies, so audit records and per-IP limits use the real client address. | [security](docs/security.md#client-ip-extraction-from-forwarded-headers) | | Run Gameplane pods hardened and optionally enforce restricted Pod Security | beta | on | Operator, API, agent and optional bridge pods run as uid 65532 with read-only root filesystems, RuntimeDefault seccomp and all capabilities dropped, and new installations enforce the Restricted Pod Security Standard in managed game namespaces by default. | [security](docs/security.md#pod-security) | diff --git a/README.md b/README.md index 4c0cdad11..bfffc76da 100644 --- a/README.md +++ b/README.md @@ -152,17 +152,16 @@ legacy default for custom deployments. See [storage and recovery](docs/standalon | `api/cmd/gateway.go` | Go | Optional private per-cluster gateway (`gateway` subcommand in the API image); proxies authorized agent and capture operations over mTLS. | | `operator/` | Go | Kubernetes controller reconciling Gameplane CRDs into K8s workloads and resources. | | `sentinel/` | Go | Waker daemon listening on game ports while a server is sleeping to trigger wake-on-connect [optional]. | -| `capture-sidecar/` | Go | Network packet capture sidecar [optional], opt-in per server, admin-only. | -| `tunnel/` | Go | Relay supervisor pod managing third-party tunnels (`frp`, `Tailscale`, `playit`) [optional]. | +| `capture-sidecar/` | Go | Submodule (`GameplanePanel/capture-sidecar`): network packet capture sidecar [optional], opt-in per server, admin-only. | +| `tunnel/` | Go | Submodule (`GameplanePanel/tunnel`): relay supervisor pod managing third-party tunnels (`frp`, `Tailscale`, `playit`) [optional]. | | `web/` | TS + React | Modern dashboard UI built with Vite, TanStack Query, xterm.js, and Monaco Editor. | | `modules/` | YAML | 29 pre-packaged game templates (Minecraft, Valheim, Terraria, Rust, etc.) as OCI bundles. | | `charts/` | Helm | Official Helm deployment chart for operator, API gateway, ingress, and helper services. | | `gameproto/` | Go | Shared protocol library for parsing game handshakes (Minecraft, Terraria) in `sentinel`. | | `gameaction/` | Go | Security guard and command renderer for custom module admin actions. | | `netguard/` | Go | SSRF protection layer for outgoing mod downloads and OCI module fetches. | -| `svcutil/` | Go | Shared HTTP server lifecycle and environment configuration utilities. | | `telemetryschema/` | Go | Shared telemetry report contract (types, strict decoder, official module catalog, report signing) used by the API and `telemetry-receiver`. | -| `audit-syslog-bridge/` | Go | HTTP-JSON to syslog relay [optional] for audit logging infrastructure. | +| `audit-syslog-bridge/` | Go | Submodule (`GameplanePanel/audit-syslog-bridge`): HTTP-JSON to syslog relay [optional] for audit logging infrastructure. | | `telemetry-receiver/` | Go | Collector [optional] for anonymous daily usage reports. | | `mcp-server/` | Go | Submodule (`GameplanePanel/mcp`): strictly read-only Model Context Protocol server [optional] for AI tools. | @@ -190,16 +189,15 @@ Gameplane extends Kubernetes using custom resources under `gameplane.local/v1alp │ ├── internal/controller/ │ └── config/ # CRD manifests and RBAC rules ├── sentinel/ # Wake-on-connect daemon (Go) -├── tunnel/ # Relay client supervisor for frp/Tailscale/playit (Go) +├── tunnel/ # Submodule: relay client supervisor for frp/Tailscale/playit (Go) ├── web/ # Dashboard frontend (React, Vite, Monaco, xterm.js) ├── modules/ # Submodule: Game templates (29 games shipped) ├── website/ # Submodule: Public documentation site ├── gameproto/ # Wire-protocol parsing library (Minecraft, Terraria) ├── gameaction/ # Console injection guard & action command renderer ├── netguard/ # SSRF dial-guard library -├── svcutil/ # Shared HTTP server & env utilities ├── telemetryschema/ # Shared telemetry report contract (types, decoder, signing) -├── audit-syslog-bridge/ # Optional syslog relay for audit logs +├── audit-syslog-bridge/ # Submodule: optional syslog relay for audit logs ├── telemetry-receiver/ # Optional anonymous usage telemetry receiver ├── mcp-server/ # Submodule: optional read-only MCP server (GameplanePanel/mcp) ├── charts/gameplane/ # Helm deployment chart @@ -263,13 +261,13 @@ Ed25519 key and do not have transparency log entries — verify them with Requires: Go 1.27+, Node 20+, Docker, kind, kubectl, helm, [oras](https://oras.land/docs/installation) (>= 1.2.0). -The game modules and the MCP server live in the separate `GameplanePanel/module` and `GameplanePanel/mcp` repos, wired in here -as the `modules/` and `mcp-server/` submodules — clone with submodules (or initialize them after): +The game modules and the split components live in separate `GameplanePanel/*` repos, wired in here as submodules: `modules/` (`GameplanePanel/module`) and the component submodules `mcp-server/`, `audit-syslog-bridge/`, `tunnel/` and `capture-sidecar/` (`GameplanePanel/mcp`, `/audit-syslog-bridge`, `/tunnel`, `/capture-sidecar`). Clone with submodules (or initialize them after): ```sh git clone --recurse-submodules # already cloned? populate the submodules: -git submodule update --init +git submodule update --init modules +hack/submodules.sh init # component submodules listed in .gitmodules (component = true); make images/dev-up also init them on demand ``` ```sh diff --git a/docs/agent-architecture.md b/docs/agent-architecture.md index cda899821..b32570c30 100644 --- a/docs/agent-architecture.md +++ b/docs/agent-architecture.md @@ -22,14 +22,13 @@ This document is the **first stop** for AI agents modifying or extending Gamepla | Component | `specs.md` location | Primary Responsibilities | | --- | --- | --- | -| **Capture Sidecar** | `capture-sidecar/specs.md` | Ephemeral network packet capture sidecar injected into game pods to capture traffic. | +| **Capture Sidecar** | `capture-sidecar/specs.md` (submodule `GameplanePanel/capture-sidecar`) | Ephemeral network packet capture sidecar injected into game pods to capture traffic. | | **Sentinel** | `sentinel/specs.md` | Wake-on-connect daemon holding ports for sleeping servers and waking them up upon player connection attempts. | -| **Tunnel** | `tunnel/specs.md` | Relay client supervisor for integrating with external tunnels (frp, Tailscale, playit). | -| **Audit-Syslog-Bridge** | `audit-syslog-bridge/specs.md` | Relay forwarding HTTP JSON audit events to external syslog servers. | +| **Tunnel** | `tunnel/specs.md` (submodule `GameplanePanel/tunnel`) | Relay client supervisor for integrating with external tunnels (frp, Tailscale, playit). | +| **Audit-Syslog-Bridge** | `audit-syslog-bridge/specs.md` (submodule `GameplanePanel/audit-syslog-bridge`) | Relay forwarding HTTP JSON audit events to external syslog servers. | | **Telemetry-Receiver** | `telemetry-receiver/specs.md` | Ingests and processes anonymous usage telemetry from the API. | | **Telemetryschema** | `telemetryschema/specs.md` | Shared telemetry report contract (types, enumerations, strict decode, official module catalog, report signing) used by the API and the telemetry-receiver. | | **MCP-Server** | `mcp-server/specs.md` (submodule `GameplanePanel/mcp`) | Read-only Model Context Protocol server exposing cluster state to AI tools. | -| **Svcutil** | `svcutil/specs.md` | Shared stdlib-only env and graceful-shutdown helpers used by backend components. | ## Frontend & Other diff --git a/docs/architecture.md b/docs/architecture.md index 4bdefc0e7..8b7b0f2a7 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -448,7 +448,7 @@ the target. See [registration and permissions](install.md#rbac-and-permissions). matching a BPF filter to PCAPNG output, exposed via mTLS on port `:9091`. Opt-in per GameServer via `spec.capture.enabled` and admin-only (`captures:manage` permission). Disabled by default; enabled cluster-wide via `capture.enabled` - Helm value. See `capture-sidecar/`. + Helm value. See the [`GameplanePanel/capture-sidecar`](https://github.com/GameplanePanel/capture-sidecar) repo (the `capture-sidecar/` submodule). - **mcp-server [optional]**: a standalone, strictly read-only MCP server (submodule `GameplanePanel/mcp`) — its tool handlers only ever hold a `*kube.Client` (`mcp-server/internal/kube`), whose sole exported methods are List/Get-shaped; the underlying typed/ diff --git a/docs/contributing.md b/docs/contributing.md index d2c4ba98a..6c534da31 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -22,12 +22,12 @@ change, the one compile check to run, and how long CI takes. | Docs only | `docs/`, `README.md`, any `*.md` | none | 1.8 min (run 2507) | | Spec only | `specs/NNN-/` | none | 5.3 min (run 2525) | | Web only | `web/` | `cd web && npx tsc --noEmit` | 18.3 min (run 2524) | -| One small Go service | `/` (e.g. `sentinel/`, `tunnel/`) | `go build ./...` in that module | same as any Go change: 29–75 min, median 37.5 min | +| One small Go service | `/` (e.g. `sentinel/`, `telemetry-receiver/`) | `go build ./...` in that module | same as any Go change: 29–75 min, median 37.5 min | | Operator / CRD | `operator/` (types in `operator/api/v1alpha1/`) | `make generate && make manifests`, then `go build ./...` in `operator/` | same as any Go change | | API route | `api/` (handlers in `api/internal/handlers/`) | `go build ./...` in `api/` | same as any Go change | | Game module | `modules//`: PR in `GameplanePanel/module`, then a pointer bump here | `make module-validate MODULE=` | 2.7 min in `GameplanePanel/module` (run 79, 2026-10-20); the bump PR here runs the docs gates | | Website | `website/`: PR in `GameplanePanel/website`, then a pointer bump here | `npm run build` in `website/` | 0.6 min in `GameplanePanel/website` (PR 25, 2026-10-22); the bump PR here runs the docs gates | -| MCP server | `mcp-server/`: PR in `GameplanePanel/mcp`, then a pointer bump here | follow that repo's docs | the bump PR here runs the build and optional-components e2e | +| Split component | `mcp-server/`, `audit-syslog-bridge/`, `tunnel/`, `capture-sidecar/`: PR in its own repo (`GameplanePanel/mcp`, `GameplanePanel/audit-syslog-bridge`, `GameplanePanel/tunnel`, `GameplanePanel/capture-sidecar`), then a pointer bump here | follow that repo's docs | the bump PR here runs the build and optional-components e2e | Times are GitHub Actions wall clock for one PR run, measured 2026-10-20: runs 2507, 2525 and 2524, and 11 Go PR runs for the median. Change-based test @@ -42,7 +42,8 @@ Gates a first PR trips on: - UI without design: dashboard changes start in `design.pen` (Pencil), see [Design first for UI changes](#design-first-for-ui-changes). Never hand-edit `.pen` files. -- Submodule work in the wrong repo: `modules/`, `website/` and `mcp-server/` changes go to +- Submodule work in the wrong repo: `modules/`, `website/` and the component submodules + (`mcp-server/`, `audit-syslog-bridge/`, `tunnel/`, `capture-sidecar/`) changes go to their own repos first, then a pointer bump PR here. ## Dev loop @@ -59,14 +60,14 @@ The repo ships one dev container per area, so you only install what your change | Profile | Size | Scope | What it installs | Setup time in CI (amd64 / arm64) | Use it for | | --- | --- | --- | --- | --- | --- | | `web` | component | `web/` | Node, `npm ci` in `web/` | 3.1 / 2.7 min | Dashboard code with mocked data | -| `api` | component | `api/`, `svcutil/` and their Go libraries | Go, golangci-lint, envtest | 5.1 / 4.7 min | API handlers, auth, DB | +| `api` | component | `api/` and its Go libraries | Go, golangci-lint, envtest | 5.1 / 4.7 min | API handlers, auth, DB | | `operator` | component | `operator/` and its Go libraries | Go, golangci-lint, envtest | 6.9 / 4.4 min | Reconcilers and CRD types | | `agent` | component | `agent/` and its Go libraries | Go, golangci-lint | 5.4 / 3.8 min | The in-pod sidecar | -| `go-services` | component | sentinel, tunnel, gp-module, mcp-server (submodule), telemetry-receiver, audit-syslog-bridge, capture-sidecar, gameproto and their Go libraries | Go, golangci-lint | 7.3 / 5.0 min | The smaller Go services | +| `go-services` | component | sentinel, tunnel (submodule), gp-module, mcp-server (submodule), telemetry-receiver, audit-syslog-bridge (submodule), capture-sidecar (submodule), gameproto and their Go libraries | Go, golangci-lint | 7.3 / 5.0 min | The smaller Go services | | `website` | component | `website/` submodule | Node, `npm ci` in `website/` | 2.4 / 2.3 min | Docs and marketing site | | `modules` | component | `modules/` submodule | Go, Python with PyYAML, oras | 3.0 / 2.7 min | Game module templates | -| `dashboard-api` | part | web + api + operator + agent, kind, chart, `modules` and `mcp-server` submodules | Docker, kind, kubectl, Helm, Go, Node, Python with PyYAML, oras | 9.1 / 7.4 min | Dashboard work against a live local cluster | -| `control-plane` | part | operator + api + agent, kind, chart, e2e, `modules` and `mcp-server` submodules | Docker, kind, kubectl, Helm, Go, Python with PyYAML, oras | 7.1 / 5.9 min | Backend work with a live cluster, e2e code | +| `dashboard-api` | part | web + api + operator + agent, kind, chart, `modules` and component submodules | Docker, kind, kubectl, Helm, Go, Node, Python with PyYAML, oras | 9.1 / 7.4 min | Dashboard work against a live local cluster | +| `control-plane` | part | operator + api + agent, kind, chart, e2e, `modules` and component submodules | Docker, kind, kubectl, Helm, Go, Python with PyYAML, oras | 7.1 / 5.9 min | Backend work with a live cluster, e2e code | | `modules-gp` | part | modules + `gp-module/` | Go, Python with PyYAML, oras | 5.0 / 4.2 min | Module work with the `gp-module` CLI | | `full` | full | everything | everything above | 11.1 / 8.4 min | Cross-cutting changes; the default. Leaves out the website's Astro port 4321 and extension (open `website` for those) | @@ -158,7 +159,7 @@ These jobs block merging. Each gate with a fixture has a `hack/*_test.sh` self-t - **`workflow lint`** also runs hadolint over every tracked Dockerfile, failing on any warning (`.hadolint.yaml`). Fix the Dockerfile: pin `apk`/`apt` package versions, and set a `SHELL` with `-o pipefail` before any piped `RUN` step. - **`dependency review`** runs on pull requests only. It fails when the PR adds a dependency with a HIGH or CRITICAL advisory. Pick a version without the advisory, or drop the dependency. - **`codegen drift`** runs `make generate manifests` and `make tidy`, then fails if `git diff` is not empty. Run the same commands locally and commit what they change (CLAUDE.md rule 7). -- **`submodule freshness`** runs `hack/check-submodule-freshness.sh`. It fails when the `modules`, `website` or `mcp-server` pointer names a commit that is not on that repo's `main`, when a gitlink is missing, or when the script cannot fetch that repo's `main`. For a pointer that is not on `main`, merge the submodule PR first, then bump the pointer to the merged commit. Otherwise restore the gitlink, or fix the fetch error, and re-run. +- **`submodule freshness`** runs `hack/check-submodule-freshness.sh`. It fails when any submodule pointer (`modules`, `website` or a component submodule listed in `.gitmodules`) names a commit that is not on that repo's `main`, when a gitlink is missing, or when the script cannot fetch that repo's `main`. For a pointer that is not on `main`, merge the submodule PR first, then bump the pointer to the merged commit. Otherwise restore the gitlink, or fix the fetch error, and re-run. It also runs `hack/submodules.sh check`, which fails when a component submodule is missing from a workflow path filter it must be in. ### How CI picks tests @@ -221,20 +222,16 @@ Per-component: cd netguard && go test ./... cd gameaction && go test ./... cd gameproto && go test ./... -cd svcutil && go test ./... cd operator && go test ./... cd api && go test ./... cd agent && go test ./... -cd audit-syslog-bridge && go test ./... cd telemetry-receiver && go test ./... cd sentinel && go test ./... -cd capture-sidecar && go test ./... -cd tunnel && go test ./... cd gp-module && go test ./... cd web && npm test ``` -The `mcp-server/` module is the `GameplanePanel/mcp` submodule; its tests and lint run in that repo's CI. To compile it here use `cd mcp-server && GOWORK=off go build ./...`. +The component submodules (`mcp-server/`, `audit-syslog-bridge/`, `tunnel/`, `capture-sidecar/`) run their tests and lint in their own repos' CI (shared `.github/workflows/go-component.yaml`). To compile one here use `cd && GOWORK=off go build ./...`. ## E2E testing @@ -327,9 +324,9 @@ and test gates below. Game-module changes (`modules/`) belong in the separate **`GameplanePanel/module`** repo, which this repo vendors as a submodule. Open the module PR there; once it merges, bump the submodule pointer here (`git add modules`) in a follow-up PR. -MCP server changes (`mcp-server/`) belong in **`GameplanePanel/mcp`** the same way (`git add mcp-server`). +Component submodule changes (`mcp-server/`, `audit-syslog-bridge/`, `tunnel/`, `capture-sidecar/`) belong in their own repos the same way (`git add `). -`.gitmodules` points all three submodules (`modules/`, `website/`, `mcp-server/`) at the upstream +`.gitmodules` points all submodules (`modules/`, `website/` and the component submodules) at the upstream GitHub URLs, so a fork of this repo clones them without forking them too. To work on your own fork of a submodule, repoint it locally: `git submodule set-url modules https://github.com//module.git` diff --git a/docs/dependencies.md b/docs/dependencies.md index cc724626f..80c91b1a2 100644 --- a/docs/dependencies.md +++ b/docs/dependencies.md @@ -1,13 +1,12 @@ # Dependency report This is a component-by-component inventory of Gameplane's third-party -dependencies and why each one is there. It covers all 15 Go modules that +dependencies and why each one is there. It covers all 12 Go modules that share `go.work` (`netguard`, `gameaction`, `gameproto`, `telemetryschema`, -`svcutil`, `operator`, `api`, `agent`, `audit-syslog-bridge` [optional], -`telemetry-receiver` [optional], `sentinel` [optional], -`capture-sidecar` [optional], `tunnel` [optional], `gp-module`, -`test/e2e`), the `mcp-server` [optional] module (the `GameplanePanel/mcp` -submodule, which keeps its own `go.mod` outside `go.work`), the +`i18n`, `operator`, `api`, `agent`, `telemetry-receiver` [optional], `sentinel` [optional], +`gp-module`, `test/e2e`), the split component submodules `mcp-server` [optional], +`audit-syslog-bridge` [optional], `tunnel` [optional] and `capture-sidecar` [optional] +(each the `GameplanePanel/` submodule, which keeps its own `go.mod` outside `go.work`), the `web/` npm package, and the build/CI toolchain that isn't a code dependency but is invoked by `make`/GitHub Actions. @@ -28,7 +27,7 @@ Toolchain versions come from `Makefile`, `.github/workflows/*.yaml`, and `.devcontainer/versions.toml` (dev container pins; `.devcontainer/setup.sh` installs them). Accurate as of **2026-09-02**, repo state `v0.3.0`; the `gameproto`, -`svcutil`, `sentinel`, `capture-sidecar`, `tunnel`, and `gp-module` sections +`sentinel`, and `gp-module` sections were added and verified on **2026-09-26**. > **Note:** The dependency versions listed in the table below reflect the state at v0.3.0. For the most current versions, refer to [CHANGELOG.md](../CHANGELOG.md). @@ -41,15 +40,14 @@ were added and verified on **2026-09-26**. | `gameaction/` | Go | 0 (stdlib only) | Shared console-injection guard + command-template renderer used by the agent and API | | `gameproto/` | Go | 0 (stdlib only) | Shared Minecraft/Terraria handshake classifier used by sentinel | | `telemetryschema/` | Go | 0 (stdlib only) | Shared telemetry report contract (types, strict decoder, official module catalog, report signing) used by the API reporter and the telemetry receiver | -| `svcutil/` | Go | 0 (stdlib only) | Shared env-parsing + graceful-shutdown helpers (no active importers yet) | | `operator/` | Go | 19 | controller-runtime reconciler for the 8 CRDs; module OCI pull/verify, git/OCI fetch, restic-backup scheduling | | `api/` | Go | 17 | chi REST + WebSocket gateway: auth (local + OIDC), RBAC, K8s client, SQLite/Postgres persistence, notifications | | `agent/` | Go | 6 | In-pod sidecar: RCON/WebRcon console, chi HTTP surface, heartbeat status patch, disk usage stats | -| `audit-syslog-bridge/` | Go | 0 (stdlib only) | Standalone HTTP-JSON → syslog relay for the audit webhook sink | +| `audit-syslog-bridge/` (submodule) | Go | 0 (stdlib only) | Standalone HTTP-JSON → syslog relay for the audit webhook sink | | `telemetry-receiver/` | Go | 1 | Standalone collector for the API's usage telemetry (daily counts; extended reports add a random install ID and its public key; on by default for new installs; `api.telemetry.enabled=false` turns it off) | | `sentinel/` | Go | 2 | Wake-on-connect listener holding ports for sleeping pods | -| `capture-sidecar/` | Go | 3 | Ephemeral AF_PACKET packet capture sidecar with BPF filtering | -| `tunnel/` | Go | 0 (stdlib only) | Relay client supervisor for frp/Tailscale/playit | +| `capture-sidecar/` (submodule) | Go | 3 | Ephemeral AF_PACKET packet capture sidecar with BPF filtering | +| `tunnel/` (submodule) | Go | 0 (stdlib only) | Relay client supervisor for frp/Tailscale/playit | | `gp-module/` | Go | 2 | Module authoring CLI: scaffold, offline validate, dry-run preview, OCI package | | `mcp-server/` (submodule) | Go | 5 | Standalone, strictly read-only MCP server for AI-assisted cluster diagnostics | | `test/e2e/` | Go | 4 | kind + Helm + real-component end-to-end suite | @@ -121,19 +119,6 @@ Imported by (spec 022): Both importers use a local `replace` module (`replace github.com/GameplanePanel/gameplane/telemetryschema => ../telemetryschema`); the same Dockerfile `COPY` requirement as netguard applies. -### svcutil - -`svcutil/go.mod` has **no `require` block at all** — stdlib only -(`log/slog`, `os`, `net/http`, `context`, `errors`, `time`). It provides -shared environment-variable parsing (`Or`, `OrInt`, `ParseLogLevel`) and a -graceful HTTP shutdown helper (`RunHTTP`), meant to cut down on -copy-pasted startup/shutdown boilerplate across the repo's standalone Go -binaries. - -It has **no active importers yet** (see `svcutil/specs.md` for adoption -status) — it ships as an available shared module ahead of the other -services being migrated onto it. - ## Services ### operator @@ -230,6 +215,8 @@ drift between modules as Dependabot bumps them one module at a time. ### audit-syslog-bridge +Lives in the `GameplanePanel/audit-syslog-bridge` submodule; Dependabot runs there. + `audit-syslog-bridge/go.mod` has **no `require` block** — stdlib only (`crypto/subtle`, `crypto/tls`, `log/slog`, `net`, `net/http`, etc.). It's a small, schema-agnostic HTTP-JSON → syslog (RFC 5424) relay: it accepts @@ -289,6 +276,8 @@ handshake. Direct deps from `sentinel/go.mod` (excluding the local ### capture-sidecar +Lives in the `GameplanePanel/capture-sidecar` submodule; Dependabot runs there. + Ephemeral, on-demand AF_PACKET packet capture container that runs alongside a `GameServer` pod with `CAP_NET_RAW` (see [`docs/security.md`](security.md) for the capability/PodSecurity @@ -302,6 +291,8 @@ trade-off). Direct deps from `capture-sidecar/go.mod`: ### tunnel +Lives in the `GameplanePanel/tunnel` submodule; Dependabot runs there. + `tunnel/go.mod` has **no `require` block at all** — stdlib only (`os/exec`, `encoding/json`, `net/http`, `context`, etc.). It's the relay client supervisor: it launches and monitors the `frp`, `tailscaled`, or diff --git a/docs/install.md b/docs/install.md index fe3bad11b..95fafe3c2 100644 --- a/docs/install.md +++ b/docs/install.md @@ -527,7 +527,7 @@ a slow or down sink never blocks or fails a request. - `api.audit.webhook.authSecretRef` — optional `Authorization` header for the webhook, sourced from a Secret (never a flag — see [security](security.md)). - `api.audit.webhook.syslogBridge.enabled` — deploy the bundled - [audit-syslog-bridge [optional]](../audit-syslog-bridge/README.md) and point the webhook + [audit-syslog-bridge [optional]](https://github.com/GameplanePanel/audit-syslog-bridge/blob/main/README.md) and point the webhook at it automatically, so events are forwarded to a **syslog** collector. Set `syslogBridge.syslog.addr` to your collector `host:port` (required when enabled), and optionally `network` (`tcp`/`udp`), `tls`, `facility`, and diff --git a/docs/layout.md b/docs/layout.md index 0cdd67e84..acbe425eb 100644 --- a/docs/layout.md +++ b/docs/layout.md @@ -17,7 +17,7 @@ A long-running binary (a Deployment, DaemonSet, sidecar or Job image). ```text / -├── cmd/main.go thin wiring: flags and env (svcutil), construct, run +├── cmd/main.go thin wiring: flags and env, construct, run ├── internal// all behavior, one package per concern ├── specs.md ├── README.md @@ -92,19 +92,18 @@ move spec 028 makes. | --- | --- | --- | --- | | `agent` | Service | `cmd/main.go` + `internal//` | matches | | `api` | Service | `cmd/main.go` + `internal//` | `cmd/` holds 7 non-test files (bootstrap, gateway, management, memlimit, metrics, panel key) → keep wiring in `cmd/`, move behavior to `internal//`; second binary `cmd/messages-export/` matches; `internal/handlers/` is one flat package of 146 files (spec 028 splits it) | -| `audit-syslog-bridge` | Service | `cmd/main.go` + `internal//` | 3 files in root `package main` (`main.go` 460 lines) → `cmd/main.go` + `internal//` | -| `capture-sidecar` | Service | `cmd/main.go` + `internal//` | matches | +| `audit-syslog-bridge` | Service | `cmd/main.go` + `internal//` | 3 files in root `package main` (`main.go` 460 lines) → `cmd/main.go` + `internal//`. Lives in the `GameplanePanel/audit-syslog-bridge` submodule. | +| `capture-sidecar` | Service | `cmd/main.go` + `internal//` | matches. Lives in the `GameplanePanel/capture-sidecar` submodule. | | `mcp-server` | Service | `cmd/main.go` + `internal//` | root `package main` (`main.go`, `tools.go`, `fixadvice.go`) → `cmd/main.go` + `internal//`; `internal/kube/` matches. Lives in the `GameplanePanel/mcp` submodule; the layout is tracked there. | | `operator` | Service | `cmd/main.go` + `internal//` | matches; `internal/controller/` is one flat package of 150 files (spec 028 splits it); `api/v1alpha1/` see §3 | | `sentinel` | Service | `cmd/main.go` + `internal//` | `main.go` 1,017 lines at root → `cmd/main.go` + `internal//` | | `telemetry-receiver` | Service | `cmd/main.go` + `internal//` | 12 source files in root `package main` → `cmd/main.go` + `internal//`; `web/` and `design-export/` assets stay | -| `tunnel` | Service | `cmd/main.go` + `internal//` | `main.go` 1,052 and `playit_reporter.go` 525 lines at root → `cmd/main.go` + `internal//`; `frpc/` (separate build module, not in `go.work`) stays | +| `tunnel` | Service | `cmd/main.go` + `internal//` | `main.go` 1,052 and `playit_reporter.go` 525 lines at root → `cmd/main.go` + `internal//`; `frpc/` (separate build module, not in `go.work`) stays. Lives in the `GameplanePanel/tunnel` submodule. | | `gp-module` | CLI tool | `cmd/gp-module/` + `internal//` | matches; `pkg/` holds the 5 packages `api` and `test/e2e` import | | `i18n` | Library + CLI | flat root package + `cmd/i18n-check/` | matches (see §3) | | `gameaction` | Library | flat root package | matches | | `gameproto` | Library | flat root package | matches | | `netguard` | Library | flat root package | matches | -| `svcutil` | Library | flat root package | matches | | `telemetryschema` | Library | flat root package | matches | | `test/e2e` | Test suite | root package + `internal//` | matches (see §3) | | `web` | Web app | `src/pages/` + route definitions in `src/routes/` | no `src/pages/` yet: screens live in `src/routes/` → move each to `src/pages/.tsx`; screens over 500 lines to split: `AdminSettings.tsx` 2,478, `CreateServer.tsx` 1,352, `tabs/Mods.tsx` 1,291, `tabs/settings/Networking.tsx` 1,045, `ThemeSettings.tsx` 886, `Users.tsx` 825, `Servers.tsx` 680, `tabs/Files.tsx` 670, `tabs/settings/ShareLinks.tsx` 658, `Backups.tsx` 642, `Dashboard.tsx` 596 | diff --git a/docs/relay-health.md b/docs/relay-health.md index 53545418d..d429799f7 100644 --- a/docs/relay-health.md +++ b/docs/relay-health.md @@ -180,6 +180,8 @@ upstream FRP 0.71.0 Linux/amd64 archive (SHA-256 `84f27e39f11169f7adcef8e8b70c9329de17747b1f14dad9fb95eef5682ea716`). On a Linux host with Python 3.11+, `taskset` and three available CPUs: +Run these from a Gameplane checkout with the tunnel submodule initialised (`hack/submodules.sh init`). + ```sh (cd tunnel/frpc && CGO_ENABLED=0 GOWORK=off go build -trimpath -mod=readonly -tags frpc,noweb -o /tmp/frpc github.com/fatedier/frp/cmd/frpc) python3 tunnel/bench/frp_udp.py --relay-load /tmp/relay-load --frpc /tmp/frpc --frps /tmp/frps --clients 8 32 64 128 --seconds 10 @@ -191,8 +193,8 @@ payload byte counters. Columns give the worst measurement across four trials per route and rate. CPU is the largest combined frpc + frps CPU-seconds delta per ten-second trial, including the driver's final one-second receive window. -The [first series](../tunnel/bench/results/frp-loopback-series-1.jsonl) and -[counter-instrumented series](../tunnel/bench/results/frp-loopback-series-2.jsonl) +The [first series](https://github.com/GameplanePanel/tunnel/blob/main/bench/results/frp-loopback-series-1.jsonl) and +[counter-instrumented series](https://github.com/GameplanePanel/tunnel/blob/main/bench/results/frp-loopback-series-2.jsonl) contain all 32 direct and relayed trial records, the runner kernel and the SHA-256 digest of each executable. From de901470144c51cf246f8d5b1237e745656b3fb4 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 00:33:30 +0000 Subject: [PATCH 3/8] docs(changelog): note the component submodule split Co-Authored-By: Claude Opus 5.5 Signed-off-by: Claude --- .../unreleased/995-split-component-submodules.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 changelog/unreleased/995-split-component-submodules.md diff --git a/changelog/unreleased/995-split-component-submodules.md b/changelog/unreleased/995-split-component-submodules.md new file mode 100644 index 000000000..99b3de196 --- /dev/null +++ b/changelog/unreleased/995-split-component-submodules.md @@ -0,0 +1,11 @@ +# Audit syslog bridge, tunnel clients and capture sidecar moved to their own repositories + +The code for the audit-syslog-bridge, the tunnel clients (frp, Tailscale, +playit) and the capture sidecar now lives in +[GameplanePanel/audit-syslog-bridge](https://github.com/GameplanePanel/audit-syslog-bridge), +[GameplanePanel/tunnel](https://github.com/GameplanePanel/tunnel) and +[GameplanePanel/capture-sidecar](https://github.com/GameplanePanel/capture-sidecar), +checked out here as submodules at the same paths. Nothing changes for +installs: images, image names and chart values stay the same. If you build +images from a clone, run `hack/submodules.sh init` first (`make images` and +`make dev-up` also do it for you). [PR #995](https://github.com/GameplanePanel/Gameplane/pull/995) From 783aefb67b0744eaf8d0ee51cb10d94ae9739fd6 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 00:34:39 +0000 Subject: [PATCH 4/8] ci: install hadolint inline in the go-component workflow A reusable workflow can't run a composite action from its own repo by path in the caller's checkout, and master doesn't have the action yet, so the component lint jobs failed. Keep the pinned download inline in go-component.yaml and leave ci.yaml's workflow-lint step as it was. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Claude --- .github/actions/install-hadolint/action.yml | 19 ------------------- .github/workflows/ci.yaml | 12 ++++++++++-- .github/workflows/go-component.yaml | 15 ++++++++++++--- 3 files changed, 22 insertions(+), 24 deletions(-) delete mode 100644 .github/actions/install-hadolint/action.yml diff --git a/.github/actions/install-hadolint/action.yml b/.github/actions/install-hadolint/action.yml deleted file mode 100644 index 459ecb6a7..000000000 --- a/.github/actions/install-hadolint/action.yml +++ /dev/null @@ -1,19 +0,0 @@ -name: install hadolint -description: >- - Download the pinned hadolint release, verify its checksum and put it on PATH. - Used by ci.yaml workflow-lint and by go-component.yaml for the split components. - -runs: - using: composite - steps: - - name: hadolint (download and verify) - shell: bash - run: | - set -euo pipefail - mkdir -p "$RUNNER_TEMP/hadolint" - cd "$RUNNER_TEMP/hadolint" - curl -fsSL -o hadolint \ - https://github.com/hadolint/hadolint/releases/download/v2.14.0/hadolint-linux-x86_64 - echo "6bf226944684f56c84dd014e8b979d27425c0148f61b3bd99bcc6f39e9dc5a47 hadolint" | sha256sum -c - - chmod +x hadolint - echo "$RUNNER_TEMP/hadolint" >> "$GITHUB_PATH" diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 136a19b5a..f2e485f9e 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -1694,8 +1694,16 @@ jobs: "$tmp/actionlint" # Spec 013 G3: hadolint over every tracked Dockerfile, at warning and # above (.hadolint.yaml). Same pinned-download pattern as actionlint. - - name: install hadolint - uses: ./.github/actions/install-hadolint + - name: hadolint (download and verify) + run: | + set -euo pipefail + mkdir -p "$RUNNER_TEMP/hadolint" + cd "$RUNNER_TEMP/hadolint" + curl -fsSL -o hadolint \ + https://github.com/hadolint/hadolint/releases/download/v2.14.0/hadolint-linux-x86_64 + echo "6bf226944684f56c84dd014e8b979d27425c0148f61b3bd99bcc6f39e9dc5a47 hadolint" | sha256sum -c - + chmod +x hadolint + echo "$RUNNER_TEMP/hadolint" >> "$GITHUB_PATH" - name: prove the Dockerfile lint gate can fail run: ./hack/check-hadolint_test.sh - name: hadolint diff --git a/.github/workflows/go-component.yaml b/.github/workflows/go-component.yaml index 5d164dfb6..bad3f9147 100644 --- a/.github/workflows/go-component.yaml +++ b/.github/workflows/go-component.yaml @@ -60,7 +60,6 @@ jobs: sparse-checkout: | .golangci.yml .hadolint.yaml - .github/actions/install-hadolint/ sparse-checkout-cone-mode: false - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: @@ -78,8 +77,18 @@ jobs: with: version: ${{ env.GOLANGCI_LINT_VERSION }} args: --config=.gameplane/.golangci.yml - - name: install hadolint - uses: ./.gameplane/.github/actions/install-hadolint + # Same pinned release and checksum as ci.yaml's workflow-lint job. Inline + # because the caller's checkout can't run an action from this repo by path. + - name: hadolint (download and verify) + run: | + set -euo pipefail + mkdir -p "$RUNNER_TEMP/hadolint" + cd "$RUNNER_TEMP/hadolint" + curl -fsSL -o hadolint \ + https://github.com/hadolint/hadolint/releases/download/v2.14.0/hadolint-linux-x86_64 + echo "6bf226944684f56c84dd014e8b979d27425c0148f61b3bd99bcc6f39e9dc5a47 hadolint" | sha256sum -c - + chmod +x hadolint + echo "$RUNNER_TEMP/hadolint" >> "$GITHUB_PATH" - name: hadolint env: DOCKERFILES: ${{ inputs.dockerfiles }} From 96e7d324b5f38fe397ca841908298f2098aff427 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 00:40:24 +0000 Subject: [PATCH 5/8] fix(operator): pin controller-tools v0.22.0 Dropping tunnel from go.work removed the tailscale requirement that raised the workspace's controller-tools to v0.22.0, so controller-gen fell back to operator's own v0.20.1 and regenerated the CRDs differently. Require v0.22.0 in operator/go.mod, the version the committed CRDs were generated with. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Claude --- operator/go.mod | 4 +--- operator/go.sum | 13 ++++++------- 2 files changed, 7 insertions(+), 10 deletions(-) diff --git a/operator/go.mod b/operator/go.mod index 1d6c21602..8f44c8ea2 100644 --- a/operator/go.mod +++ b/operator/go.mod @@ -170,8 +170,6 @@ require ( gopkg.in/evanphx/json-patch.v4 v4.13.0 // indirect gopkg.in/inf.v0 v0.9.1 // indirect gopkg.in/warnings.v0 v0.1.2 // indirect - gopkg.in/yaml.v2 v2.4.0 // indirect - gopkg.in/yaml.v3 v3.0.1 // indirect gotest.tools/v3 v3.5.2 // indirect k8s.io/apiextensions-apiserver v0.37.0 // indirect k8s.io/code-generator v0.37.0 // indirect @@ -179,7 +177,7 @@ require ( k8s.io/klog/v2 v2.140.0 // indirect k8s.io/kube-openapi v0.0.0-20260721132016-d427ff9ee9ad // indirect k8s.io/streaming v0.37.2 // indirect - sigs.k8s.io/controller-tools v0.20.1 // indirect + sigs.k8s.io/controller-tools v0.22.0 // indirect sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 // indirect sigs.k8s.io/randfill v1.0.0 // indirect sigs.k8s.io/structured-merge-diff/v6 v6.4.2 // indirect diff --git a/operator/go.sum b/operator/go.sum index ecbd36300..ebef7a30b 100644 --- a/operator/go.sum +++ b/operator/go.sum @@ -387,14 +387,14 @@ github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vv github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE= github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU= github.com/onsi/ginkgo/v2 v2.1.3/go.mod h1:vw5CSIxN1JObi/U8gcbwft7ZxR2dgaR70JSE3/PpL4c= -github.com/onsi/ginkgo/v2 v2.27.4 h1:fcEcQW/A++6aZAZQNUmNjvA9PSOzefMJBerHJ4t8v8Y= -github.com/onsi/ginkgo/v2 v2.27.4/go.mod h1:ArE1D/XhNXBXCBkKOLkbsb2c81dQHCRcF5zwn/ykDRo= +github.com/onsi/ginkgo/v2 v2.32.1 h1:6tlvcDm/3sE8lGJbZ4+d4mO3RLy24/tQWOFzVSQNIfw= +github.com/onsi/ginkgo/v2 v2.32.1/go.mod h1:+aXOY+vzZ5mu2iI2HpTZUPmM//oQfsNFX6gU9kNcA44= github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= github.com/onsi/gomega v1.17.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY= github.com/onsi/gomega v1.19.0/go.mod h1:LY+I3pBVzYsTBU1AnDwOSxaYi9WoWiqgwooUqq9yPro= -github.com/onsi/gomega v1.39.0 h1:y2ROC3hKFmQZJNFeGAMeHZKkjBL65mIZcvrLQBF9k6Q= -github.com/onsi/gomega v1.39.0/go.mod h1:ZCU1pkQcXDO5Sl9/VVEGlDyp+zm0m1cmeG5TOzLgdh4= +github.com/onsi/gomega v1.43.0 h1:VlG/1FxqNxhSO+lq/OHBNaaqwiBK/mO8JbVkX9Y+FeU= +github.com/onsi/gomega v1.43.0/go.mod h1:REff/hsDsodHoKlWsP2mAPhu1+5/6hVYNf9rIEBpeSg= github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040= @@ -673,7 +673,6 @@ gopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRN gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= @@ -710,8 +709,8 @@ sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.36.0 h1:/YpDJ4vReG7Zm sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.36.0/go.mod h1:tJo1aepTXyR+8Xs3sUsGBDk4Ub2AM5dPAPKJx0mpm5c= sigs.k8s.io/controller-runtime v0.25.2 h1:bEkK3PVOIVK9X8QWLGVhJgmFc++47vfT6wakSzAOLsQ= sigs.k8s.io/controller-runtime v0.25.2/go.mod h1:4QqLdT6z/L6Olj8JJCtvztid4/fnIiYsfaTFScegctc= -sigs.k8s.io/controller-tools v0.20.1 h1:gkfMt9YodI0K85oT8rVi80NTXO/kDmabKR5Ajn5GYxs= -sigs.k8s.io/controller-tools v0.20.1/go.mod h1:b4qPmjGU3iZwqn34alUU5tILhNa9+VXK+J3QV0fT/uU= +sigs.k8s.io/controller-tools v0.22.0 h1:eG3FAVja/KnlXKIWg95udIFz1cMyAtMjP11cqBh3t+k= +sigs.k8s.io/controller-tools v0.22.0/go.mod h1:VizwUStoZK7rReCj704czGGrB7mLxXTiJSJt7wN5ilI= sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 h1:IpInykpT6ceI+QxKBbEflcR5EXP7sU1kvOlxwZh5txg= sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730/go.mod h1:mdzfpAEoE6DHQEN0uh9ZbOCuHbLK5wOm7dK4ctXE9Tg= sigs.k8s.io/randfill v1.0.0 h1:JfjMILfT8A6RbawdsK2JXGBR5AQVfd+9TbzrlneTyrU= From 997a7e34d7f52738583c4a47b523033a66b0f068 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 00:40:32 +0000 Subject: [PATCH 6/8] ci: note the path input for mcp in the go-component example Co-Authored-By: Claude Opus 5.5 Signed-off-by: Claude --- .github/workflows/go-component.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/go-component.yaml b/.github/workflows/go-component.yaml index bad3f9147..ee0005484 100644 --- a/.github/workflows/go-component.yaml +++ b/.github/workflows/go-component.yaml @@ -7,6 +7,7 @@ # uses: GameplanePanel/Gameplane/.github/workflows/go-component.yaml@ # master # with: # dockerfiles: Dockerfile +# # path: mcp-server # only when the repo name differs from its folder here (mcp) # # Lint uses this repository's root .golangci.yml and .hadolint.yaml, fetched # from master, so every component is linted by the same ruleset as Gameplane From c4dc856f52ad8cfa0664e7ee310e699fdbaf29f7 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 08:40:51 +0000 Subject: [PATCH 7/8] chore: bump tunnel, audit-syslog-bridge and mcp-server pointers tunnel picks up tunnel#1 (shared CI, tailscale.com v1.104.7 and Go 1.27.4 carried over from #982). audit-syslog-bridge#1 and mcp#1 add each repo's CI. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Claude --- audit-syslog-bridge | 2 +- mcp-server | 2 +- tunnel | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/audit-syslog-bridge b/audit-syslog-bridge index 7a5d30d1e..47f927d7e 160000 --- a/audit-syslog-bridge +++ b/audit-syslog-bridge @@ -1 +1 @@ -Subproject commit 7a5d30d1efc2631c9e7bc077f9e389c03513e9a9 +Subproject commit 47f927d7e11acab6d65f84fa1122ac1c2509a1cb diff --git a/mcp-server b/mcp-server index 8ee5b0fa9..cb6e85935 160000 --- a/mcp-server +++ b/mcp-server @@ -1 +1 @@ -Subproject commit 8ee5b0fa985bfa4bfe9f5ac5c4d8d5625db61f5b +Subproject commit cb6e859354093145d3e6cb7c00314fc18513034d diff --git a/tunnel b/tunnel index e8dcb5c45..f14bdbc19 160000 --- a/tunnel +++ b/tunnel @@ -1 +1 @@ -Subproject commit e8dcb5c45495ae948261d50db7cf0b5e82db93a6 +Subproject commit f14bdbc19e80a669ee7ab8125cef245c0a9bf839 From 8966ec9bbe280b70fef02e7e481ed2642a4995a2 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 08:42:24 +0000 Subject: [PATCH 8/8] chore: bump capture-sidecar and mcp-server pointers capture-sidecar#1 adds that repo's shared CI; mcp#2 moves mcp onto the shared go-component workflow. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Claude --- capture-sidecar | 2 +- mcp-server | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/capture-sidecar b/capture-sidecar index 1ef701cb1..f101c8a99 160000 --- a/capture-sidecar +++ b/capture-sidecar @@ -1 +1 @@ -Subproject commit 1ef701cb15dda75e907e8faf89ec0d9b42b7fbf0 +Subproject commit f101c8a99e882e77e2da30f375d972f02bae735c diff --git a/mcp-server b/mcp-server index cb6e85935..7f247f7c8 160000 --- a/mcp-server +++ b/mcp-server @@ -1 +1 @@ -Subproject commit cb6e859354093145d3e6cb7c00314fc18513034d +Subproject commit 7f247f7c8a7d92b512e5ff000717658f9ef24535