From 5f38fa9185b90f1c99d11944e9f94d0840dfaa72 Mon Sep 17 00:00:00 2001 From: Ted H Date: Sat, 14 Nov 2026 06:35:35 -0500 Subject: [PATCH 1/4] ci: cover filtered workflow inputs Agent: codex/gpt-6.1-terra --- .github/workflows/at-members.yml | 73 +++ .github/workflows/at-secops.yml | 47 ++ .github/workflows/at-usage.yml | 78 +++ .github/workflows/backup.yml | 10 + .github/workflows/contracts.yml | 6 + .github/workflows/dns.yml | 68 +++ .github/workflows/fleetupdate.yml | 4 +- .github/workflows/installer.yml | 76 +++ .github/workflows/portal.yml | 12 + tests/ci/commands_test.go | 32 ++ tests/ci/matcher_test.go | 138 ++++++ tests/ci/workflow_paths_test.go | 772 ++++++++++++++++++++++++++++++ 12 files changed, 1314 insertions(+), 2 deletions(-) create mode 100644 tests/ci/commands_test.go create mode 100644 tests/ci/matcher_test.go create mode 100644 tests/ci/workflow_paths_test.go diff --git a/.github/workflows/at-members.yml b/.github/workflows/at-members.yml index fb39a2ceb..03cb0e4d8 100644 --- a/.github/workflows/at-members.yml +++ b/.github/workflows/at-members.yml @@ -7,6 +7,79 @@ on: - docs/e2e/at/members/** - mk/at-members.mk - .github/workflows/at-members.yml + - apps/** + - contracts/* + - contracts/examples/policies/fair-use.json + - contracts/examples/valid/ObservationReport.json + - contracts/schemas/** + - db/** + - deploy/backup/postgres/** + - deploy/devstack/** + - docs/dns/BACKEND.md + - docs/poc/G2-f802-mtu1280-2026-10-31.md + - go.mod + - go.sum + - internal/audit/** + - internal/auth/** + - internal/billing/** + - internal/config/** + - internal/db/* + - internal/desiredstate/** + - internal/devices/** + - internal/dnsfeeds/** + - internal/dnspolicy/* + - internal/dnspublish/** + - internal/enrollment/** + - internal/entitlement/** + - internal/exits/** + - internal/fleetupdate/** + - internal/fup/** + - internal/httpapi/* + - internal/httpapi/gen/** + - internal/installerjob/** + - internal/leases/** + - internal/members/** + - internal/netbird/** + - internal/nodes/** + - internal/operations/** + - internal/pki/* + - internal/policies/* + - internal/policies/schemas/** + - internal/releases/* + - internal/signing/* + - internal/usage/* + - mk/e2e.mk + - node/agent/** + - node/dns/** + - node/enforce/** + - node/internal/agentstore/** + - node/internal/controlclient/** + - node/internal/healthattest/** + - node/internal/meter/** + - node/internal/nodelock/** + - node/internal/timeanchor/** + - node/internal/updatejournal/** + - node/internal/usagestore/** + - node/internal/usageupload/** + - node/nodelock/** + - node/updater/** + - node/watchdog/** + - packaging/installer/* + - packaging/release/* + - pkg/** + - tests/e2e/* + - tests/e2e/cmd/fvpn-e2e-control/** + - tests/e2e/cmd/fvpn-e2e-fixture-probe/** + - tests/e2e/cmd/fvpn-e2e-idp/** + - tests/e2e/cmd/fvpn-e2e-lease-read/** + - tests/e2e/cmd/fvpn-e2e-member-session/** + - tests/e2e/cmd/fvpn-e2e-native-observe/** + - tests/e2e/cmd/fvpn-e2e-nbbootstrap/** + - tests/e2e/cmd/fvpn-e2e-nodeconfig/** + - tests/e2e/cmd/fvpn-e2e-origin/** + - tests/e2e/cmd/fvpn-e2e-payment/** + - tests/e2e/cmd/fvpn-e2e-prepare/** + - tests/e2e/internal/** workflow_dispatch: permissions: diff --git a/.github/workflows/at-secops.yml b/.github/workflows/at-secops.yml index 1e459db05..f2b354968 100644 --- a/.github/workflows/at-secops.yml +++ b/.github/workflows/at-secops.yml @@ -6,6 +6,53 @@ on: - 'docs/e2e/at/secops/**' - 'mk/at-secops.mk' - '.github/workflows/at-secops.yml' + - 'contracts/*' + - 'contracts/examples/policies/fair-use.json' + - 'contracts/schemas/**' + - 'db/**' + - 'deploy/**' + - 'go.mod' + - 'go.sum' + - 'internal/audit/**' + - 'internal/auth/**' + - 'internal/billing/**' + - 'internal/config/**' + - 'internal/db/*' + - 'internal/db/dbtest/**' + - 'internal/devices/**' + - 'internal/entitlement/**' + - 'internal/httpapi/*' + - 'internal/httpapi/gen/**' + - 'internal/members/*' + - 'internal/members/issuer/**' + - 'internal/netbird/**' + - 'internal/nodes/*' + - 'internal/nodes/commandtx/**' + - 'internal/operations/**' + - 'internal/pki/**' + - 'internal/signing/*' + - 'internal/usage/*' + - 'internal/usage/cmd/**' + - 'node/agent/observe.go' + - 'node/agent/serving.go' + - 'node/agent/sync.go' + - 'node/enforce/**' + - 'node/internal/nodelock/**' + - 'node/internal/timeanchor/**' + - 'node/nodelock/**' + - 'node/watchdog/*' + - 'packaging/release/*' + - 'pkg/**' + - 'tests/e2e/*' + - 'tests/e2e/internal/counterread/**' + - 'tests/e2e/internal/dnsrelay/**' + - 'tests/e2e/internal/granttrace/**' + - 'tests/e2e/internal/idplogin/**' + - 'tests/e2e/internal/labstack/**' + - 'tests/e2e/internal/leasehold/**' + - 'tests/e2e/internal/nativecapture/**' + - 'tests/e2e/internal/offertrace/**' + - 'tests/e2e/internal/streamstats/**' workflow_dispatch: permissions: contents: read diff --git a/.github/workflows/at-usage.yml b/.github/workflows/at-usage.yml index 2cc666ef1..a000c0028 100644 --- a/.github/workflows/at-usage.yml +++ b/.github/workflows/at-usage.yml @@ -7,6 +7,84 @@ on: - docs/e2e/at/usage/** - mk/at-usage.mk - .github/workflows/at-usage.yml + - apps/** + - contracts/* + - contracts/schemas/** + - db/** + - deploy/backup/postgres/** + - deploy/devstack/** + - go.mod + - go.sum + - internal/audit/** + - internal/auth/** + - internal/billing/** + - internal/config/** + - internal/db/* + - internal/db/dbtest/** + - internal/desiredstate/** + - internal/devices/** + - internal/dnsfeeds/** + - internal/dnspolicy/* + - internal/dnspublish/** + - internal/enrollment/** + - internal/entitlement/** + - internal/exits/** + - internal/fleetupdate/** + - internal/fup/** + - internal/httpapi/* + - internal/httpapi/gen/** + - internal/installerjob/** + - internal/leases/** + - internal/members/** + - internal/netbird/** + - internal/nodes/** + - internal/operations/** + - internal/pki/* + - internal/policies/* + - internal/policies/schemas/** + - internal/releases/* + - internal/signing/* + - internal/usage/* + - internal/usage/cmd/** + - mk/e2e.mk + - node/agent/** + - node/dns/** + - node/enforce/** + - node/internal/agentstore/** + - node/internal/controlclient/** + - node/internal/fakecontrol/* + - node/internal/healthattest/** + - node/internal/meter/** + - node/internal/nodelock/** + - node/internal/timeanchor/** + - node/internal/updatejournal/** + - node/internal/usagestore/** + - node/internal/usageupload/** + - node/nodelock/** + - node/updater/** + - node/watchdog/** + - packaging/installer/* + - packaging/release/* + - pkg/** + - tests/e2e/* + - tests/e2e/cmd/fvpn-e2e-control/** + - tests/e2e/cmd/fvpn-e2e-idp/** + - tests/e2e/cmd/fvpn-e2e-nbbootstrap/** + - tests/e2e/cmd/fvpn-e2e-nodeconfig/** + - tests/e2e/cmd/fvpn-e2e-origin/** + - tests/e2e/cmd/fvpn-e2e-payment/** + - tests/e2e/cmd/fvpn-e2e-prepare/** + - tests/e2e/internal/agentwait/** + - tests/e2e/internal/counterread/** + - tests/e2e/internal/dnsrelay/** + - tests/e2e/internal/granttrace/** + - tests/e2e/internal/idplogin/** + - tests/e2e/internal/labtls/** + - tests/e2e/internal/leasehold/** + - tests/e2e/internal/nativecapture/** + - tests/e2e/internal/offertrace/** + - tests/e2e/internal/probeauth/** + - tests/e2e/internal/streamstats/** workflow_dispatch: permissions: diff --git a/.github/workflows/backup.yml b/.github/workflows/backup.yml index 7c2f19c1b..6deb92078 100644 --- a/.github/workflows/backup.yml +++ b/.github/workflows/backup.yml @@ -12,6 +12,11 @@ on: - "mk/backup.mk" - ".github/workflows/backup.yml" - "tests/backup/**" + - "db/**" + - "go.mod" + - "go.sum" + - "internal/db/*" + - "internal/db/cmd/fvpn-migrate/**" pull_request: paths: - "deploy/backup/**" @@ -23,6 +28,11 @@ on: - "mk/backup.mk" - ".github/workflows/backup.yml" - "tests/backup/**" + - "db/**" + - "go.mod" + - "go.sum" + - "internal/db/*" + - "internal/db/cmd/fvpn-migrate/**" workflow_dispatch: inputs: record_evidence: diff --git a/.github/workflows/contracts.yml b/.github/workflows/contracts.yml index d442c49ed..f6cf20df6 100644 --- a/.github/workflows/contracts.yml +++ b/.github/workflows/contracts.yml @@ -15,6 +15,9 @@ on: - '.github/workflows/contracts.yml' - 'go.mod' - 'go.sum' + - 'internal/dnspolicy/*' + - 'internal/dnspublish/*' + - 'internal/policies/schemas/**' pull_request: paths: - 'contracts/**' @@ -28,6 +31,9 @@ on: - '.github/workflows/contracts.yml' - 'go.mod' - 'go.sum' + - 'internal/dnspolicy/*' + - 'internal/dnspublish/*' + - 'internal/policies/schemas/**' permissions: contents: read diff --git a/.github/workflows/dns.yml b/.github/workflows/dns.yml index e1cb6c1db..8c37a9a01 100644 --- a/.github/workflows/dns.yml +++ b/.github/workflows/dns.yml @@ -22,6 +22,40 @@ on: - ".github/workflows/dns.yml" - "go.mod" - "go.sum" + - "apps/control/*" + - "apps/worker/**" + - "contracts/*" + - "contracts/examples/**" + - "contracts/schemas/**" + - "db/**" + - "docs/control/config.example.json" + - "internal/audit/**" + - "internal/auth/**" + - "internal/billing/**" + - "internal/config/**" + - "internal/db/*" + - "internal/db/dbtest/**" + - "internal/desiredstate/**" + - "internal/devices/**" + - "internal/enrollment/**" + - "internal/entitlement/**" + - "internal/exits/**" + - "internal/fleetupdate/**" + - "internal/fup/**" + - "internal/httpapi/*" + - "internal/httpapi/gen/**" + - "internal/installerjob/**" + - "internal/leases/**" + - "internal/members/**" + - "internal/netbird/**" + - "internal/nodes/**" + - "internal/operations/**" + - "internal/pki/**" + - "internal/releases/**" + - "internal/signing/*" + - "internal/usage/*" + - "internal/usage/usagetest/**" + - "pkg/**" pull_request: paths: - "internal/dnspolicy/**" @@ -43,6 +77,40 @@ on: - ".github/workflows/dns.yml" - "go.mod" - "go.sum" + - "apps/control/*" + - "apps/worker/**" + - "contracts/*" + - "contracts/examples/**" + - "contracts/schemas/**" + - "db/**" + - "docs/control/config.example.json" + - "internal/audit/**" + - "internal/auth/**" + - "internal/billing/**" + - "internal/config/**" + - "internal/db/*" + - "internal/db/dbtest/**" + - "internal/desiredstate/**" + - "internal/devices/**" + - "internal/enrollment/**" + - "internal/entitlement/**" + - "internal/exits/**" + - "internal/fleetupdate/**" + - "internal/fup/**" + - "internal/httpapi/*" + - "internal/httpapi/gen/**" + - "internal/installerjob/**" + - "internal/leases/**" + - "internal/members/**" + - "internal/netbird/**" + - "internal/nodes/**" + - "internal/operations/**" + - "internal/pki/**" + - "internal/releases/**" + - "internal/signing/*" + - "internal/usage/*" + - "internal/usage/usagetest/**" + - "pkg/**" workflow_dispatch: schedule: - cron: "15 3 * * *" diff --git a/.github/workflows/fleetupdate.yml b/.github/workflows/fleetupdate.yml index 123001585..28abede32 100644 --- a/.github/workflows/fleetupdate.yml +++ b/.github/workflows/fleetupdate.yml @@ -1,9 +1,9 @@ name: Central fleet updates on: push: - paths: ['internal/releases/**', 'internal/fleetupdate/**', 'internal/installerjob/**', 'internal/nodes/update_view.go', 'node/updater/**', 'db/migrations/**', 'contracts/**', 'pkg/**', 'go.*', 'mk/fleetupdate.mk', '.github/workflows/fleetupdate.yml'] + paths: ['internal/releases/**', 'internal/fleetupdate/**', 'internal/installerjob/**', 'internal/nodes/update_view.go', 'node/updater/**', 'db/migrations/**', 'contracts/**', 'pkg/**', 'go.*', 'mk/fleetupdate.mk', '.github/workflows/fleetupdate.yml', 'Makefile', 'apps/**', 'internal/**', 'mk/**', 'node/**', 'packaging/**', 'tests/backup/**', 'tests/ci/**', 'tests/e2e/*', 'tests/e2e/at/**', 'tests/e2e/cmd/**', 'tests/e2e/internal/agentwait/**', 'tests/e2e/internal/counterread/**', 'tests/e2e/internal/dnsrelay/**', 'tests/e2e/internal/granttrace/**', 'tests/e2e/internal/idplogin/**', 'tests/e2e/internal/labtls/**', 'tests/e2e/internal/leasehold/**', 'tests/e2e/internal/nativecapture/**', 'tests/e2e/internal/offertrace/**', 'tests/e2e/internal/probeauth/**', 'tests/e2e/internal/streamstats/**', 'tests/handover/**', 'tests/netlab/*', 'tests/netlab/at/**', 'tests/netlab/cmd/**', 'tests/netlab/dns/cmd/**', 'tests/netlab/dns/internal/**'] pull_request: - paths: ['internal/releases/**', 'internal/fleetupdate/**', 'internal/installerjob/**', 'internal/nodes/update_view.go', 'node/updater/**', 'db/migrations/**', 'contracts/**', 'pkg/**', 'go.*', 'mk/fleetupdate.mk', '.github/workflows/fleetupdate.yml'] + paths: ['internal/releases/**', 'internal/fleetupdate/**', 'internal/installerjob/**', 'internal/nodes/update_view.go', 'node/updater/**', 'db/migrations/**', 'contracts/**', 'pkg/**', 'go.*', 'mk/fleetupdate.mk', '.github/workflows/fleetupdate.yml', 'Makefile', 'apps/**', 'internal/**', 'mk/**', 'node/**', 'packaging/**', 'tests/backup/**', 'tests/ci/**', 'tests/e2e/*', 'tests/e2e/at/**', 'tests/e2e/cmd/**', 'tests/e2e/internal/agentwait/**', 'tests/e2e/internal/counterread/**', 'tests/e2e/internal/dnsrelay/**', 'tests/e2e/internal/granttrace/**', 'tests/e2e/internal/idplogin/**', 'tests/e2e/internal/labtls/**', 'tests/e2e/internal/leasehold/**', 'tests/e2e/internal/nativecapture/**', 'tests/e2e/internal/offertrace/**', 'tests/e2e/internal/probeauth/**', 'tests/e2e/internal/streamstats/**', 'tests/handover/**', 'tests/netlab/*', 'tests/netlab/at/**', 'tests/netlab/cmd/**', 'tests/netlab/dns/cmd/**', 'tests/netlab/dns/internal/**'] permissions: contents: read jobs: diff --git a/.github/workflows/installer.yml b/.github/workflows/installer.yml index d75e146d7..19039a86f 100644 --- a/.github/workflows/installer.yml +++ b/.github/workflows/installer.yml @@ -14,6 +14,44 @@ on: - .github/workflows/installer.yml - go.mod - go.sum + - contracts/* + - contracts/schemas/** + - db/** + - internal/audit/** + - internal/auth/** + - internal/billing/** + - internal/config/** + - internal/db/* + - internal/dnspolicy/* + - internal/dnspublish/* + - internal/entitlement/** + - internal/httpapi/* + - internal/httpapi/gen/** + - internal/installerjob/** + - internal/members/issuer/** + - internal/nodes/commandtx/** + - internal/operations/** + - internal/pki/** + - internal/signing/* + - node/agent/* + - node/dns/** + - node/enforce/** + - node/internal/agentstore/** + - node/internal/controlclient/** + - node/internal/fakecontrol/* + - node/internal/healthattest/** + - node/internal/meter/** + - node/internal/nodelock/** + - node/internal/timeanchor/** + - node/internal/updatejournal/** + - node/internal/usagestore/** + - node/internal/usageupload/** + - node/nodelock/** + - node/updater/* + - node/updater/fsutil/** + - node/watchdog/* + - packaging/release/* + - pkg/** pull_request: paths: - packaging/installer/** @@ -25,6 +63,44 @@ on: - .github/workflows/installer.yml - go.mod - go.sum + - contracts/* + - contracts/schemas/** + - db/** + - internal/audit/** + - internal/auth/** + - internal/billing/** + - internal/config/** + - internal/db/* + - internal/dnspolicy/* + - internal/dnspublish/* + - internal/entitlement/** + - internal/httpapi/* + - internal/httpapi/gen/** + - internal/installerjob/** + - internal/members/issuer/** + - internal/nodes/commandtx/** + - internal/operations/** + - internal/pki/** + - internal/signing/* + - node/agent/* + - node/dns/** + - node/enforce/** + - node/internal/agentstore/** + - node/internal/controlclient/** + - node/internal/fakecontrol/* + - node/internal/healthattest/** + - node/internal/meter/** + - node/internal/nodelock/** + - node/internal/timeanchor/** + - node/internal/updatejournal/** + - node/internal/usagestore/** + - node/internal/usageupload/** + - node/nodelock/** + - node/updater/* + - node/updater/fsutil/** + - node/watchdog/* + - packaging/release/* + - pkg/** permissions: contents: read jobs: diff --git a/.github/workflows/portal.yml b/.github/workflows/portal.yml index 047c40673..d19d160df 100644 --- a/.github/workflows/portal.yml +++ b/.github/workflows/portal.yml @@ -17,6 +17,12 @@ on: - 'docs/portal/**' - 'mk/portal.mk' - '.github/workflows/portal.yml' + - 'contracts/*' + - 'contracts/schemas/**' + - 'contracts/vectors/release-manifest-signing.json' + - 'db/**' + - 'go.mod' + - 'go.sum' pull_request: paths: - 'apps/portal/**' @@ -29,6 +35,12 @@ on: - 'docs/portal/**' - 'mk/portal.mk' - '.github/workflows/portal.yml' + - 'contracts/*' + - 'contracts/schemas/**' + - 'contracts/vectors/release-manifest-signing.json' + - 'db/**' + - 'go.mod' + - 'go.sum' jobs: portal: diff --git a/tests/ci/commands_test.go b/tests/ci/commands_test.go new file mode 100644 index 000000000..182e707b6 --- /dev/null +++ b/tests/ci/commands_test.go @@ -0,0 +1,32 @@ +package ci + +import ( + "reflect" + "testing" +) + +func TestMakeGoCommandExtraction(t *testing.T) { + commands := `go test -tags=e2e -o ./generated.test ./tests/e2e/at/usage/... ./pkg/new +for pkg in ./one ./two; do go build -o ./bin/output $pkg; done +go run honnef.co/go/tools/cmd/staticcheck@v0.8.2 -tags integration ./internal/example/...` + requests, tests := map[string]map[string]bool{}, map[string]map[string]bool{} + if err := parseGoCommands(commands, requests, tests); err != nil { + t.Fatal(err) + } + want := map[string][]string{ + "": {"./one", "./two"}, + "e2e": {"./pkg/new", "./tests/e2e/at/usage/..."}, + "integration": {"./internal/example/..."}, + } + for tags, packages := range want { + if got := sortedKeys(requests[tags]); !reflect.DeepEqual(got, packages) { + t.Errorf("tags %q: got %v, want %v", tags, got, packages) + } + } + if got := sortedKeys(tests["e2e"]); !reflect.DeepEqual(got, want["e2e"]) { + t.Errorf("tested packages = %v, want %v", got, want["e2e"]) + } + if err := parseGoCommands("go test $unknown", requests, tests); err == nil { + t.Error("unresolved test package should fail closed") + } +} diff --git a/tests/ci/matcher_test.go b/tests/ci/matcher_test.go new file mode 100644 index 000000000..97da57d40 --- /dev/null +++ b/tests/ci/matcher_test.go @@ -0,0 +1,138 @@ +package ci + +import ( + "fmt" + "regexp" + "strings" + "testing" + "unicode/utf8" + + "gopkg.in/yaml.v3" +) + +// workflowMatch applies patterns in order, including re-inclusions after an +// exclusion. The supported metacharacters are the ones used by these filters. +type compiledPattern struct { + re *regexp.Regexp + negative bool +} + +func compilePatterns(patterns []string) ([]compiledPattern, error) { + var compiled []compiledPattern + for _, pattern := range patterns { + negative := strings.HasPrefix(pattern, "!") + if negative { + pattern = pattern[1:] + } + var re strings.Builder + re.WriteByte('^') + for i := 0; i < len(pattern); i++ { + switch pattern[i] { + case '*': + if i+1 < len(pattern) && pattern[i+1] == '*' { + i++ + if i+1 < len(pattern) && pattern[i+1] == '/' { + i++ + re.WriteString("(.*/)?") + } else { + re.WriteString(".*") + } + } else { + re.WriteString("[^/]*") + } + case '?': + re.WriteString("[^/]") + default: + r, size := utf8.DecodeRuneInString(pattern[i:]) + re.WriteString(regexp.QuoteMeta(string(r))) + i += size - 1 + } + } + re.WriteByte('$') + matcher, err := regexp.Compile(re.String()) + if err != nil { + return nil, fmt.Errorf("pattern %q: %w", pattern, err) + } + compiled = append(compiled, compiledPattern{matcher, negative}) + } + return compiled, nil +} + +func matches(patterns []compiledPattern, path string) bool { + matched := false + for _, pattern := range patterns { + if pattern.re.MatchString(path) { + matched = !pattern.negative + } + } + return matched +} + +func workflowMatch(patterns []string, path string) (bool, error) { + compiled, err := compilePatterns(patterns) + return matches(compiled, path), err +} + +type eventFilter struct { + Paths []string `yaml:"paths"` + PathsIgnore []string `yaml:"paths-ignore"` +} + +func (e eventFilter) includes(path string) (bool, error) { + if len(e.Paths) > 0 && len(e.PathsIgnore) > 0 { + return false, fmt.Errorf("paths and paths-ignore cannot coexist") + } + if len(e.Paths) > 0 { + return workflowMatch(e.Paths, path) + } + if len(e.PathsIgnore) > 0 { + ignored, err := workflowMatch(e.PathsIgnore, path) + return !ignored, err + } + return true, nil +} + +func TestWorkflowMatcher(t *testing.T) { + tests := []struct { + name string + filter eventFilter + path string + included bool + }{ + {"star", eventFilter{Paths: []string{"a/*.go"}}, "a/file.go", true}, + {"star stops at slash", eventFilter{Paths: []string{"a/*.go"}}, "a/sub/file.go", false}, + {"globstar nested", eventFilter{Paths: []string{"a/**"}}, "a/sub/file.go", true}, + {"globstar zero directories", eventFilter{Paths: []string{"a/**/file.go"}}, "a/file.go", true}, + {"globstar more directories", eventFilter{Paths: []string{"a/**/file.go"}}, "a/b/c/file.go", true}, + {"question mark", eventFilter{Paths: []string{"a/?.go"}}, "a/x.go", true}, + {"unicode literal and wildcard", eventFilter{Paths: []string{"文件/?.go"}}, "文件/測.go", true}, + {"question mark stops at slash", eventFilter{Paths: []string{"a?b"}}, "a/b", false}, + {"exclude", eventFilter{Paths: []string{"a/**", "!a/private/**"}}, "a/private/x", false}, + {"last inclusion wins", eventFilter{Paths: []string{"a/**", "!a/private/**", "a/private/keep"}}, "a/private/keep", true}, + {"last exclusion wins", eventFilter{Paths: []string{"a/private/keep", "!a/**"}}, "a/private/keep", false}, + {"ignore matches", eventFilter{PathsIgnore: []string{"docs/**"}}, "docs/x", false}, + {"ignore does not match", eventFilter{PathsIgnore: []string{"docs/**"}}, "pkg/x", true}, + {"no filter", eventFilter{}, "pkg/x", true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := tt.filter.includes(tt.path) + if err != nil || got != tt.included { + t.Fatalf("includes(%q) = %v, %v; want %v", tt.path, got, err, tt.included) + } + }) + } + if _, err := (eventFilter{Paths: []string{"**"}, PathsIgnore: []string{"x"}}).includes("x"); err == nil { + t.Fatal("paths and paths-ignore together must be rejected") + } +} + +func TestYAMLOnIsString(t *testing.T) { + var doc map[string]any + if err := yaml.Unmarshal([]byte("on:\n pull_request:\n paths: ['x/**']\n"), &doc); err != nil { + t.Fatal(err) + } + if _, ok := doc["on"]; !ok { + t.Fatalf("yaml.v3 did not decode on as a string key: %#v", doc) + } +} diff --git a/tests/ci/workflow_paths_test.go b/tests/ci/workflow_paths_test.go new file mode 100644 index 000000000..ddf4a7620 --- /dev/null +++ b/tests/ci/workflow_paths_test.go @@ -0,0 +1,772 @@ +package ci + +import ( + "bytes" + "encoding/json" + "fmt" + "go/parser" + "go/token" + "io" + "net/url" + "os" + "os/exec" + "path/filepath" + "regexp" + "sort" + "strconv" + "strings" + "testing" + + "gopkg.in/yaml.v3" +) + +const modulePath = "github.com/TED-H-com/Freedom-VPN/" + +type workflow struct { + On map[string]yaml.Node `yaml:"on"` + Jobs map[string]struct { + Steps []struct { + Run string `yaml:"run"` + } `yaml:"steps"` + } `yaml:"jobs"` +} + +// These are the inputs hidden behind scripts or test processes. Packages in +// make recipes are deliberately NOT enumerated here: they are read from make. +// Source roots are scanned for new literal commands and repository paths. +type indirect struct { + packages []string + files []string // exact files or directories ending in /** + sources []string // files or trees containing the indirect references + fixture string // source copied into a temporary module +} + +var stackPackages = []string{ + "./tests/e2e/cmd/fvpn-e2e-prepare", "./apps/control/cmd/fvpn-control", + "./apps/worker/cmd/fvpn-worker", "./node/agent/cmd/fvpn-agent", + "./node/watchdog/cmd/fvpn-watchdog", "./node/updater/cmd/fvpn-updater", + "./tests/e2e/cmd/fvpn-e2e-idp", "./tests/e2e/cmd/fvpn-e2e-payment", + "./tests/e2e/cmd/fvpn-e2e-nodeconfig", "./tests/e2e/cmd/fvpn-e2e-origin", + "./tests/e2e/cmd/fvpn-e2e-nbbootstrap", "./tests/e2e/cmd/fvpn-e2e-control", +} + +var usagePackages = []string{ + "./internal/usage/cmd/fvpn-usage-admin", "./node/internal/meter", + "./node/internal/usagestore", "./node/internal/usageupload", +} + +func together(lists ...[]string) []string { + var out []string + for _, list := range lists { + out = append(out, list...) + } + return out +} + +var indirectInputs = map[string]map[string]indirect{ + "at-members": { + "verify": {packages: []string{"./tests/e2e/at/members/cmd/probe"}, files: []string{"tests/e2e/at/members/**", "docs/e2e/at/members/**", "deploy/devstack/probe-portal.mjs", "docs/dns/BACKEND.md", "docs/poc/G2-f802-mtu1280-2026-10-31.md", "contracts/examples/valid/ObservationReport.json", "contracts/examples/policies/fair-use.json"}, sources: []string{"tests/e2e/at/members"}}, + "assigned-stack": {packages: together(stackPackages, []string{"./tests/e2e/at/members/cmd/probe"}), files: []string{"mk/e2e.mk", "deploy/devstack/**", "deploy/backup/postgres/**", "apps/portal/**", "tests/e2e/at/members/**", "docs/e2e/at/members/**", "docs/dns/BACKEND.md", "docs/poc/G2-f802-mtu1280-2026-10-31.md", "contracts/examples/valid/ObservationReport.json", "contracts/examples/policies/fair-use.json"}, sources: []string{"deploy/devstack", "tests/e2e/at/members"}}, + }, + "at-usage": { + "verify": {packages: usagePackages, files: []string{"tests/e2e/at/usage/**", "docs/e2e/at/usage/**"}, sources: []string{"tests/e2e/at/usage"}}, + "assigned-stack": {packages: together(stackPackages, usagePackages), files: []string{"mk/e2e.mk", "deploy/devstack/**", "deploy/backup/postgres/**", "apps/portal/**", "tests/e2e/at/usage/**", "docs/e2e/at/usage/**"}, sources: []string{"deploy/devstack", "tests/e2e/at/usage"}}, + }, + "at-secops": { + "component-checks": {packages: []string{"./tests/e2e/at/secops/leaseprobe", "./tests/e2e/at/secops/proxyprobe", "./internal/usage/cmd/fvpn-usage-admin"}, files: []string{"tests/e2e/at/secops/**", "docs/e2e/at/secops/**", "node/agent/observe.go", "node/agent/sync.go", "node/agent/serving.go", "deploy/devstack/nginx.conf", "deploy/backup/restore-pitr.sh", "deploy/backup/post-restore-checklist.sql", "deploy/backup/backup.sh", "contracts/examples/policies/fair-use.json"}, sources: []string{"tests/e2e/at/secops"}}, + }, + "backup": { + "lint-and-unit": {packages: []string{"./internal/db/cmd/fvpn-migrate"}, files: []string{"deploy/backup/**", "tests/backup/**", "docs/ops/backups.md", "docs/handover/restore-drill.md"}, sources: []string{"tests/backup", "deploy/backup"}}, + "pitr-drill": {packages: []string{"./internal/db/cmd/fvpn-migrate"}, files: []string{"deploy/backup/**", "tests/backup/**", "docs/ops/backups.md", "docs/handover/restore-drill.md"}, sources: []string{"tests/backup", "deploy/backup"}}, + }, + "contracts": { + "contracts": {files: []string{"contracts/**", "docs/contracts/**", "internal/policies/schemas/**"}, sources: []string{"contracts"}}, + }, + "dns": { + "unit": {packages: []string{"./internal/dnspolicy/cmd/bootstrap", "./tests/netlab/dns/cmd/cache-authority"}, files: []string{"deploy/dev/adguard/**", "tests/netlab/dns/**", "docs/dns/BACKEND.md", "docs/control/config.example.json", "contracts/examples/valid/ResolverDocument.json", "contracts/examples/valid/ResolverDocumentRef.json", "contracts/examples/valid/DnsPolicyEvidence.json"}, sources: []string{"tests/netlab/dns"}}, + "integration": {packages: []string{"./internal/dnspolicy/cmd/bootstrap"}, files: []string{"deploy/dev/adguard/**"}, sources: []string{"deploy/dev/adguard"}}, + "publish": {files: []string{"contracts/examples/valid/ObservationReport.json", "contracts/examples/valid/ResolverDocument.json", "contracts/examples/valid/ResolverDocumentRef.json", "contracts/examples/valid/DnsPolicyEvidence.json", "contracts/examples/valid/ThreatFeedPayload.default-null-attribution.json", "contracts/examples/valid/PolicyRevisionCreate.feed-default-null-attribution.json"}}, + "lab": {packages: []string{"./internal/dnspolicy/cmd/bootstrap", "./tests/netlab/dns/cmd/cache-authority"}, files: []string{"deploy/dev/adguard/**", "tests/netlab/dns/**", "docs/dns/BACKEND.md"}, sources: []string{"tests/netlab/dns"}}, + }, + "fleetupdate": {"verify": {files: []string{"Makefile", "mk/**", "contracts/examples/valid/ObservationReport.json", "contracts/examples/valid/UpdateResult.installer.json", "contracts/vectors/release-manifest-signing.json"}}}, + "installer": { + "verify": {files: []string{"tests/installer/**", "deploy/node/**"}, sources: []string{"tests/installer/control-build.py"}, fixture: "tests/installer/cmd/fvpn-w5-control"}, + }, + "portal": { + "portal": {packages: []string{"./apps/control/cmd/fvpn-control", "./apps/worker/cmd/fvpn-worker"}, files: []string{"apps/portal/**", "contracts/vectors/release-manifest-signing.json", "internal/fleetupdate/testdata/at26-direct-rollback.json", "internal/netbird/testdata/**"}, sources: []string{"apps/portal/e2e/dev-stack.mjs", "apps/portal/playwright.config.ts"}}, + }, +} + +var ( + makeLine = regexp.MustCompile(`\bmake\s+((?:-f\s+[^\s]+\s+)?[a-zA-Z0-9_.-]+(?:\s+[a-zA-Z0-9_.-]+)*)`) + goCommand = regexp.MustCompile(`\bgo\s+(test|build|vet|run|install)\b([^;\n]*)`) + goTags = regexp.MustCompile(`(?:^|\s)-tags(?:=|\s+)([a-zA-Z0-9_,]+)`) + localPkg = regexp.MustCompile(`(?:^|[^a-zA-Z0-9_])((?:\./)[a-zA-Z0-9_./-]*)`) + forLoop = regexp.MustCompile(`\bfor\s+([a-zA-Z_][a-zA-Z0-9_]*)\s+in\s+([^;]+);`) + quotedPkg = regexp.MustCompile(`["'` + "`" + `](\./[a-zA-Z0-9_./-]+)["'` + "`" + `]`) + quotedPath = regexp.MustCompile(`["'` + "`" + `]((?:\.\./|(?:contracts|internal|pkg|node|apps|deploy|tests|docs|mk)/)[a-zA-Z0-9_./*+-]+)`) + quotedGo = regexp.MustCompile(`["']go["']\s*,\s*\[?\s*["'](?:build|run|install|test)["']`) + scriptPath = regexp.MustCompile(`\b((?:tests|deploy|contracts|apps)/[a-zA-Z0-9_./-]+\.(?:sh|py|mjs|ts))\b`) +) + +func addRequest(dst map[string]map[string]bool, tags string, pkgs ...string) { + if dst[tags] == nil { + dst[tags] = make(map[string]bool) + } + for _, p := range pkgs { + if p != "" { + dst[tags][p] = true + } + } +} + +// Commands are taken from make -n, including literal loop lists used by build +// and coverage recipes. A new, unrecognized variable package fails closed. +func parseGoCommands(text string, dst, tests map[string]map[string]bool) error { + text = strings.ReplaceAll(text, "\\\n", " ") + loops := map[string][]string{} + for _, loop := range forLoop.FindAllStringSubmatch(text, -1) { + for _, p := range localPkg.FindAllStringSubmatch(loop[2], -1) { + loops[loop[1]] = append(loops[loop[1]], p[1]) + } + } + for _, command := range goCommand.FindAllStringSubmatch(text, -1) { + args := command[2] + tags := "" + if m := goTags.FindStringSubmatch(args); m != nil { + tags = m[1] + } + var pkgs []string + skipValue := false + for _, field := range strings.Fields(args) { + field = strings.Trim(field, "\"'()\\") + if skipValue { + skipValue = false + continue + } + switch field { + case "-o", "-coverprofile", "-cpuprofile", "-memprofile", "-trace", "-outputdir", "-overlay", "-modfile": + skipValue = true + continue + } + if strings.HasPrefix(field, "./") { + pkgs = append(pkgs, field) + } + } + for variable, values := range loops { + if regexp.MustCompile(`\$\{?` + regexp.QuoteMeta(variable) + `\}?\b`).MatchString(args) { + pkgs = append(pkgs, values...) + } + } + if len(pkgs) == 0 && command[1] != "run" { + return fmt.Errorf("cannot derive package arguments from go %s%s", command[1], args) + } + addRequest(dst, tags, pkgs...) + if command[1] == "test" { + addRequest(tests, tags, pkgs...) + } + } + return nil +} + +// The selected targets have no recursive-make or '+' recipes. Recheck this +// before dry-running: make executes those recipes even with -n. The only +// make-level shell functions currently in these files are read-only id calls. +func safeMake(root, file string, targets []string) error { + files := []string{file} + if file == "Makefile" { + more, err := filepath.Glob(filepath.Join(root, "mk", "*.mk")) + if err != nil { + return err + } + for _, path := range more { + rel, err := filepath.Rel(root, path) + if err != nil { + return err + } + files = append(files, rel) + } + } + for _, name := range files { + b, err := os.ReadFile(filepath.Join(root, name)) + if err != nil { + return err + } + s := strings.ReplaceAll(strings.ReplaceAll(string(b), "$(shell id -u)", ""), "$(shell id -g)", "") + if strings.Contains(s, "$(shell") || strings.Contains(s, "${shell") { + return fmt.Errorf("%s contains an unaudited make shell function", name) + } + if strings.Contains(s, "$(file ") || strings.Contains(s, "${file ") || strings.Contains(s, "$(eval ") || regexp.MustCompile(`(?m)^[^#\n]*\s!=`).MatchString(s) { + return fmt.Errorf("%s contains unaudited make expansion", name) + } + for _, line := range strings.Split(s, "\n") { + if regexp.MustCompile(`^\s*(-?include|sinclude)\s+`).MatchString(line) && line != "include $(wildcard mk/*.mk)" { + return fmt.Errorf("%s contains an unaudited make include", name) + } + } + if regexp.MustCompile(`(?m)^\t[@-]*\+`).MatchString(s) { + return fmt.Errorf("%s contains an always-executed recipe", name) + } + } + // Traverse literal prerequisites too: recursive recipes in prerequisites + // also execute under -n. Unknown variable prerequisites require review. + type rule struct { + deps []string + recursive bool + } + rules := map[string]rule{} + ruleLine := regexp.MustCompile(`^([a-zA-Z0-9_.-]+):\s*([^#]*)`) + for _, name := range files { + b, err := os.ReadFile(filepath.Join(root, name)) + if err != nil { + return err + } + lines := strings.Split(string(b), "\n") + active := "" + for _, line := range lines { + if match := ruleLine.FindStringSubmatch(line); match != nil { + active = match[1] + r := rules[active] + r.deps = append(r.deps, strings.Fields(match[2])...) + rules[active] = r + } else if len(line) > 0 && line[0] != '\t' && !strings.HasPrefix(line, "#") { + active = "" + } + if active != "" && strings.HasPrefix(line, "\t") && (strings.Contains(line, "$(MAKE)") || strings.Contains(line, "${MAKE}")) { + r := rules[active] + r.recursive = true + rules[active] = r + } + } + } + seen := map[string]bool{} + var visit func(string) error + visit = func(target string) error { + if seen[target] { + return nil + } + seen[target] = true + r, ok := rules[target] + if !ok { + return nil + } + if r.recursive { + return fmt.Errorf("recursive make in selected target %s", target) + } + for _, dep := range r.deps { + if strings.ContainsAny(dep, "$%") { + return fmt.Errorf("unaudited prerequisite %q in %s", dep, target) + } + if dep != "|" { + if err := visit(dep); err != nil { + return err + } + } + } + return nil + } + for _, target := range targets { + if err := visit(target); err != nil { + return err + } + } + return nil +} + +func recordScripts(text string, scripts map[string]bool) { + for _, match := range scriptPath.FindAllStringSubmatch(text, -1) { + scripts[match[1]] = true + } +} + +func commandsFromStep(root, run string, requests, tests map[string]map[string]bool, files, scripts map[string]bool) error { + recordScripts(run, scripts) + if err := parseGoCommands(run, requests, tests); err != nil { + return err + } + for _, match := range makeLine.FindAllStringSubmatch(run, -1) { + fields := strings.Fields(match[1]) + makefile := "Makefile" + if len(fields) >= 2 && fields[0] == "-f" { + makefile, fields = fields[1], fields[2:] + } + if len(fields) == 0 { + return fmt.Errorf("no make target in %q", match[0]) + } + if err := safeMake(root, makefile, fields); err != nil { + return err + } + args := append([]string{"-n", "-f", makefile}, fields...) + cmd := exec.Command("make", args...) + cmd.Dir = root + out, err := cmd.CombinedOutput() + if err != nil { + return fmt.Errorf("make dry run %q: %w: %s", match[0], err, out) + } + files[makefile] = true + recordScripts(string(out), scripts) + if err := parseGoCommands(string(out), requests, tests); err != nil { + return fmt.Errorf("%s: %w", match[0], err) + } + } + return nil +} + +type listedPackage struct { + Dir string + ImportPath string + EmbedFiles []string + TestEmbedFiles []string + XTestEmbedFiles []string + TestGoFiles []string + XTestGoFiles []string +} + +type inventory struct { + dirs map[string]bool + files map[string]bool +} + +func listPackages(root, tags, arch, proxy string, pkgs []string) (inventory, error) { + result := inventory{dirs: map[string]bool{}, files: map[string]bool{}} + if len(pkgs) == 0 { + return result, nil + } + args := []string{"list", "-deps", "-test", "-json"} + if tags != "" { + args = append(args, "-tags="+tags) + } + args = append(args, pkgs...) + cmd := exec.Command("go", args...) + cmd.Dir = root + cmd.Env = append(os.Environ(), "GOOS=linux", "GOARCH="+arch, "GOPROXY="+proxy, "GOSUMDB=off") + var stderr bytes.Buffer + cmd.Stderr = &stderr + out, err := cmd.Output() + if err != nil { + return result, fmt.Errorf("go %s: %w: %s", strings.Join(args, " "), err, stderr.String()) + } + dec := json.NewDecoder(bytes.NewReader(out)) + for { + var p listedPackage + if err := dec.Decode(&p); err != nil { + if err == io.EOF { + break + } + return result, err + } + rel, err := filepath.Rel(root, p.Dir) + if err != nil || rel == "." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) || filepath.IsAbs(rel) { + continue + } + rel = filepath.ToSlash(rel) + result.dirs[rel] = true + for _, f := range together(p.EmbedFiles, p.TestEmbedFiles, p.XTestEmbedFiles) { + result.files[rel+"/"+filepath.ToSlash(f)] = true + } + } + return result, nil +} + +// Only the explicitly tested packages execute their tests. Dependency tests +// in go list -deps -test are compiled for type analysis, not executed. +func testSources(root, tags, proxy string, pkgs []string) ([]string, error) { + if len(pkgs) == 0 { + return nil, nil + } + args := []string{"list", "-json"} + if tags != "" { + args = append(args, "-tags="+tags) + } + args = append(args, pkgs...) + cmd := exec.Command("go", args...) + cmd.Dir = root + cmd.Env = append(os.Environ(), "GOOS=linux", "GOARCH=amd64", "GOPROXY="+proxy, "GOSUMDB=off") + var stderr bytes.Buffer + cmd.Stderr = &stderr + out, err := cmd.Output() + if err != nil { + return nil, fmt.Errorf("go %s: %w: %s", strings.Join(args, " "), err, stderr.String()) + } + dec := json.NewDecoder(bytes.NewReader(out)) + var files []string + for { + var p listedPackage + if err := dec.Decode(&p); err != nil { + if err == io.EOF { + break + } + return nil, err + } + for _, f := range together(p.TestGoFiles, p.XTestGoFiles) { + file, err := filepath.Rel(root, filepath.Join(p.Dir, f)) + if err == nil && !strings.HasPrefix(file, "..") { + files = append(files, file) + } + } + } + return files, nil +} + +func fixtureImports(root, dir string) ([]string, error) { + entries, err := filepath.Glob(filepath.Join(root, dir, "*.go")) + if err != nil { + return nil, err + } + if len(entries) == 0 { + return nil, fmt.Errorf("fixture %s has no Go source", dir) + } + var imports []string + for _, file := range entries { + parsed, err := parser.ParseFile(token.NewFileSet(), file, nil, parser.ImportsOnly) + if err != nil { + return nil, err + } + for _, spec := range parsed.Imports { + path, err := strconv.Unquote(spec.Path.Value) + if err != nil { + return nil, err + } + if strings.HasPrefix(path, modulePath) { + imports = append(imports, "./"+strings.TrimPrefix(path, modulePath)) + } + } + } + return imports, nil +} + +func sourceFiles(root string, sources []string) ([]string, error) { + files := map[string]bool{} + for _, source := range sources { + p := filepath.Join(root, source) + err := filepath.WalkDir(p, func(path string, entry os.DirEntry, err error) error { + if err != nil { + return err + } + if entry.IsDir() { + if entry.Name() == "node_modules" || entry.Name() == "testdata" { + return filepath.SkipDir + } + return nil + } + switch filepath.Ext(path) { + case ".go", ".sh", ".mjs": + files[path] = true + case ".ts": + if !strings.HasSuffix(path, ".d.ts") { + files[path] = true + } + case ".py": + if path == p || strings.HasPrefix(entry.Name(), "test_") { + files[path] = true + } + } + return nil + }) + if err != nil { + return nil, err + } + } + return sortedKeys(files), nil +} + +// Literal scanning is intentionally conservative; computed paths and shell +// indirection still need the explicit inventory above and human review. +func scanSources(root string, in indirect, knownDirs, knownFiles map[string]bool) ([]string, error) { + files, err := sourceFiles(root, in.sources) + if err != nil { + return nil, err + } + known := map[string]bool{} + for _, p := range in.packages { + known[p] = true + } + var problems []string + for _, file := range files { + data, err := os.ReadFile(file) + if err != nil { + return nil, err + } + rel, err := filepath.Rel(root, file) + if err != nil { + return nil, err + } + lines := strings.Split(string(data), "\n") + for i, line := range lines { + trimmed := strings.TrimSpace(line) + if strings.HasPrefix(trimmed, "//") || strings.HasPrefix(trimmed, "#") { + continue + } + if goCommand.MatchString(line) || quotedGo.MatchString(line) || strings.Contains(line, "build_one ./") { + end := min(i+5, len(lines)) + window := strings.Join(lines[i:end], "\n") + pkgs := quotedPkg.FindAllStringSubmatch(window, -1) + for _, p := range localPkg.FindAllStringSubmatch(line, -1) { + pkgs = append(pkgs, []string{"", p[1]}) + } + for _, p := range pkgs { + candidate := strings.TrimSuffix(p[1], "/") + if !known[candidate] && !knownDirs[strings.TrimPrefix(candidate, "./")] { + if info, err := os.Stat(filepath.Join(root, candidate)); err == nil && info.IsDir() { + problems = append(problems, fmt.Sprintf("%s:%d: runtime package %s is missing from indirect table", filepath.ToSlash(rel), i+1, candidate)) + } + } + } + } + for _, match := range quotedPath.FindAllStringSubmatch(line, -1) { + candidate := match[1] + if strings.Contains(candidate, "*") { + continue + } + path := filepath.Join(root, candidate) + if strings.HasPrefix(candidate, "../") { + path = filepath.Join(filepath.Dir(file), candidate) + } + info, err := os.Stat(path) + if err != nil || info.IsDir() { + continue + } + path, err = filepath.Rel(root, path) + if err != nil || strings.HasPrefix(path, "..") { + continue + } + path = filepath.ToSlash(path) + // This literal is a process-name comparison, not a file read. + if filepath.ToSlash(rel) == "tests/e2e/at/members/admission.py" && path == "mk/at-isolation.mk" && strings.Contains(line, "term in matches[p]") { + continue + } + ok, err := workflowMatch(in.files, path) + if err != nil { + return nil, err + } + if !ok && !knownFiles[path] && !knownDirs[filepath.ToSlash(filepath.Dir(path))] { + problems = append(problems, fmt.Sprintf("%s:%d: repository path %s is missing from indirect table", filepath.ToSlash(rel), i+1, path)) + } + } + } + } + return problems, nil +} + +func sortedKeys(m map[string]bool) []string { + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + sort.Strings(keys) + return keys +} + +func TestWorkflowPaths(t *testing.T) { + root, err := filepath.Abs("../..") + if err != nil { + t.Fatal(err) + } + // A file-only module proxy lets go list use the local download cache while + // guaranteeing that this test never contacts a proxy or checksum server. + cacheCmd := exec.Command("go", "env", "GOMODCACHE") + cacheCmd.Dir = root + cachePath, err := cacheCmd.Output() + if err != nil { + t.Fatalf("go env GOMODCACHE: %v", err) + } + proxy := (&url.URL{Scheme: "file", Path: filepath.ToSlash(filepath.Join(strings.TrimSpace(string(cachePath)), "cache", "download"))}).String() + cache := map[string]inventory{} + names := make([]string, 0, len(indirectInputs)) + for name := range indirectInputs { + names = append(names, name) + } + sort.Strings(names) + for _, name := range names { + path := ".github/workflows/" + name + ".yml" + data, err := os.ReadFile(filepath.Join(root, path)) + if err != nil { + t.Fatal(err) + } + var wf workflow + if err := yaml.Unmarshal(data, &wf); err != nil { + t.Fatalf("%s: %v", path, err) + } + if _, ok := wf.On["pull_request"]; !ok { + t.Errorf("%s: missing pull_request", name) + continue + } + for job, def := range wf.Jobs { + in, ok := indirectInputs[name][job] + if !ok { + t.Errorf("%s job %s: missing indirect input inventory", name, job) + continue + } + requests := map[string]map[string]bool{} + tests := map[string]map[string]bool{} + scripts := map[string]bool{} + files := map[string]bool{path: true} + for _, step := range def.Steps { + if err := commandsFromStep(root, step.Run, requests, tests, files, scripts); err != nil { + t.Errorf("%s job %s: %v", name, job, err) + } + } + addRequest(requests, "", in.packages...) + if in.fixture != "" { + imports, err := fixtureImports(root, in.fixture) + if err != nil { + t.Errorf("%s job %s: %v", name, job, err) + } else { + addRequest(requests, "installerfixture", imports...) + } + files[in.fixture+"/__ci_filter_probe__.go"] = true + } + for _, item := range in.files { + if strings.HasSuffix(item, "/**") { + files[strings.TrimSuffix(item, "**")+"__ci_filter_probe__"] = true + base := strings.TrimSuffix(item, "/**") + err := filepath.WalkDir(filepath.Join(root, base), func(path string, entry os.DirEntry, err error) error { + if err != nil { + return err + } + if entry.IsDir() && (entry.Name() == "node_modules" || entry.Name() == ".git" || entry.Name() == "dist") { + return filepath.SkipDir + } + rel, err := filepath.Rel(root, path) + if err != nil { + return err + } + rel = filepath.ToSlash(rel) + if entry.IsDir() { + files[rel+"/__ci_filter_probe__"] = true + } else { + files[rel] = true + } + return nil + }) + if err != nil { + t.Errorf("%s job %s input %s: %v", name, job, item, err) + } + } else { + files[item] = true + } + } + for script := range scripts { + covered := false + for _, source := range in.sources { + if script == source || strings.HasPrefix(script, strings.TrimSuffix(source, "/")+"/") { + covered = true + break + } + } + if !covered { + for _, event := range []string{"pull_request", "push"} { + if _, ok := wf.On[event]; ok { + t.Errorf("%s job %s event %s: script %s is missing from indirect source inventory", name, job, event, script) + } + } + } + files[script] = true + in.sources = append(in.sources, script) + } + if len(requests) > 0 { + files["go.mod"], files["go.sum"] = true, true + } + dirs := map[string]bool{} + for tags, set := range requests { + pkgs := sortedKeys(set) + if len(pkgs) == 0 { + continue + } + for _, arch := range []string{"amd64", "arm64"} { + key := arch + "\x00" + tags + "\x00" + strings.Join(pkgs, "\x00") + listed, ok := cache[key] + if !ok { + listed, err = listPackages(root, tags, arch, proxy, pkgs) + if err != nil { + t.Errorf("%s job %s: %v", name, job, err) + continue + } + cache[key] = listed + } + for dir := range listed.dirs { + dirs[dir] = true + } + for file := range listed.files { + files[file] = true + } + } + t.Logf("inventory %s/%s tags=%q packages=%s", name, job, tags, strings.Join(pkgs, ",")) + } + for dir := range dirs { + files[dir+"/__ci_filter_probe__.go"] = true + entries, err := os.ReadDir(filepath.Join(root, dir)) + if err != nil { + t.Errorf("%s job %s: %v", name, job, err) + continue + } + for _, entry := range entries { + if !entry.IsDir() { + files[dir+"/"+entry.Name()] = true + } + } + } + for tags, set := range tests { + sources, err := testSources(root, tags, proxy, sortedKeys(set)) + if err != nil { + t.Errorf("%s job %s: %v", name, job, err) + } else { + in.sources = append(in.sources, sources...) + } + } + problems, err := scanSources(root, in, dirs, files) + if err != nil { + t.Errorf("%s job %s: %v", name, job, err) + } + for _, problem := range problems { + for _, event := range []string{"pull_request", "push"} { + if _, ok := wf.On[event]; ok { + t.Errorf("%s job %s event %s: %s", name, job, event, problem) + } + } + } + t.Logf("inventory %s/%s directories=%d", name, job, len(dirs)) + if os.Getenv("CI_FILTER_INVENTORY") == "1" { + t.Logf("inventory-dirs %s/%s %s", name, job, strings.Join(sortedKeys(dirs), ",")) + } + for _, event := range []string{"pull_request", "push"} { + node, exists := wf.On[event] + if !exists { + continue + } + var filter eventFilter + if err := node.Decode(&filter); err != nil { + t.Errorf("%s event %s: %v", name, event, err) + continue + } + if len(filter.Paths) > 0 && len(filter.PathsIgnore) > 0 { + t.Errorf("%s job %s event %s: paths and paths-ignore cannot coexist", name, job, event) + continue + } + patterns := filter.Paths + if len(filter.PathsIgnore) > 0 { + patterns = filter.PathsIgnore + } + compiled, err := compilePatterns(patterns) + if err != nil { + t.Errorf("%s job %s event %s: %v", name, job, event, err) + continue + } + for _, file := range sortedKeys(files) { + included := len(patterns) == 0 || matches(compiled, file) + if len(filter.PathsIgnore) > 0 { + included = !matches(compiled, file) + } + if !included { + t.Errorf("%s job %s event %s: filter misses %s", name, job, event, file) + } + } + } + } + for job := range indirectInputs[name] { + if _, ok := wf.Jobs[job]; !ok { + t.Errorf("%s: inventoried job %s is missing", name, job) + } + } + } +} From 9569b993ea718097997fb48ed4f0b71a72c25f7a Mon Sep 17 00:00:00 2001 From: Ted H Date: Sat, 14 Nov 2026 06:43:46 -0500 Subject: [PATCH 2/4] ci: track indirect script wiring Agent: codex/gpt-6.1-terra --- tests/ci/commands_test.go | 39 +++++++++++++++ tests/ci/workflow_paths_test.go | 85 ++++++++++++++++++++++++++++++--- 2 files changed, 117 insertions(+), 7 deletions(-) diff --git a/tests/ci/commands_test.go b/tests/ci/commands_test.go index 182e707b6..3ef200c7b 100644 --- a/tests/ci/commands_test.go +++ b/tests/ci/commands_test.go @@ -1,7 +1,12 @@ package ci import ( + "crypto/sha256" + "fmt" + "os" + "path/filepath" "reflect" + "strings" "testing" ) @@ -30,3 +35,37 @@ go run honnef.co/go/tools/cmd/staticcheck@v0.8.2 -tags integration ./internal/ex t.Error("unresolved test package should fail closed") } } + +func TestIndirectWiringRequiresReview(t *testing.T) { + root := t.TempDir() + if err := os.MkdirAll(filepath.Join(root, "apps/portal"), 0o700); err != nil { + t.Fatal(err) + } + script := []byte("dynamic build helper\n") + if err := os.WriteFile(filepath.Join(root, "helper.sh"), script, 0o600); err != nil { + t.Fatal(err) + } + manifest := filepath.Join(root, "apps/portal/package.json") + if err := os.WriteFile(manifest, []byte(`{"scripts":{"build":"build-command"}}`), 0o600); err != nil { + t.Fatal(err) + } + in := indirect{pins: map[string]string{"helper.sh": fmt.Sprintf("%x", sha256.Sum256(script))}, npm: map[string]string{"build": "build-command"}} + if problems, err := checkWiring(root, in); err != nil || len(problems) != 0 { + t.Fatalf("unchanged wiring: %v, %v", problems, err) + } + if err := os.WriteFile(filepath.Join(root, "helper.sh"), []byte("changed\n"), 0o600); err != nil { + t.Fatal(err) + } + if problems, err := checkWiring(root, in); err != nil || len(problems) != 1 || !strings.Contains(problems[0], "helper.sh") { + t.Fatalf("changed helper: %v, %v", problems, err) + } + if err := os.WriteFile(filepath.Join(root, "helper.sh"), script, 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(manifest, []byte(`{"scripts":{"build":"build-command","prebuild":"new-command"}}`), 0o600); err != nil { + t.Fatal(err) + } + if problems, err := checkWiring(root, in); err != nil || len(problems) != 1 || !strings.Contains(problems[0], "package.json") { + t.Fatalf("new lifecycle script: %v, %v", problems, err) + } +} diff --git a/tests/ci/workflow_paths_test.go b/tests/ci/workflow_paths_test.go index ddf4a7620..24958d996 100644 --- a/tests/ci/workflow_paths_test.go +++ b/tests/ci/workflow_paths_test.go @@ -2,6 +2,7 @@ package ci import ( "bytes" + "crypto/sha256" "encoding/json" "fmt" "go/parser" @@ -36,9 +37,22 @@ type workflow struct { // Source roots are scanned for new literal commands and repository paths. type indirect struct { packages []string - files []string // exact files or directories ending in /** - sources []string // files or trees containing the indirect references - fixture string // source copied into a temporary module + files []string // exact files or directories ending in /** + sources []string // files or trees containing the indirect references + fixture string // source copied into a temporary module + pins map[string]string // dynamic script wiring that must be re-audited on change + npm map[string]string // invoked package.json scripts +} + +const stackDriverHash = "c5b018fd00a38aade91da66e1d9428ca5dfebff8ba139bb18bef2db5505ac239" + +// Any npm script can affect npm ci through lifecycle hooks. +var portalScripts = map[string]string{ + "dev": "vite", "dev:stack": "node e2e/dev-stack.mjs", "preview": "vite preview", + "build": "tsc --noEmit && vite build", "typecheck": "tsc --noEmit", "lint": "eslint .", + "format:check": `prettier --check "src/**/*.{ts,tsx,css}" "e2e/**/*.{ts,mjs}" index.html vite.config.ts playwright.config.ts eslint.config.js`, + "format": `prettier --write "src/**/*.{ts,tsx,css}" "e2e/**/*.{ts,mjs}" index.html vite.config.ts playwright.config.ts eslint.config.js`, + "test": "node --test e2e/*.test.mjs && vitest run", "test:coverage": "node --test e2e/*.test.mjs && vitest run --coverage", "e2e": "playwright test", } var stackPackages = []string{ @@ -66,11 +80,11 @@ func together(lists ...[]string) []string { var indirectInputs = map[string]map[string]indirect{ "at-members": { "verify": {packages: []string{"./tests/e2e/at/members/cmd/probe"}, files: []string{"tests/e2e/at/members/**", "docs/e2e/at/members/**", "deploy/devstack/probe-portal.mjs", "docs/dns/BACKEND.md", "docs/poc/G2-f802-mtu1280-2026-10-31.md", "contracts/examples/valid/ObservationReport.json", "contracts/examples/policies/fair-use.json"}, sources: []string{"tests/e2e/at/members"}}, - "assigned-stack": {packages: together(stackPackages, []string{"./tests/e2e/at/members/cmd/probe"}), files: []string{"mk/e2e.mk", "deploy/devstack/**", "deploy/backup/postgres/**", "apps/portal/**", "tests/e2e/at/members/**", "docs/e2e/at/members/**", "docs/dns/BACKEND.md", "docs/poc/G2-f802-mtu1280-2026-10-31.md", "contracts/examples/valid/ObservationReport.json", "contracts/examples/policies/fair-use.json"}, sources: []string{"deploy/devstack", "tests/e2e/at/members"}}, + "assigned-stack": {packages: together(stackPackages, []string{"./tests/e2e/at/members/cmd/probe"}), files: []string{"mk/e2e.mk", "deploy/devstack/**", "deploy/backup/postgres/**", "apps/portal/**", "tests/e2e/at/members/**", "docs/e2e/at/members/**", "docs/dns/BACKEND.md", "docs/poc/G2-f802-mtu1280-2026-10-31.md", "contracts/examples/valid/ObservationReport.json", "contracts/examples/policies/fair-use.json"}, sources: []string{"deploy/devstack", "tests/e2e/at/members"}, pins: map[string]string{"deploy/devstack/up.sh": stackDriverHash}, npm: portalScripts}, }, "at-usage": { "verify": {packages: usagePackages, files: []string{"tests/e2e/at/usage/**", "docs/e2e/at/usage/**"}, sources: []string{"tests/e2e/at/usage"}}, - "assigned-stack": {packages: together(stackPackages, usagePackages), files: []string{"mk/e2e.mk", "deploy/devstack/**", "deploy/backup/postgres/**", "apps/portal/**", "tests/e2e/at/usage/**", "docs/e2e/at/usage/**"}, sources: []string{"deploy/devstack", "tests/e2e/at/usage"}}, + "assigned-stack": {packages: together(stackPackages, usagePackages), files: []string{"mk/e2e.mk", "deploy/devstack/**", "deploy/backup/postgres/**", "apps/portal/**", "tests/e2e/at/usage/**", "docs/e2e/at/usage/**"}, sources: []string{"deploy/devstack", "tests/e2e/at/usage"}, pins: map[string]string{"deploy/devstack/up.sh": stackDriverHash, "tests/e2e/at/usage/stack.sh": "026119fe79f3af2fac9123e6001d553613b5be8ce32a770297df941778c42240"}, npm: portalScripts}, }, "at-secops": { "component-checks": {packages: []string{"./tests/e2e/at/secops/leaseprobe", "./tests/e2e/at/secops/proxyprobe", "./internal/usage/cmd/fvpn-usage-admin"}, files: []string{"tests/e2e/at/secops/**", "docs/e2e/at/secops/**", "node/agent/observe.go", "node/agent/sync.go", "node/agent/serving.go", "deploy/devstack/nginx.conf", "deploy/backup/restore-pitr.sh", "deploy/backup/post-restore-checklist.sql", "deploy/backup/backup.sh", "contracts/examples/policies/fair-use.json"}, sources: []string{"tests/e2e/at/secops"}}, @@ -90,10 +104,10 @@ var indirectInputs = map[string]map[string]indirect{ }, "fleetupdate": {"verify": {files: []string{"Makefile", "mk/**", "contracts/examples/valid/ObservationReport.json", "contracts/examples/valid/UpdateResult.installer.json", "contracts/vectors/release-manifest-signing.json"}}}, "installer": { - "verify": {files: []string{"tests/installer/**", "deploy/node/**"}, sources: []string{"tests/installer/control-build.py"}, fixture: "tests/installer/cmd/fvpn-w5-control"}, + "verify": {files: []string{"tests/installer/**", "deploy/node/**"}, sources: []string{"tests/installer/control-build.py"}, fixture: "tests/installer/cmd/fvpn-w5-control", pins: map[string]string{"tests/installer/control-build.py": "2e53816a71000b9ea41e0e02aca1e80bf634d4eec49c8da8a85f3cb484cf4933"}}, }, "portal": { - "portal": {packages: []string{"./apps/control/cmd/fvpn-control", "./apps/worker/cmd/fvpn-worker"}, files: []string{"apps/portal/**", "contracts/vectors/release-manifest-signing.json", "internal/fleetupdate/testdata/at26-direct-rollback.json", "internal/netbird/testdata/**"}, sources: []string{"apps/portal/e2e/dev-stack.mjs", "apps/portal/playwright.config.ts"}}, + "portal": {packages: []string{"./apps/control/cmd/fvpn-control", "./apps/worker/cmd/fvpn-worker"}, files: []string{"apps/portal/**", "contracts/vectors/release-manifest-signing.json", "internal/fleetupdate/testdata/at26-direct-rollback.json", "internal/netbird/testdata/**"}, sources: []string{"apps/portal/e2e/dev-stack.mjs", "apps/portal/playwright.config.ts", "apps/portal/package.json"}, pins: map[string]string{"apps/portal/playwright.config.ts": "7e3fe2a53ad5e58ce94c4ca112c8fd8ba29151b542adca7afda8ee429ee8a383"}, npm: portalScripts}, }, } @@ -460,6 +474,10 @@ func sourceFiles(root string, sources []string) ([]string, error) { if path == p || strings.HasPrefix(entry.Name(), "test_") { files[path] = true } + case ".json": + if path == p { + files[path] = true + } } return nil }) @@ -470,6 +488,42 @@ func sourceFiles(root string, sources []string) ([]string, error) { return sortedKeys(files), nil } +func checkWiring(root string, in indirect) ([]string, error) { + var problems []string + for path, expected := range in.pins { + data, err := os.ReadFile(filepath.Join(root, path)) + if err != nil { + return nil, err + } + if fmt.Sprintf("%x", sha256.Sum256(data)) != expected { + problems = append(problems, path+": dynamic script changed; review and update indirect inventory") + } + } + if in.npm != nil { + const path = "apps/portal/package.json" + data, err := os.ReadFile(filepath.Join(root, path)) + if err != nil { + return nil, err + } + var manifest struct { + Scripts map[string]string `json:"scripts"` + } + if err := json.Unmarshal(data, &manifest); err != nil { + return nil, err + } + if len(manifest.Scripts) != len(in.npm) { + problems = append(problems, path+": npm scripts changed; review and update indirect inventory") + } else { + for name, expected := range in.npm { + if actual, ok := manifest.Scripts[name]; !ok || actual != expected { + problems = append(problems, path+": npm script "+name+" changed; review and update indirect inventory") + } + } + } + } + return problems, nil +} + // Literal scanning is intentionally conservative; computed paths and shell // indirection still need the explicit inventory above and human review. func scanSources(root string, in indirect, knownDirs, knownFiles map[string]bool) ([]string, error) { @@ -601,6 +655,23 @@ func TestWorkflowPaths(t *testing.T) { tests := map[string]map[string]bool{} scripts := map[string]bool{} files := map[string]bool{path: true} + for pinned := range in.pins { + files[pinned] = true + } + if in.npm != nil { + files["apps/portal/package.json"] = true + } + wiringProblems, err := checkWiring(root, in) + if err != nil { + t.Errorf("%s job %s: %v", name, job, err) + } + for _, problem := range wiringProblems { + for _, event := range []string{"pull_request", "push"} { + if _, ok := wf.On[event]; ok { + t.Errorf("%s job %s event %s: %s", name, job, event, problem) + } + } + } for _, step := range def.Steps { if err := commandsFromStep(root, step.Run, requests, tests, files, scripts); err != nil { t.Errorf("%s job %s: %v", name, job, err) From 8bc95cfda6a31692f1819d3dee213905e3ac2e39 Mon Sep 17 00:00:00 2001 From: Ted H Date: Sat, 14 Nov 2026 07:50:33 -0500 Subject: [PATCH 3/4] ci: track gofmt inputs in workflow filters Agent: codex/gpt-6.1-terra --- .github/workflows/at-secops.yml | 3 +- .github/workflows/fleetupdate.yml | 4 +- tests/ci/commands_test.go | 60 ++++++ tests/ci/gofmt_test.go | 318 ++++++++++++++++++++++++++++++ tests/ci/matcher_test.go | 15 ++ tests/ci/workflow_paths_test.go | 35 +++- 6 files changed, 430 insertions(+), 5 deletions(-) create mode 100644 tests/ci/gofmt_test.go diff --git a/.github/workflows/at-secops.yml b/.github/workflows/at-secops.yml index f2b354968..9b11da084 100644 --- a/.github/workflows/at-secops.yml +++ b/.github/workflows/at-secops.yml @@ -10,7 +10,8 @@ on: - 'contracts/examples/policies/fair-use.json' - 'contracts/schemas/**' - 'db/**' - - 'deploy/**' + - 'deploy/backup/**' + - 'deploy/devstack/**' - 'go.mod' - 'go.sum' - 'internal/audit/**' diff --git a/.github/workflows/fleetupdate.yml b/.github/workflows/fleetupdate.yml index 28abede32..3b3bc9d5a 100644 --- a/.github/workflows/fleetupdate.yml +++ b/.github/workflows/fleetupdate.yml @@ -1,9 +1,9 @@ name: Central fleet updates on: push: - paths: ['internal/releases/**', 'internal/fleetupdate/**', 'internal/installerjob/**', 'internal/nodes/update_view.go', 'node/updater/**', 'db/migrations/**', 'contracts/**', 'pkg/**', 'go.*', 'mk/fleetupdate.mk', '.github/workflows/fleetupdate.yml', 'Makefile', 'apps/**', 'internal/**', 'mk/**', 'node/**', 'packaging/**', 'tests/backup/**', 'tests/ci/**', 'tests/e2e/*', 'tests/e2e/at/**', 'tests/e2e/cmd/**', 'tests/e2e/internal/agentwait/**', 'tests/e2e/internal/counterread/**', 'tests/e2e/internal/dnsrelay/**', 'tests/e2e/internal/granttrace/**', 'tests/e2e/internal/idplogin/**', 'tests/e2e/internal/labtls/**', 'tests/e2e/internal/leasehold/**', 'tests/e2e/internal/nativecapture/**', 'tests/e2e/internal/offertrace/**', 'tests/e2e/internal/probeauth/**', 'tests/e2e/internal/streamstats/**', 'tests/handover/**', 'tests/netlab/*', 'tests/netlab/at/**', 'tests/netlab/cmd/**', 'tests/netlab/dns/cmd/**', 'tests/netlab/dns/internal/**'] + paths: ['internal/releases/**', 'internal/fleetupdate/**', 'internal/installerjob/**', 'internal/nodes/update_view.go', 'node/updater/**', 'db/migrations/**', 'contracts/**', 'pkg/**', 'go.*', 'mk/fleetupdate.mk', '.github/workflows/fleetupdate.yml', 'Makefile', 'apps/**', 'internal/**', 'mk/**', 'node/**', 'packaging/**', 'tests/backup/**', 'tests/ci/**', 'tests/e2e/*', 'tests/e2e/at/**', 'tests/e2e/cmd/**', 'tests/e2e/internal/agentwait/**', 'tests/e2e/internal/counterread/**', 'tests/e2e/internal/dnsrelay/**', 'tests/e2e/internal/granttrace/**', 'tests/e2e/internal/idplogin/**', 'tests/e2e/internal/labtls/**', 'tests/e2e/internal/leasehold/**', 'tests/e2e/internal/nativecapture/**', 'tests/e2e/internal/offertrace/**', 'tests/e2e/internal/probeauth/**', 'tests/e2e/internal/streamstats/**', 'tests/handover/**', 'tests/netlab/*', 'tests/netlab/at/**', 'tests/netlab/cmd/**', 'tests/netlab/dns/cmd/**', 'tests/netlab/dns/internal/**', '**/*.go'] pull_request: - paths: ['internal/releases/**', 'internal/fleetupdate/**', 'internal/installerjob/**', 'internal/nodes/update_view.go', 'node/updater/**', 'db/migrations/**', 'contracts/**', 'pkg/**', 'go.*', 'mk/fleetupdate.mk', '.github/workflows/fleetupdate.yml', 'Makefile', 'apps/**', 'internal/**', 'mk/**', 'node/**', 'packaging/**', 'tests/backup/**', 'tests/ci/**', 'tests/e2e/*', 'tests/e2e/at/**', 'tests/e2e/cmd/**', 'tests/e2e/internal/agentwait/**', 'tests/e2e/internal/counterread/**', 'tests/e2e/internal/dnsrelay/**', 'tests/e2e/internal/granttrace/**', 'tests/e2e/internal/idplogin/**', 'tests/e2e/internal/labtls/**', 'tests/e2e/internal/leasehold/**', 'tests/e2e/internal/nativecapture/**', 'tests/e2e/internal/offertrace/**', 'tests/e2e/internal/probeauth/**', 'tests/e2e/internal/streamstats/**', 'tests/handover/**', 'tests/netlab/*', 'tests/netlab/at/**', 'tests/netlab/cmd/**', 'tests/netlab/dns/cmd/**', 'tests/netlab/dns/internal/**'] + paths: ['internal/releases/**', 'internal/fleetupdate/**', 'internal/installerjob/**', 'internal/nodes/update_view.go', 'node/updater/**', 'db/migrations/**', 'contracts/**', 'pkg/**', 'go.*', 'mk/fleetupdate.mk', '.github/workflows/fleetupdate.yml', 'Makefile', 'apps/**', 'internal/**', 'mk/**', 'node/**', 'packaging/**', 'tests/backup/**', 'tests/ci/**', 'tests/e2e/*', 'tests/e2e/at/**', 'tests/e2e/cmd/**', 'tests/e2e/internal/agentwait/**', 'tests/e2e/internal/counterread/**', 'tests/e2e/internal/dnsrelay/**', 'tests/e2e/internal/granttrace/**', 'tests/e2e/internal/idplogin/**', 'tests/e2e/internal/labtls/**', 'tests/e2e/internal/leasehold/**', 'tests/e2e/internal/nativecapture/**', 'tests/e2e/internal/offertrace/**', 'tests/e2e/internal/probeauth/**', 'tests/e2e/internal/streamstats/**', 'tests/handover/**', 'tests/netlab/*', 'tests/netlab/at/**', 'tests/netlab/cmd/**', 'tests/netlab/dns/cmd/**', 'tests/netlab/dns/internal/**', '**/*.go'] permissions: contents: read jobs: diff --git a/tests/ci/commands_test.go b/tests/ci/commands_test.go index 3ef200c7b..f640ca676 100644 --- a/tests/ci/commands_test.go +++ b/tests/ci/commands_test.go @@ -36,6 +36,66 @@ go run honnef.co/go/tools/cmd/staticcheck@v0.8.2 -tags integration ./internal/ex } } +func TestGofmtInputExtraction(t *testing.T) { + root, err := filepath.Abs("../..") + if err != nil { + t.Fatal(err) + } + tracked, err := trackedFiles(root) + if err != nil { + t.Fatal(err) + } + tests := []struct { + name, command, form string + want []string + }{ + {"git pathspec", `test -z "$(gofmt -l $(git ls-files --cached --others --exclude-standard 'pkg/decstr/*.go'))"`, "git ls-files", []string{"pkg/decstr/decstr.go", "pkg/decstr/decstr_test.go"}}, + {"rg directories", `gofmt -l $(rg --files pkg/decstr pkg/canonjson -g '*.go')`, "rg --files", []string{"pkg/canonjson/canonjson.go", "pkg/canonjson/canonjson_test.go", "pkg/canonjson/review_test.go", "pkg/decstr/decstr.go", "pkg/decstr/decstr_test.go"}}, + {"literal paths and shell glob", `gofmt -l pkg/decstr pkg/canonjson/*test.go pkg/envelope/envelope.go`, "paths", []string{"pkg/canonjson/canonjson_test.go", "pkg/canonjson/review_test.go", "pkg/decstr/decstr.go", "pkg/decstr/decstr_test.go", "pkg/envelope/envelope.go"}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + sets, err := gofmtInputs(root, tt.command, tracked) + if err != nil || len(sets) != 1 { + t.Fatalf("sets = %v, error = %v", sets, err) + } + if sets[0].form != tt.form || !reflect.DeepEqual(sets[0].files, tt.want) { + t.Errorf("got %s %v; want %s %v", sets[0].form, sets[0].files, tt.form, tt.want) + } + }) + } + sets, err := gofmtInputs(root, `gofmt -l $(git ls-files --cached --others --exclude-standard 'pkg/*.go')`, tracked) + if err != nil || len(sets) != 1 || !contains(sets[0].files, "pkg/decstr/decstr.go") { + t.Errorf("git pathspec star must cross directories: %v, %v", sets, err) + } + withNested := append(append([]string(nil), tracked...), "pkg/decstr/nested/extra.go") + sets, err = gofmtInputs(root, `gofmt -l pkg/decstr/*.go`, withNested) + if err != nil || len(sets) != 1 || contains(sets[0].files, "pkg/decstr/nested/extra.go") { + t.Errorf("shell glob star must stop at a slash: %v, %v", sets, err) + } + for _, command := range []string{`gofmt -l $(find pkg -name '*.go')`, `gofmt -l $files`, `gofmt -w pkg/decstr`} { + if _, err := gofmtInputs(root, command, tracked); err == nil || !strings.Contains(err.Error(), "gofmt") { + t.Errorf("unsupported command %q: %v", command, err) + } + } + sets, err = gofmtInputs(root, `echo 'gofmt required'; echo "gofmt needed: $(gofmt -l pkg/decstr)"; gofmt -l pkg/decstr`, tracked) + if err != nil || len(sets) != 2 { + t.Errorf("commands in shell and quoted substitutions: %v, %v", sets, err) + } + if _, err := trackedFiles(t.TempDir()); err == nil || !strings.Contains(err.Error(), "needs a git checkout") { + t.Errorf("missing checkout error = %v", err) + } +} + +func contains(values []string, want string) bool { + for _, value := range values { + if value == want { + return true + } + } + return false +} + func TestIndirectWiringRequiresReview(t *testing.T) { root := t.TempDir() if err := os.MkdirAll(filepath.Join(root, "apps/portal"), 0o700); err != nil { diff --git a/tests/ci/gofmt_test.go b/tests/ci/gofmt_test.go new file mode 100644 index 000000000..9186a6066 --- /dev/null +++ b/tests/ci/gofmt_test.go @@ -0,0 +1,318 @@ +package ci + +import ( + "fmt" + "os" + "os/exec" + "path" + "path/filepath" + "strings" +) + +type gofmtSet struct { + command string + form string + files []string +} + +// Git's pathspec rules differ from shell globs, so let Git resolve them. +func trackedFiles(root string, pathspecs ...string) ([]string, error) { + args := append([]string{"ls-files", "--cached", "-z", "--"}, pathspecs...) + cmd := exec.Command("git", args...) + cmd.Dir = root + out, err := cmd.Output() + if err != nil { + return nil, fmt.Errorf("gofmt inventory needs a git checkout: git ls-files: %w", err) + } + var files []string + for _, file := range strings.Split(string(out), "\x00") { + if file != "" { + files = append(files, file) + } + } + return files, nil +} + +// substitutionEnd finds the end of a shell $(...) without evaluating it. +func substitutionEnd(text string, start int) (int, error) { + var quote byte + for i := start + 2; i < len(text); i++ { + c := text[i] + if quote == '\'' { + if c == quote { + quote = 0 + } + continue + } + if c == '\\' { + i++ + continue + } + if c == '$' && i+1 < len(text) && text[i+1] == '(' { + end, err := substitutionEnd(text, i) + if err != nil { + return 0, err + } + i = end + continue + } + if quote == '"' { + if c == quote { + quote = 0 + } + continue + } + switch c { + case '\'', '"': + quote = c + case ')': + return i, nil + } + } + return 0, fmt.Errorf("unclosed shell command substitution") +} + +type shellWord struct { + value string + quoted bool +} + +// shellWords accepts literal words and whole command substitutions only. It +// stops at shell operators; unsupported expansions are errors, not guesses. +func shellWords(text string) ([]shellWord, int, error) { + var words []shellWord + for i := 0; i < len(text); { + if text[i] == ' ' || text[i] == '\t' || text[i] == '\r' { + i++ + continue + } + if strings.ContainsRune("\n;|&<>(){}", rune(text[i])) { + return words, i, nil + } + var word strings.Builder + quoted := false + for i < len(text) && !strings.ContainsRune(" \t\r\n;|&<>(){}", rune(text[i])) { + c := text[i] + switch { + case c == '\'' || c == '"': + quote := c + quoted = true + i++ + for i < len(text) && text[i] != quote { + if quote == '"' && strings.ContainsRune("$`\\", rune(text[i])) { + return nil, i, fmt.Errorf("unsupported quoted expansion") + } + word.WriteByte(text[i]) + i++ + } + if i == len(text) { + return nil, i, fmt.Errorf("unclosed quote") + } + i++ + case c == '$' && i+1 < len(text) && text[i+1] == '(': + if word.Len() != 0 { + return nil, i, fmt.Errorf("mixed command substitution") + } + end, err := substitutionEnd(text, i) + if err != nil { + return nil, i, err + } + word.WriteString(text[i : end+1]) + i = end + 1 + if i < len(text) && !strings.ContainsRune(" \t\r\n;|&<>(){}", rune(text[i])) { + return nil, i, fmt.Errorf("mixed command substitution") + } + case strings.ContainsRune("$`\\", rune(c)): + return nil, i, fmt.Errorf("unsupported shell expansion") + default: + word.WriteByte(c) + i++ + } + } + words = append(words, shellWord{word.String(), quoted}) + } + return words, len(text), nil +} + +// Search the shell text and its command substitutions, but not literal quoted +// messages such as echo 'gofmt required'. No workflow command is executed. +func gofmtCommands(text string) ([]string, error) { + text = strings.ReplaceAll(text, "\\\n", " ") + var commands []string + var scan func(string) error + scan = func(text string) error { + var quote byte + for i := 0; i < len(text); i++ { + c := text[i] + if quote == '\'' { + if c == quote { + quote = 0 + } + continue + } + if c == '\\' { + i++ + continue + } + if c == '$' && i+1 < len(text) && text[i+1] == '(' { + end, err := substitutionEnd(text, i) + if err != nil { + return err + } + if err := scan(text[i+2 : end]); err != nil { + return err + } + i = end + continue + } + if quote == '"' { + if c == quote { + quote = 0 + } + continue + } + if c == '\'' || c == '"' { + quote = c + continue + } + if !strings.HasPrefix(text[i:], "gofmt") || (i > 0 && !strings.ContainsRune(" \t\r\n;|&({", rune(text[i-1]))) || (i+5 < len(text) && !strings.ContainsRune(" \t\r\n;|&)>", rune(text[i+5]))) { + continue + } + _, end, err := shellWords(text[i:]) + if err != nil { + return fmt.Errorf("gofmt command %q: %w", text[i:], err) + } + commands = append(commands, strings.TrimSpace(text[i:i+end])) + i += end - 1 + } + return nil + } + err := scan(text) + return commands, err +} + +func repoPath(value string) (string, error) { + clean := path.Clean(value) + if path.IsAbs(value) || clean == ".." || strings.HasPrefix(clean, "../") || strings.ContainsAny(value, "?[]{}") { + return "", fmt.Errorf("unsupported path %q", value) + } + return clean, nil +} + +func gofmtInputs(root, text string, tracked []string) ([]gofmtSet, error) { + commands, err := gofmtCommands(text) + if err != nil { + return nil, err + } + var sets []gofmtSet + for _, command := range commands { + set, err := resolveGofmt(root, command, tracked) + if err != nil { + return nil, fmt.Errorf("gofmt command %q: %w", command, err) + } + sets = append(sets, set) + } + return sets, nil +} + +func resolveGofmt(root, command string, tracked []string) (gofmtSet, error) { + result := gofmtSet{command: command} + words, _, err := shellWords(command) + if err != nil { + return result, err + } + if len(words) < 3 || words[0].value != "gofmt" || words[1].value != "-l" { + return result, fmt.Errorf("expected gofmt -l with file arguments") + } + files := map[string]bool{} + if strings.HasPrefix(words[2].value, "$(") { + if len(words) != 3 || words[2].quoted { + return result, fmt.Errorf("unsupported command substitution arguments") + } + inner := strings.TrimSuffix(strings.TrimPrefix(words[2].value, "$("), ")") + args, end, err := shellWords(inner) + if err != nil || end != len(inner) || len(args) < 2 { + return result, fmt.Errorf("unsupported file-list command %q", inner) + } + switch { + case len(args) >= 6 && args[0].value == "git" && args[1].value == "ls-files" && args[2].value == "--cached" && args[3].value == "--others" && args[4].value == "--exclude-standard": + result.form = "git ls-files" + var specs []string + for _, arg := range args[5:] { + if strings.HasPrefix(arg.value, "-") || (!arg.quoted && strings.ContainsAny(arg.value, "*?[")) { + return result, fmt.Errorf("unsupported git pathspec %q", arg.value) + } + specs = append(specs, arg.value) + } + listed, err := trackedFiles(root, specs...) + if err != nil { + return result, err + } + for _, file := range listed { + files[file] = true + } + case len(args) >= 5 && args[0].value == "rg" && args[1].value == "--files" && args[len(args)-2].value == "-g" && args[len(args)-1].value == "*.go" && args[len(args)-1].quoted: + result.form = "rg --files" + for _, arg := range args[2 : len(args)-2] { + dir, err := repoPath(arg.value) + if err != nil || strings.Contains(dir, "*") || strings.HasPrefix(dir, "-") { + return result, fmt.Errorf("unsupported rg directory %q", arg.value) + } + info, err := os.Stat(filepath.Join(root, filepath.FromSlash(dir))) + if err != nil || !info.IsDir() { + return result, fmt.Errorf("rg directory %q does not exist", dir) + } + for _, file := range tracked { + if (dir == "." || strings.HasPrefix(file, dir+"/")) && strings.HasSuffix(file, ".go") { + files[file] = true + } + } + } + default: + return result, fmt.Errorf("unsupported file-list command %q", inner) + } + } else { + result.form = "paths" + for _, arg := range words[2:] { + name, err := repoPath(arg.value) + if err != nil || strings.HasPrefix(name, "-") { + return result, fmt.Errorf("unsupported file argument %q", arg.value) + } + if strings.Contains(name, "*") && arg.quoted { + return result, fmt.Errorf("quoted glob %q is not a shell expansion", name) + } + if !strings.Contains(name, "*") { + info, err := os.Stat(filepath.Join(root, filepath.FromSlash(name))) + if err != nil { + return result, fmt.Errorf("file argument %q: %w", name, err) + } + for _, file := range tracked { + if file == name || (info.IsDir() && (name == "." || strings.HasPrefix(file, name+"/")) && strings.HasSuffix(file, ".go")) { + files[file] = true + } + } + continue + } + matched := false + for _, file := range tracked { + for candidate := file; candidate != "."; candidate = path.Dir(candidate) { + ok, err := path.Match(name, candidate) + if err != nil { + return result, err + } + if ok { + matched = true + if candidate == file || strings.HasSuffix(file, ".go") { + files[file] = true + } + } + } + } + if !matched { + return result, fmt.Errorf("shell glob %q matches no tracked path", name) + } + } + } + result.files = sortedKeys(files) + return result, nil +} diff --git a/tests/ci/matcher_test.go b/tests/ci/matcher_test.go index 97da57d40..5878071c2 100644 --- a/tests/ci/matcher_test.go +++ b/tests/ci/matcher_test.go @@ -3,6 +3,7 @@ package ci import ( "fmt" "regexp" + "strconv" "strings" "testing" "unicode/utf8" @@ -20,6 +21,9 @@ type compiledPattern struct { func compilePatterns(patterns []string) ([]compiledPattern, error) { var compiled []compiledPattern for _, pattern := range patterns { + if strings.ContainsAny(pattern, `[]+\`) { + return nil, fmt.Errorf("unsupported syntax in pattern %q", pattern) + } negative := strings.HasPrefix(pattern, "!") if negative { pattern = pattern[1:] @@ -104,6 +108,12 @@ func TestWorkflowMatcher(t *testing.T) { {"globstar nested", eventFilter{Paths: []string{"a/**"}}, "a/sub/file.go", true}, {"globstar zero directories", eventFilter{Paths: []string{"a/**/file.go"}}, "a/file.go", true}, {"globstar more directories", eventFilter{Paths: []string{"a/**/file.go"}}, "a/b/c/file.go", true}, + {"leading globstar root", eventFilter{Paths: []string{"**/file.go"}}, "file.go", true}, + {"leading globstar nested", eventFilter{Paths: []string{"**/file.go"}}, "a/b/file.go", true}, + {"leading globstar suffix", eventFilter{Paths: []string{"**/file.go"}}, "file.go.txt", false}, + {"go module", eventFilter{Paths: []string{"go.*"}}, "go.mod", true}, + {"go checksum", eventFilter{Paths: []string{"go.*"}}, "go.sum", true}, + {"go module nested", eventFilter{Paths: []string{"go.*"}}, "vendor/go.mod", false}, {"question mark", eventFilter{Paths: []string{"a/?.go"}}, "a/x.go", true}, {"unicode literal and wildcard", eventFilter{Paths: []string{"文件/?.go"}}, "文件/測.go", true}, {"question mark stops at slash", eventFilter{Paths: []string{"a?b"}}, "a/b", false}, @@ -125,6 +135,11 @@ func TestWorkflowMatcher(t *testing.T) { if _, err := (eventFilter{Paths: []string{"**"}, PathsIgnore: []string{"x"}}).includes("x"); err == nil { t.Fatal("paths and paths-ignore together must be rejected") } + for _, pattern := range []string{"a/[b", "a/]b", "a/+b", `a/\b`} { + if _, err := compilePatterns([]string{pattern}); err == nil || !strings.Contains(err.Error(), strconv.Quote(pattern)) { + t.Errorf("unsupported pattern %q: got error %v", pattern, err) + } + } } func TestYAMLOnIsString(t *testing.T) { diff --git a/tests/ci/workflow_paths_test.go b/tests/ci/workflow_paths_test.go index 24958d996..419786ddd 100644 --- a/tests/ci/workflow_paths_test.go +++ b/tests/ci/workflow_paths_test.go @@ -293,11 +293,27 @@ func recordScripts(text string, scripts map[string]bool) { } } -func commandsFromStep(root, run string, requests, tests map[string]map[string]bool, files, scripts map[string]bool) error { +func commandsFromStep(root, run string, requests, tests map[string]map[string]bool, files, scripts map[string]bool, tracked []string, formats *[]gofmtSet) error { + addFormats := func(text string) error { + sets, err := gofmtInputs(root, text, tracked) + if err != nil { + return err + } + for _, set := range sets { + for _, file := range set.files { + files[file] = true + } + *formats = append(*formats, set) + } + return nil + } recordScripts(run, scripts) if err := parseGoCommands(run, requests, tests); err != nil { return err } + if err := addFormats(run); err != nil { + return err + } for _, match := range makeLine.FindAllStringSubmatch(run, -1) { fields := strings.Fields(match[1]) makefile := "Makefile" @@ -322,6 +338,9 @@ func commandsFromStep(root, run string, requests, tests map[string]map[string]bo if err := parseGoCommands(string(out), requests, tests); err != nil { return fmt.Errorf("%s: %w", match[0], err) } + if err := addFormats(string(out)); err != nil { + return fmt.Errorf("%s: %w", match[0], err) + } } return nil } @@ -616,6 +635,10 @@ func TestWorkflowPaths(t *testing.T) { if err != nil { t.Fatal(err) } + tracked, err := trackedFiles(root) + if err != nil { + t.Fatal(err) + } // A file-only module proxy lets go list use the local download cache while // guaranteeing that this test never contacts a proxy or checksum server. cacheCmd := exec.Command("go", "env", "GOMODCACHE") @@ -655,6 +678,7 @@ func TestWorkflowPaths(t *testing.T) { tests := map[string]map[string]bool{} scripts := map[string]bool{} files := map[string]bool{path: true} + var formats []gofmtSet for pinned := range in.pins { files[pinned] = true } @@ -673,10 +697,17 @@ func TestWorkflowPaths(t *testing.T) { } } for _, step := range def.Steps { - if err := commandsFromStep(root, step.Run, requests, tests, files, scripts); err != nil { + if err := commandsFromStep(root, step.Run, requests, tests, files, scripts, tracked, &formats); err != nil { t.Errorf("%s job %s: %v", name, job, err) } } + seenFormats := map[string]bool{} + for _, format := range formats { + if !seenFormats[format.command] { + t.Logf("gofmt %s/%s form=%s files=%d command=%q", name, job, format.form, len(format.files), format.command) + seenFormats[format.command] = true + } + } addRequest(requests, "", in.packages...) if in.fixture != "" { imports, err := fixtureImports(root, in.fixture) From 344deb5f73abe7fc90506663729f445850a37df1 Mon Sep 17 00:00:00 2001 From: Ted H Date: Sat, 14 Nov 2026 14:13:43 -0500 Subject: [PATCH 4/4] ci: require checkout roots for gofmt inventory Agent: codex/gpt-6.1-terra --- tests/ci/commands_test.go | 4 ++++ tests/ci/gofmt_test.go | 25 +++++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/tests/ci/commands_test.go b/tests/ci/commands_test.go index f640ca676..6ea6c8a29 100644 --- a/tests/ci/commands_test.go +++ b/tests/ci/commands_test.go @@ -82,6 +82,10 @@ func TestGofmtInputExtraction(t *testing.T) { if err != nil || len(sets) != 2 { t.Errorf("commands in shell and quoted substitutions: %v, %v", sets, err) } + subdir := filepath.Join(root, "tests", "ci") + if _, err := trackedFiles(subdir); err == nil || !strings.Contains(err.Error(), "needs a git checkout") || !strings.Contains(err.Error(), subdir) || !strings.Contains(err.Error(), root) { + t.Errorf("subdirectory checkout error = %v", err) + } if _, err := trackedFiles(t.TempDir()); err == nil || !strings.Contains(err.Error(), "needs a git checkout") { t.Errorf("missing checkout error = %v", err) } diff --git a/tests/ci/gofmt_test.go b/tests/ci/gofmt_test.go index 9186a6066..ff5f6f83f 100644 --- a/tests/ci/gofmt_test.go +++ b/tests/ci/gofmt_test.go @@ -17,6 +17,31 @@ type gofmtSet struct { // Git's pathspec rules differ from shell globs, so let Git resolve them. func trackedFiles(root string, pathspecs ...string) ([]string, error) { + topCmd := exec.Command("git", "rev-parse", "--show-toplevel") + topCmd.Dir = root + topOutput, err := topCmd.Output() + if err != nil { + return nil, fmt.Errorf("gofmt inventory needs a git checkout at %q: git rev-parse: %w", root, err) + } + top := strings.TrimSpace(string(topOutput)) + canonical := func(name string) (string, error) { + absolute, err := filepath.Abs(name) + if err != nil { + return "", err + } + return filepath.EvalSymlinks(absolute) + } + actualRoot, err := canonical(root) + if err != nil { + return nil, fmt.Errorf("gofmt inventory needs a git checkout at %q (git top level %q): %w", root, top, err) + } + actualTop, err := canonical(top) + if err != nil { + return nil, fmt.Errorf("gofmt inventory needs a git checkout at %q (git top level %q): %w", root, top, err) + } + if actualRoot != actualTop { + return nil, fmt.Errorf("gofmt inventory needs a git checkout at %q (git top level %q)", root, top) + } args := append([]string{"ls-files", "--cached", "-z", "--"}, pathspecs...) cmd := exec.Command("git", args...) cmd.Dir = root