diff --git a/.golangci.yml b/.golangci.yml index 4425faefb..773235ee9 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -42,6 +42,7 @@ linters: - errorlint - fatcontext - forcetypeassert + - gosec - makezero - nilerr - nilnesserr @@ -128,6 +129,12 @@ linters: - HACK - BUG + gosec: + excludes: + - G104 # errcheck covers unchecked errors + - G115 # integer conversions are bounded where they occur + - G204 # running commands is what the tools and workflow steps do + - G304 # file paths come from configuration and confined worktrees interfacebloat: max: 8 diff --git a/internal/agentexec/modelloop/transcript_test.go b/internal/agentexec/modelloop/transcript_test.go index 05950d65e..9f18b2426 100644 --- a/internal/agentexec/modelloop/transcript_test.go +++ b/internal/agentexec/modelloop/transcript_test.go @@ -11,7 +11,7 @@ import ( func TestTranscriptToolEntryRedactsAndClips(t *testing.T) { const jwt = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhcmNoaWUifQ.c2lnbmF0dXJlc2lnbmF0dXJl" - const pem = "-----BEGIN RSA PRIVATE KEY-----\nMIIEow\n-----END RSA PRIVATE KEY-----" + const pem = "-----BEGIN RSA PRIVATE KEY-----\nMIIEow\n-----END RSA PRIVATE KEY-----" //nolint:gosec // G101: a fake key the redaction must catch. long := strings.Repeat("x", transcriptFieldLimit+10) tests := []struct { name string diff --git a/internal/app/agentworker/task_execution.go b/internal/app/agentworker/task_execution.go index 51405f9e4..6c928d55e 100644 --- a/internal/app/agentworker/task_execution.go +++ b/internal/app/agentworker/task_execution.go @@ -111,13 +111,19 @@ func (h *hybridTrees) HasUncommittedChanges(ctx context.Context, dir string) (bo var _ workflow.Trees = (*hybridTrees)(nil) -// chownTree recursively lchowns dir to uid:gid. +// chownTree recursively lchowns dir to uid:gid, through a root so a symlink +// swapped in mid-walk cannot point it outside dir. func chownTree(dir string, uid, gid int) error { - return filepath.WalkDir(dir, func(path string, _ fs.DirEntry, err error) error { + root, err := os.OpenRoot(dir) + if err != nil { + return err + } + defer func() { _ = root.Close() }() + return fs.WalkDir(root.FS(), ".", func(path string, _ fs.DirEntry, err error) error { if err != nil { return err } - return os.Lchown(path, uid, gid) + return root.Lchown(path, uid, gid) }) } diff --git a/internal/app/archied/model_egress_test.go b/internal/app/archied/model_egress_test.go index 9e64d5e7e..56e90e567 100644 --- a/internal/app/archied/model_egress_test.go +++ b/internal/app/archied/model_egress_test.go @@ -43,13 +43,13 @@ func TestModelEgressResolvesProviderSecretRefs(t *testing.T) { }, { name: "an env-only provider keeps its binding", - provider: config.Provider{Class: "openai", APIKeyEnv: "PROVIDER_ENV_KEY"}, + provider: config.Provider{Class: "openai", APIKeyEnv: "PROVIDER_ENV_KEY"}, //nolint:gosec // G101: env var and secret names, not values. bindings: []config.CredentialBinding{{Service: "used", Org: "org-test", Secret: config.SecretRef{Engine: "env", Key: "PROVIDER_KEY"}}}, wantEnv: "PROVIDER_ENV_KEY", }, { name: "an env-only provider without a binding is refused", - provider: config.Provider{Class: "openai", APIKeyEnv: "PROVIDER_ENV_KEY"}, + provider: config.Provider{Class: "openai", APIKeyEnv: "PROVIDER_ENV_KEY"}, //nolint:gosec // G101: env var and secret names, not values. wantErr: "no credential binding", }, } diff --git a/internal/app/archied/repository_access_test.go b/internal/app/archied/repository_access_test.go index 107223e11..63c82fe30 100644 --- a/internal/app/archied/repository_access_test.go +++ b/internal/app/archied/repository_access_test.go @@ -6,7 +6,7 @@ import ( "errors" "log/slog" "net/http" - "net/http/cgi" + "net/http/cgi" //nolint:gosec // G504: serves git http-backend; the Httpoxy CVE predates Go 1.6.3. "net/http/httptest" "os" "os/exec" diff --git a/internal/app/archied/update_test.go b/internal/app/archied/update_test.go index e86a92520..9797b65b4 100644 --- a/internal/app/archied/update_test.go +++ b/internal/app/archied/update_test.go @@ -16,8 +16,10 @@ func TestUpdateTopologyRefusal(t *testing.T) { root := t.TempDir() config := filepath.Join(root, "config.toml") required := releaseupdate.Topology{Units: []string{"archie-state-store", "archie-gateway", "archied"}, ConfigSections: []string{"services.state", "services.gateway"}} - writeUpdateFixture(t, config, "[services.state]\ntarget='localhost:9090'\n") - writeUpdateFixture(t, filepath.Join(root, "systemctl"), "#!/bin/sh\nprintf 'archied.service enabled enabled\\n'\n") + if err := os.WriteFile(config, []byte("[services.state]\ntarget='localhost:9090'\n"), 0o600); err != nil { + t.Fatal(err) + } + writeScript(t, filepath.Join(root, "systemctl"), "#!/bin/sh\nprintf 'archied.service enabled enabled\\n'\n") t.Setenv("PATH", root+":"+os.Getenv("PATH")) var output bytes.Buffer if err := checkUpdateTopology(t.Context(), config, required, true, &output); err == nil { @@ -39,8 +41,8 @@ func TestResumeUpdate(t *testing.T) { t.Fatal(err) } called := filepath.Join(root, "called") - writeUpdateFixture(t, filepath.Join(root, "systemd-run"), "#!/bin/sh\nprintf '%s\\n' \"$@\" > '"+called+"'\n") - writeUpdateFixture(t, filepath.Join(root, "systemctl"), "#!/bin/sh\n") + writeScript(t, filepath.Join(root, "systemd-run"), "#!/bin/sh\nprintf '%s\\n' \"$@\" > '"+called+"'\n") + writeScript(t, filepath.Join(root, "systemctl"), "#!/bin/sh\n") t.Setenv("PATH", root+":"+os.Getenv("PATH")) lock, err := os.OpenFile(filepath.Join(root, "lock"), os.O_CREATE|os.O_RDWR, 0o600) if err != nil { @@ -69,9 +71,10 @@ func TestResumeUpdate(t *testing.T) { } } -func writeUpdateFixture(t *testing.T, path, data string) { +// writeScript writes a stand-in for a host command the update runs. +func writeScript(t *testing.T, path, data string) { t.Helper() - if err := os.WriteFile(path, []byte(data), 0o700); err != nil { + if err := os.WriteFile(path, []byte(data), 0o700); err != nil { //nolint:gosec // G306: a script needs the execute bit. t.Fatal(err) } } diff --git a/internal/app/archiemessaging/org_channels.go b/internal/app/archiemessaging/org_channels.go index fe56fcb64..35e5b8d5d 100644 --- a/internal/app/archiemessaging/org_channels.go +++ b/internal/app/archiemessaging/org_channels.go @@ -26,7 +26,7 @@ import ( const telegramCredential = "telegram" // credentialBindingsKind is the control-plane resource holding the bindings. -const credentialBindingsKind = "credential-bindings" +const credentialBindingsKind = "credential-bindings" //nolint:gosec // G101: a credential service name, not a credential. // orgChannelSource is where the Messaging Service learns which orgs run a // channel and how they are bound. *controlplanerpc.Client satisfies the first diff --git a/internal/app/prbench/prbench.go b/internal/app/prbench/prbench.go index 330db68c4..7dc42dd7c 100644 --- a/internal/app/prbench/prbench.go +++ b/internal/app/prbench/prbench.go @@ -193,5 +193,5 @@ func writeReport(dir, report string) (string, error) { return "", err } path := filepath.Join(dir, "pr-review-"+time.Now().UTC().Format("20060102-150405")+".md") - return path, os.WriteFile(path, []byte(report), 0o644) + return path, os.WriteFile(path, []byte(report), 0o644) //nolint:gosec // G306: a report for the operator to read. } diff --git a/internal/container/pool.go b/internal/container/pool.go index 72b7845f4..c2d1903ac 100644 --- a/internal/container/pool.go +++ b/internal/container/pool.go @@ -93,7 +93,7 @@ func WriteTaskJSON(workspace string, payload TaskPayload) error { if err := os.MkdirAll(gitDir, 0o700); err != nil { return fmt.Errorf("task.json: %w", err) } - return os.WriteFile(filepath.Join(gitDir, "task.json"), data, 0o644) + return os.WriteFile(filepath.Join(gitDir, "task.json"), data, 0o644) //nolint:gosec // G306: the task container reads its brief as another user. } // Pool manages a set of Docker containers running archie-agent. @@ -699,7 +699,7 @@ func encodeRegistryAuth(credential string) (string, error) { if auth.Username == "" && auth.Password == "" && auth.IdentityToken == "" && auth.RegistryToken == "" { return "", errors.New("registry credential names no username, password, identity token or registry token") } - payload, err := json.Marshal(auth) + payload, err := json.Marshal(auth) //nolint:gosec // G117: the registry credential is meant for the image pull's auth header. if err != nil { return "", fmt.Errorf("encode registry credential: %w", err) } diff --git a/internal/daemon/pr_review_prefetch.go b/internal/daemon/pr_review_prefetch.go index 601030315..5d85729be 100644 --- a/internal/daemon/pr_review_prefetch.go +++ b/internal/daemon/pr_review_prefetch.go @@ -54,7 +54,7 @@ func prefetchPRReview(ctx context.Context, f any, owner, repo string, number int if err != nil { return fmt.Errorf("prefetch pr-review: %w", err) } - if err := os.WriteFile(filepath.Join(base, "diff.patch"), []byte(diff), 0o644); err != nil { + if err := os.WriteFile(filepath.Join(base, "diff.patch"), []byte(diff), 0o644); err != nil { //nolint:gosec // G306: the task container reads the diff as another user. return fmt.Errorf("prefetch pr-review: write diff: %w", err) } @@ -66,7 +66,7 @@ func prefetchPRReview(ctx context.Context, f any, owner, repo string, number int if err != nil { return fmt.Errorf("prefetch pr-review: encode metadata: %w", err) } - if err := os.WriteFile(filepath.Join(base, "metadata.json"), metaJSON, 0o644); err != nil { + if err := os.WriteFile(filepath.Join(base, "metadata.json"), metaJSON, 0o644); err != nil { //nolint:gosec // G306: the task container reads the metadata as another user. return fmt.Errorf("prefetch pr-review: write metadata: %w", err) } return nil diff --git a/internal/domain/alert/alert.go b/internal/domain/alert/alert.go index 78ec1d290..1c637341e 100644 --- a/internal/domain/alert/alert.go +++ b/internal/domain/alert/alert.go @@ -67,7 +67,7 @@ const ( KindModelAlias = "model.alias" KindProviderNoKey = "provider.no_credential" KindToolNoBinding = "tool.no_credential" - KindCredentialInvalid = "credential.rejected" + KindCredentialInvalid = "credential.rejected" //nolint:gosec // G101: an alert kind, not a credential. KindServiceUnhealthy = "service.unhealthy" KindReleaseAvailable = "release.available" KindPolicyInvalid = "policy.invalid" diff --git a/internal/domain/identity/authentication_test.go b/internal/domain/identity/authentication_test.go index 961fa12fc..af1edd2aa 100644 --- a/internal/domain/identity/authentication_test.go +++ b/internal/domain/identity/authentication_test.go @@ -9,7 +9,7 @@ func TestAuthenticationSettingsRejectUntrustedOrigins(t *testing.T) { }{ {name: "public TLS", url: "https://archie.example", want: true}, {name: "localhost", url: "http://localhost:8484", want: true}, - {name: "userinfo is not an origin", url: "https://user:password@archie.example", want: false}, + {name: "userinfo is not an origin", url: "https://user:password@archie.example", want: false}, //nolint:gosec // G101: a fake URL with userinfo, which must be refused. {name: "URL path cannot change the RP origin", url: "https://archie.example/subpath", want: false}, {name: "query is not an origin", url: "https://archie.example?token=1", want: false}, {name: "complete provider", url: "https://archie.example", issuer: "https://identity.example", client: "archie", audience: "archie", want: true}, diff --git a/internal/domain/identity/common_passwords.go b/internal/domain/identity/common_passwords.go index b8c5c243c..e5bbaf811 100644 --- a/internal/domain/identity/common_passwords.go +++ b/internal/domain/identity/common_passwords.go @@ -26,6 +26,7 @@ package identity // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. +//nolint:gosec // G101: the list of passwords sign-up refuses. const commonPasswords = ` $hex[687474703a2f2f616473] $hex[687474703a2f2f777777] diff --git a/internal/infrastructure/configuration/setup/setup_test.go b/internal/infrastructure/configuration/setup/setup_test.go index 59cf40fb0..0d4c6b88d 100644 --- a/internal/infrastructure/configuration/setup/setup_test.go +++ b/internal/infrastructure/configuration/setup/setup_test.go @@ -89,7 +89,7 @@ func bundledMigrationURL() string { // database as an explicit choice, switching to it must generate PGPASSWORD // into the sink, and keeping must leave the existing URL untouched. func TestRunParamsDatabaseChoice(t *testing.T) { - const existing = "postgres://operator:secret@db.internal:5432/archie" + const existing = "postgres://operator:secret@db.internal:5432/archie" //nolint:gosec // G101: a fake database URL. tests := []struct { name string diff --git a/internal/infrastructure/configuration/setup/step_provider.go b/internal/infrastructure/configuration/setup/step_provider.go index e7625a0fd..29f29b8e9 100644 --- a/internal/infrastructure/configuration/setup/step_provider.go +++ b/internal/infrastructure/configuration/setup/step_provider.go @@ -18,6 +18,7 @@ type cloudProvider struct { apiKeyEnv string } +//nolint:gosec // G101: env var names, not values. var cloudProviders = []cloudProvider{ {name: "OpenAI", class: "openai", apiKeyEnv: "OPENAI_API_KEY"}, {name: "Anthropic", class: "anthropic", apiKeyEnv: "ANTHROPIC_API_KEY"}, diff --git a/internal/infrastructure/controlplanestore/credential_bindings.go b/internal/infrastructure/controlplanestore/credential_bindings.go index 17ea82460..e355b1291 100644 --- a/internal/infrastructure/controlplanestore/credential_bindings.go +++ b/internal/infrastructure/controlplanestore/credential_bindings.go @@ -4,7 +4,7 @@ import "github.com/samcharles93/archie-core/internal/config" // CredentialBindingsKind is the resource mapping credential service names to // org secrets. Applied live on each launch. -const CredentialBindingsKind = "credential-bindings" +const CredentialBindingsKind = "credential-bindings" //nolint:gosec // G101: a resource kind, not a credential. // credentialBinding is one config.CredentialBinding as the document writes // it: explicit snake_case json tags, following channel_settings.go / diff --git a/internal/infrastructure/egress/ca.go b/internal/infrastructure/egress/ca.go index 895a8360c..a9d285089 100644 --- a/internal/infrastructure/egress/ca.go +++ b/internal/infrastructure/egress/ca.go @@ -97,7 +97,7 @@ func createCA(dir, certPath, keyPath string) (*CA, error) { if err := os.WriteFile(keyPath, keyPEM, 0o600); err != nil { return nil, err } - if err := os.WriteFile(certPath, certPEM, 0o644); err != nil { + if err := os.WriteFile(certPath, certPEM, 0o644); err != nil { //nolint:gosec // G306: a CA certificate is public; its key is written 0600 above. return nil, err } return parseCA(certPEM, keyPEM) diff --git a/internal/infrastructure/modelcatalog/catalog_test.go b/internal/infrastructure/modelcatalog/catalog_test.go index 14b8fcc48..c40587276 100644 --- a/internal/infrastructure/modelcatalog/catalog_test.go +++ b/internal/infrastructure/modelcatalog/catalog_test.go @@ -100,7 +100,7 @@ func TestUsableProviderCredentials(t *testing.T) { // again. func TestMergeProvidersKeepsDisabled(t *testing.T) { merged := mergeProviders( - map[string]config.Provider{"openai": {Class: "openai", APIKeyEnv: "OPENAI_API_KEY"}}, + map[string]config.Provider{"openai": {Class: "openai", APIKeyEnv: "OPENAI_API_KEY"}}, //nolint:gosec // G101: an env var name, not a value. map[string]config.Provider{"openai": {Disabled: true}}, ) if !merged["openai"].Disabled { diff --git a/internal/infrastructure/postgres/provision_test.go b/internal/infrastructure/postgres/provision_test.go index 1c1e1fa8c..b1cbea0c6 100644 --- a/internal/infrastructure/postgres/provision_test.go +++ b/internal/infrastructure/postgres/provision_test.go @@ -21,9 +21,9 @@ func testProvisionRoles() provisionRoles { // plan that would leave the runtime role owning schema changes. func TestParseProvisionURLs(t *testing.T) { const ( - adminURL = "postgres://archie:admin@db.internal/archie" - runtimeURL = "postgres://archie_runtime:runtime@db.internal/archie" - migrationURL = "postgres://archie_migrator:migration@db.internal/archie" + adminURL = "postgres://archie:admin@db.internal/archie" //nolint:gosec // G101: fake database URLs. + runtimeURL = "postgres://archie_runtime:runtime@db.internal/archie" //nolint:gosec // G101: fake database URLs. + migrationURL = "postgres://archie_migrator:migration@db.internal/archie" //nolint:gosec // G101: fake database URLs. ) tests := []struct { name string @@ -75,7 +75,7 @@ func TestParseProvisionURLs(t *testing.T) { }, { name: "the same role cannot be runtime and migration", - opts: ProvisionOptions{AdminURL: adminURL, RuntimeURL: runtimeURL, MigrationURL: "postgres://archie_runtime:other@db.internal/archie"}, + opts: ProvisionOptions{AdminURL: adminURL, RuntimeURL: runtimeURL, MigrationURL: "postgres://archie_runtime:other@db.internal/archie"}, //nolint:gosec // G101: a fake database URL. wantErr: "same role", }, { @@ -85,7 +85,7 @@ func TestParseProvisionURLs(t *testing.T) { }, { name: "a non-PostgreSQL URL is refused", - opts: ProvisionOptions{AdminURL: "mysql://archie:admin@db.internal/archie", RuntimeURL: runtimeURL, MigrationURL: migrationURL}, + opts: ProvisionOptions{AdminURL: "mysql://archie:admin@db.internal/archie", RuntimeURL: runtimeURL, MigrationURL: migrationURL}, //nolint:gosec // G101: a fake database URL. wantErr: "postgres:// URL", }, { diff --git a/internal/infrastructure/prsource/archive.go b/internal/infrastructure/prsource/archive.go index ac39a6576..0e5155c93 100644 --- a/internal/infrastructure/prsource/archive.go +++ b/internal/infrastructure/prsource/archive.go @@ -130,7 +130,7 @@ func writeEntry(destDir, prefix string, e tarEntry) error { if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { return err } - return os.WriteFile(target, e.data, 0o644) + return os.WriteFile(target, e.data, 0o644) //nolint:gosec // G306: the task container reads the checkout as another user. default: // Symlinks, devices, etc: not followed, not written. return nil diff --git a/internal/infrastructure/secretengine/namespaces_linux_test.go b/internal/infrastructure/secretengine/namespaces_linux_test.go index b21d2201b..55f289a22 100644 --- a/internal/infrastructure/secretengine/namespaces_linux_test.go +++ b/internal/infrastructure/secretengine/namespaces_linux_test.go @@ -14,7 +14,7 @@ import ( // at all and there is nothing here to test. func requireNamespaces(t *testing.T) { t.Helper() - cmd := exec.CommandContext(t.Context(), os.Args[0], "-test.run=^$") + cmd := exec.CommandContext(t.Context(), os.Args[0], "-test.run=^$") //nolint:gosec // G702: re-runs this test binary. cmd.SysProcAttr = &syscall.SysProcAttr{ Cloneflags: syscall.CLONE_NEWUSER | syscall.CLONE_NEWNET, UidMappings: []syscall.SysProcIDMap{{ContainerID: os.Getuid(), HostID: os.Getuid(), Size: 1}}, diff --git a/internal/infrastructure/secretengine/runner_test.go b/internal/infrastructure/secretengine/runner_test.go index a5d658e6d..3f531fe45 100644 --- a/internal/infrastructure/secretengine/runner_test.go +++ b/internal/infrastructure/secretengine/runner_test.go @@ -103,7 +103,7 @@ func TestMain(m *testing.M) { func selfDigest(t *testing.T) string { t.Helper() - binary, err := os.ReadFile(os.Args[0]) + binary, err := os.ReadFile(os.Args[0]) //nolint:gosec // G703: reads this test binary. if err != nil { t.Fatal(err) } @@ -243,7 +243,7 @@ func layerOf(t *testing.T, name string, content []byte) []byte { // An extension runs only while its package is accepted and the settings enable // it, and stops the moment either stops being true. func TestRunnerRunsOnlyWhatIsAcceptedAndEnabled(t *testing.T) { - binary, err := os.ReadFile(os.Args[0]) + binary, err := os.ReadFile(os.Args[0]) //nolint:gosec // G703: reads this test binary. if err != nil { t.Fatal(err) } diff --git a/internal/infrastructure/skillcurator/store.go b/internal/infrastructure/skillcurator/store.go index c27a4a8ef..55c10996f 100644 --- a/internal/infrastructure/skillcurator/store.go +++ b/internal/infrastructure/skillcurator/store.go @@ -85,7 +85,7 @@ func (s *Store) Write(_ context.Context, sk curator.Skill) error { if info, err := os.Stat(dir); err != nil || !info.IsDir() { return fmt.Errorf("skillcurator: skill %q does not exist under %s", sk.Name, s.skillsPath()) } - if err := os.WriteFile(s.skillPath(sk.Name), []byte(sk.Content), 0o644); err != nil { + if err := os.WriteFile(s.skillPath(sk.Name), []byte(sk.Content), 0o644); err != nil { //nolint:gosec // G306: agents read skills as another user. return fmt.Errorf("skillcurator: writing %s: %w", s.skillPath(sk.Name), err) } return nil diff --git a/internal/infrastructure/staterpc/model_provider_wire_test.go b/internal/infrastructure/staterpc/model_provider_wire_test.go index a4070c24f..911091cc2 100644 --- a/internal/infrastructure/staterpc/model_provider_wire_test.go +++ b/internal/infrastructure/staterpc/model_provider_wire_test.go @@ -14,7 +14,7 @@ func TestModelProviderWireCarriesCredentialRef(t *testing.T) { t.Parallel() sent := map[string]config.Provider{ - "remote": { + "remote": { //nolint:gosec // G101: env var and secret names, not values. Class: "deepseek", BaseURL: "https://example.invalid/v1", APIKeyEnv: "REMOTE_API_KEY", diff --git a/internal/infrastructure/storepkg/registry.go b/internal/infrastructure/storepkg/registry.go index ee4d1fbf7..9ef412ed7 100644 --- a/internal/infrastructure/storepkg/registry.go +++ b/internal/infrastructure/storepkg/registry.go @@ -153,7 +153,7 @@ func validateLayer(layer []byte, mediaType string, files []domain.File) error { return err } found[header.Name] = true - if _, err := io.Copy(io.Discard, tarReader); err != nil { + if _, err := io.Copy(io.Discard, tarReader); err != nil { //nolint:gosec // G110: the tar reader is bounded by io.LimitReader(maxPackageBytes). return err } } diff --git a/internal/releaseupdate/publish.go b/internal/releaseupdate/publish.go index 1128e6d01..c39fd9e77 100644 --- a/internal/releaseupdate/publish.go +++ b/internal/releaseupdate/publish.go @@ -74,7 +74,7 @@ func Publish(ctx context.Context, req PublishRequest) (Statement, error) { for i, content := range [][]byte{ocispec.DescriptorEmptyJSON.Data, encoded, archive} { desc := ocispec.DescriptorEmptyJSON if i > 0 { - desc = layers[i-1] + desc = layers[i-1] //nolint:gosec // G602: i > 0 indexes the two layers built above. } if err := pushBlob(ctx, repository, desc, content); err != nil { return Statement{}, err diff --git a/internal/releaseupdate/transaction_test.go b/internal/releaseupdate/transaction_test.go index efb40a638..699015ea5 100644 --- a/internal/releaseupdate/transaction_test.go +++ b/internal/releaseupdate/transaction_test.go @@ -198,7 +198,7 @@ func TestTransaction(t *testing.T) { server := httptest.NewServer(handler) defer server.Close() for _, unit := range testUnits { - writeTestFile(t, filepath.Join(host.bin, unit), versionScript(unit, "1.0.0")) + writeScript(t, filepath.Join(host.bin, unit), versionScript(unit, "1.0.0")) } report := filepath.Join(root, "report.json") tx := &Transaction{ @@ -358,12 +358,13 @@ func versionScript(unit, version string) string { return fmt.Sprintf("#!/bin/sh\n# %s %s\necho '%s %s'\n", unit, version, unit, version) } -func writeTestFile(t *testing.T, path, data string) { +// writeScript writes a stand-in for a release binary the transaction runs. +func writeScript(t *testing.T, path, data string) { t.Helper() if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { t.Fatal(err) } - if err := os.WriteFile(path, []byte(data), 0o755); err != nil { + if err := os.WriteFile(path, []byte(data), 0o700); err != nil { //nolint:gosec // G306: a script needs the execute bit. t.Fatal(err) } } diff --git a/internal/taskstate/taskstate.go b/internal/taskstate/taskstate.go index c04898105..5284d554a 100644 --- a/internal/taskstate/taskstate.go +++ b/internal/taskstate/taskstate.go @@ -308,7 +308,7 @@ const ( BlockerForgeExtension Blocker = "forge_extension" // BlockerModelCredential: a model provider the run needs has no usable // credential. - BlockerModelCredential Blocker = "model_credential" + BlockerModelCredential Blocker = "model_credential" //nolint:gosec // G101: a blocker name, not a credential. // BlockerModelCredit: a model provider refused the run for want of // credit or quota on its account. BlockerModelCredit Blocker = "model_credit" diff --git a/internal/tools/builtin/write.go b/internal/tools/builtin/write.go index 886e15d66..fdf8a807d 100644 --- a/internal/tools/builtin/write.go +++ b/internal/tools/builtin/write.go @@ -117,7 +117,7 @@ func makeWriteExecutor(cwd string, mq *MutationQueue, rt *ReadTracker) Executor // file, a directory, a symlink, or any other non-regular entry returns false, // which lets new files skip the overwrite and read-before-write checks. func isRegularFile(path string) bool { - info, err := os.Stat(path) + info, err := os.Stat(path) //nolint:gosec // G703: callers confine path with isConfined first. return err == nil && info.Mode().IsRegular() } diff --git a/internal/tools/provider/mcp/provider.go b/internal/tools/provider/mcp/provider.go index d1882e08e..148e0b32b 100644 --- a/internal/tools/provider/mcp/provider.go +++ b/internal/tools/provider/mcp/provider.go @@ -297,7 +297,7 @@ func (p *Provider) writeMultimodalResult(toolName, summaryText string, media []p ext := extensionForMimeType(mimeType) name := fmt.Sprintf("%d%s", i, ext) path := filepath.Join(subdir, name) - if err := os.WriteFile(path, raw, 0o644); err != nil { + if err := os.WriteFile(path, raw, 0o644); err != nil { //nolint:gosec // G306: the agent reads tool media as another user. return tools.MultimodalResult{}, fmt.Errorf("MCP tool %s: write media block %d: %w", toolName, i, err) } files = append(files, path) diff --git a/internal/webui/access_denials_test.go b/internal/webui/access_denials_test.go index b7367e397..571a6013a 100644 --- a/internal/webui/access_denials_test.go +++ b/internal/webui/access_denials_test.go @@ -57,7 +57,7 @@ func TestDenialsRouteRequiresAdmin(t *testing.T) { } req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "https://archie.example"+path, nil) req.Header.Set("X-Archie-CSRF", "1") - req.AddCookie(&http.Cookie{Name: "archie_session", Value: "valid"}) + sendCookie(req, "archie_session", "valid") rec := httptest.NewRecorder() srv.Handler().ServeHTTP(rec, req) if rec.Code != tt.want { diff --git a/internal/webui/accounts.go b/internal/webui/accounts.go index ccfb8c778..a685934b3 100644 --- a/internal/webui/accounts.go +++ b/internal/webui/accounts.go @@ -152,14 +152,13 @@ func (s *Server) signInAccount(w http.ResponseWriter, r *http.Request, email, pa if s.Log != nil { s.Log.InfoContext(r.Context(), "account signed in", "identity", value.Identity.ID) } - s.clearProviderCookie(w) + s.clearCookie(w, r, s.cookies().providerToken, "/") s.setAccountCookie(w, r, value) writeJSON(w, map[string]any{"user": value.Identity}) } func (s *Server) setAccountCookie(w http.ResponseWriter, r *http.Request, value identity.AccountSession) { - scheme, _ := s.expectedOrigin(r) - http.SetCookie(w, &http.Cookie{Name: s.cookies().account, Value: value.Token, Path: "/", HttpOnly: true, Secure: scheme == "https", SameSite: http.SameSiteStrictMode, Expires: value.Expires, MaxAge: int(time.Until(value.Expires).Seconds())}) + s.setCookie(w, r, cookie{name: s.cookies().account, value: value.Token, maxAge: int(time.Until(value.Expires).Seconds())}) w.Header().Set("Cache-Control", "no-store") } @@ -174,7 +173,7 @@ func (s *Server) handleAccountLogout(w http.ResponseWriter, r *http.Request) { } } for _, name := range []string{s.cookies().account, s.cookies().providerToken} { - http.SetCookie(w, &http.Cookie{Name: name, Path: "/", HttpOnly: true, MaxAge: -1, SameSite: http.SameSiteStrictMode}) + s.clearCookie(w, r, name, "/") } w.WriteHeader(http.StatusNoContent) } @@ -214,7 +213,7 @@ func (s *Server) handleAccountPassword(w http.ResponseWriter, r *http.Request) { s.writeAccountError(w, err) return } - http.SetCookie(w, &http.Cookie{Name: s.cookies().account, Path: "/", MaxAge: -1, HttpOnly: true, SameSite: http.SameSiteStrictMode}) + s.clearCookie(w, r, s.cookies().account, "/") w.WriteHeader(http.StatusNoContent) } @@ -356,10 +355,6 @@ func (s *Server) handleAccountRecover(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNoContent) } -func (s *Server) clearProviderCookie(w http.ResponseWriter) { - http.SetCookie(w, &http.Cookie{Name: s.cookies().providerToken, Path: "/", HttpOnly: true, SameSite: http.SameSiteStrictMode, MaxAge: -1}) -} - func (s *Server) authorizeAuthenticationMutation(w http.ResponseWriter, r *http.Request) bool { if !s.authorizeTaskMutation(w, r) { return false diff --git a/internal/webui/accounts_test.go b/internal/webui/accounts_test.go index f30538141..484cde3cb 100644 --- a/internal/webui/accounts_test.go +++ b/internal/webui/accounts_test.go @@ -74,7 +74,7 @@ func TestAccountBoundary(t *testing.T) { req.Header.Set("Content-Type", "application/json") req.Header.Set("X-Archie-CSRF", tc.csrf) if tc.cookie != "" { - req.AddCookie(&http.Cookie{Name: "archie_session", Value: tc.cookie}) + sendCookie(req, "archie_session", tc.cookie) } recorder := httptest.NewRecorder() srv.Handler().ServeHTTP(recorder, req) diff --git a/internal/webui/api_setup.go b/internal/webui/api_setup.go index f3e0f091e..61db52ca3 100644 --- a/internal/webui/api_setup.go +++ b/internal/webui/api_setup.go @@ -35,7 +35,7 @@ type ModelReader interface { // rather than imported so the dashboard package stays a leaf. const ( providerSettingsKind = "provider-settings" - credentialBindingsKind = "credential-bindings" + credentialBindingsKind = "credential-bindings" //nolint:gosec // G101: a resource kind, not a credential. ) // providerDoc is the part of one provider-settings entry the read needs: where diff --git a/internal/webui/auth.go b/internal/webui/auth.go index 0f56d79dc..f1b2c2f72 100644 --- a/internal/webui/auth.go +++ b/internal/webui/auth.go @@ -85,19 +85,12 @@ func (s *Server) requireToken(h http.Handler) http.Handler { http.Error(w, "unauthorised", http.StatusUnauthorized) return } - http.SetCookie(w, &http.Cookie{ - Name: s.cookies().token, - Value: tok, - Path: "/", - HttpOnly: true, - SameSite: http.SameSiteStrictMode, - Secure: r.TLS != nil, - }) + s.setCookie(w, r, cookie{name: s.cookies().token, value: tok}) clean := *r.URL q := clean.Query() q.Del("t") clean.RawQuery = q.Encode() - http.Redirect(w, r, sameOriginPath(clean.Path, clean.RawQuery), http.StatusSeeOther) + http.Redirect(w, r, sameOriginPath(clean.Path, clean.RawQuery), http.StatusSeeOther) //nolint:gosec // G710: sameOriginPath keeps the redirect on this origin. return } @@ -172,8 +165,8 @@ func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) { s.refuseUnidentified(w, r, err) return } - setFlowCookie(w, r, s.cookies().loginState, state) - setFlowCookie(w, r, s.cookies().loginVerifier, verifier) + s.setFlowCookie(w, r, s.cookies().loginState, state) + s.setFlowCookie(w, r, s.cookies().loginVerifier, verifier) http.Redirect(w, r, url, http.StatusSeeOther) } @@ -211,8 +204,8 @@ func (s *Server) handleCallback(w http.ResponseWriter, r *http.Request) { s.refuseUnidentified(w, r, err) return } - clearFlowCookie(w, r, s.cookies().loginState) - clearFlowCookie(w, r, s.cookies().loginVerifier) + s.clearFlowCookie(w, r, s.cookies().loginState) + s.clearFlowCookie(w, r, s.cookies().loginVerifier) if security, ok := s.Accounts.(identity.AccountSecurity); ok { principal, resolveErr := s.Principals.PrincipalFor(r.Context(), value.ID) if resolveErr != nil { @@ -226,26 +219,16 @@ func (s *Server) handleCallback(w http.ResponseWriter, r *http.Request) { } s.setAccountCookie(w, r, local) } - http.SetCookie(w, &http.Cookie{ - Name: s.cookies().providerToken, Value: session.Token, Path: "/", - HttpOnly: true, SameSite: http.SameSiteStrictMode, Secure: r.TLS != nil, - }) + s.setCookie(w, r, cookie{name: s.cookies().providerToken, value: session.Token}) http.Redirect(w, r, "/", http.StatusSeeOther) } -func setFlowCookie(w http.ResponseWriter, r *http.Request, name, value string) { - http.SetCookie(w, &http.Cookie{ - Name: name, Value: value, Path: "/oauth2", - HttpOnly: true, SameSite: http.SameSiteLaxMode, Secure: r.TLS != nil, - MaxAge: loginCookieMaxAge, - }) +func (s *Server) setFlowCookie(w http.ResponseWriter, r *http.Request, name, value string) { + s.setCookie(w, r, cookie{name: name, value: value, path: "/oauth2", sameSite: http.SameSiteLaxMode, maxAge: loginCookieMaxAge}) } -func clearFlowCookie(w http.ResponseWriter, r *http.Request, name string) { - http.SetCookie(w, &http.Cookie{ - Name: name, Value: "", Path: "/oauth2", - HttpOnly: true, SameSite: http.SameSiteLaxMode, Secure: r.TLS != nil, MaxAge: -1, - }) +func (s *Server) clearFlowCookie(w http.ResponseWriter, r *http.Request, name string) { + s.setCookie(w, r, cookie{name: name, path: "/oauth2", sameSite: http.SameSiteLaxMode, maxAge: -1}) } // randomToken returns a fresh URL-safe nonce for a sign-in's state. diff --git a/internal/webui/authorization_surfaces_test.go b/internal/webui/authorization_surfaces_test.go index 9fea2db20..42b9adca4 100644 --- a/internal/webui/authorization_surfaces_test.go +++ b/internal/webui/authorization_surfaces_test.go @@ -148,7 +148,7 @@ func TestHTTPPolicyCannotBeBypassed(t *testing.T) { req.Header.Set("X-Archie-CSRF", "1") want := http.StatusUnauthorized if signedIn { - req.AddCookie(&http.Cookie{Name: "archie_session", Value: "valid"}) + sendCookie(req, "archie_session", "valid") want = http.StatusForbidden } rec := httptest.NewRecorder() @@ -189,7 +189,7 @@ func TestResourceHistoryNeedsPolicyManagement(t *testing.T) { } req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "https://archie.example"+path, nil) req.Header.Set("X-Archie-CSRF", "1") - req.AddCookie(&http.Cookie{Name: "archie_session", Value: "valid"}) + sendCookie(req, "archie_session", "valid") rec := httptest.NewRecorder() srv.Handler().ServeHTTP(rec, req) if rec.Code != tt.want { @@ -231,7 +231,7 @@ func TestAuditRoutesFollowTheReadAuditRole(t *testing.T) { } req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "https://archie.example"+route.path, nil) req.Header.Set("X-Archie-CSRF", "1") - req.AddCookie(&http.Cookie{Name: "archie_session", Value: "valid"}) + sendCookie(req, "archie_session", "valid") rec := httptest.NewRecorder() srv.Handler().ServeHTTP(rec, req) if rec.Code != tt.want { diff --git a/internal/webui/chat_files_test.go b/internal/webui/chat_files_test.go index fca1b5411..55b7a7f20 100644 --- a/internal/webui/chat_files_test.go +++ b/internal/webui/chat_files_test.go @@ -33,7 +33,7 @@ func TestChatFileDownload(t *testing.T) { }{ {name: "an offered file is served", token: token, want: http.StatusOK}, {name: "a token nobody was given is refused", token: "0123456789abcdef0123456789abcdef", want: http.StatusNotFound}, - {name: "a path is not a token", token: "..%2f..%2fetc%2fpasswd", want: http.StatusNotFound}, + {name: "a path is not a token", token: "..%2f..%2fetc%2fpasswd", want: http.StatusNotFound}, //nolint:gosec // G101: a fake file token. {name: "owner downloads private file", user: "alice", token: private, want: http.StatusOK}, {name: "another person cannot download", user: "bob", token: private, want: http.StatusNotFound}, {name: "unidentified caller cannot download private file", token: private, want: http.StatusNotFound}, diff --git a/internal/webui/cookies.go b/internal/webui/cookies.go index 17d88213d..799326023 100644 --- a/internal/webui/cookies.go +++ b/internal/webui/cookies.go @@ -1,6 +1,9 @@ package webui -import "strings" +import ( + "net/http" + "strings" +) // cookieNames are the dashboard's cookie names. Browsers scope cookies by host // and ignore the port, so each name carries the instance: two instances on @@ -27,3 +30,31 @@ func newCookieNames(instance string) cookieNames { } func (s *Server) cookies() cookieNames { return newCookieNames(s.Instance) } + +// cookie is what varies between the dashboard's cookies. Every one is +// HttpOnly, and Secure whenever the browser reached the dashboard over HTTPS. +type cookie struct { + name, value, path string + // sameSite defaults to Strict; the sign-in flow needs Lax to survive the + // provider's redirect back. + sameSite http.SameSite + // maxAge is in seconds; negative deletes the cookie. + maxAge int +} + +func (s *Server) setCookie(w http.ResponseWriter, r *http.Request, c cookie) { + if c.path == "" { + c.path = "/" + } + if c.sameSite == 0 { + c.sameSite = http.SameSiteStrictMode + } + http.SetCookie(w, &http.Cookie{ //nolint:gosec // G124: a fixed Secure would stop plain-HTTP deployments signing in. + Name: c.name, Value: c.value, Path: c.path, MaxAge: c.maxAge, + HttpOnly: true, Secure: s.secureRequest(r), SameSite: c.sameSite, + }) +} + +func (s *Server) clearCookie(w http.ResponseWriter, r *http.Request, name, path string) { + s.setCookie(w, r, cookie{name: name, path: path, maxAge: -1}) +} diff --git a/internal/webui/cookies_test.go b/internal/webui/cookies_test.go new file mode 100644 index 000000000..f8e4bb443 --- /dev/null +++ b/internal/webui/cookies_test.go @@ -0,0 +1,50 @@ +package webui + +import ( + "crypto/tls" + "net/http" + "net/http/httptest" + "testing" +) + +// sendCookie attaches a cookie to a request as a browser sends it: a name and +// a value, with none of the attributes a response sets. +func sendCookie(req *http.Request, name, value string) { + req.Header.Add("Cookie", name+"="+value) +} + +// TestSessionCookiesSecureBehindProxy pins that a cookie is marked Secure +// whenever the browser reached the dashboard over HTTPS, including through a +// trusted proxy that terminates TLS. +func TestSessionCookiesSecureBehindProxy(t *testing.T) { + tests := []struct { + name string + tls bool + forwarded string + trust bool + wantSecure bool + }{ + {"direct https", true, "", false, true}, + {"plain http", false, "", false, false}, + {"trusted proxy terminating https", false, "https", true, true}, + {"untrusted forwarded header", false, "https", false, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + s := &Server{TrustForwardedHeaders: tt.trust} + r := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/", nil) + if tt.tls { + r.TLS = &tls.ConnectionState{} + } + if tt.forwarded != "" { + r.Header.Set("X-Forwarded-Proto", tt.forwarded) + } + w := httptest.NewRecorder() + s.setOrgCookie(w, r, "acme") + cookies := w.Result().Cookies() + if len(cookies) != 1 || cookies[0].Secure != tt.wantSecure { + t.Fatalf("cookies = %+v, want one with Secure=%v", cookies, tt.wantSecure) + } + }) + } +} diff --git a/internal/webui/org_selection.go b/internal/webui/org_selection.go index ed2135529..425a2ef44 100644 --- a/internal/webui/org_selection.go +++ b/internal/webui/org_selection.go @@ -41,14 +41,11 @@ func (s *Server) workspaces() access.WorkspaceLister { } func (s *Server) setOrgCookie(w http.ResponseWriter, r *http.Request, id string) { - cookie := &http.Cookie{ - Name: s.cookies().org, Value: id, Path: "/", - HttpOnly: true, SameSite: http.SameSiteStrictMode, Secure: r.TLS != nil, MaxAge: orgCookieMaxAge, - } if id == "" { - cookie.MaxAge = -1 + s.clearCookie(w, r, s.cookies().org, "/") + return } - http.SetCookie(w, cookie) + s.setCookie(w, r, cookie{name: s.cookies().org, value: id, maxAge: orgCookieMaxAge}) } // handleOrgSelect makes the caller's chosen org the one its tasks, workflows diff --git a/internal/webui/orgs_test.go b/internal/webui/orgs_test.go index 671271c9e..655873aa4 100644 --- a/internal/webui/orgs_test.go +++ b/internal/webui/orgs_test.go @@ -484,7 +484,7 @@ func TestOrgSelection(t *testing.T) { req.Header.Set("Content-Type", "application/json") } if tt.cookie != "" { - req.AddCookie(&http.Cookie{Name: s.cookies().org, Value: tt.cookie}) + sendCookie(req, s.cookies().org, tt.cookie) } rec := httptest.NewRecorder() orgRoutes(s).ServeHTTP(rec, req) diff --git a/internal/webui/passkeys.go b/internal/webui/passkeys.go index abeeb7090..8f014c8c5 100644 --- a/internal/webui/passkeys.go +++ b/internal/webui/passkeys.go @@ -40,8 +40,7 @@ func (s *Server) handlePasskeyBegin(w http.ResponseWriter, r *http.Request, regi s.writeAccountError(w, err) return } - scheme, _ := s.expectedOrigin(r) - http.SetCookie(w, &http.Cookie{Name: s.passkeyCookie(registration), Value: value.Token, Path: "/api/", HttpOnly: true, Secure: scheme == "https", SameSite: http.SameSiteStrictMode, MaxAge: 300}) + s.setCookie(w, r, cookie{name: s.passkeyCookie(registration), value: value.Token, path: "/api/", maxAge: 300}) w.Header().Set("Cache-Control", "no-store") writeJSON(w, json.RawMessage(value.Options)) } @@ -63,7 +62,7 @@ func (s *Server) handlePasskeyFinish(w http.ResponseWriter, r *http.Request, reg http.Error(w, "passkey request expired", http.StatusUnauthorized) return } - http.SetCookie(w, &http.Cookie{Name: s.passkeyCookie(registration), Path: "/api/", HttpOnly: true, SameSite: http.SameSiteStrictMode, MaxAge: -1}) + s.clearCookie(w, r, s.passkeyCookie(registration), "/api/") var request struct { Credential json.RawMessage `json:"credential"` Name string `json:"name"` @@ -77,7 +76,7 @@ func (s *Server) handlePasskeyFinish(w http.ResponseWriter, r *http.Request, reg return } if !registration { - s.clearProviderCookie(w) + s.clearCookie(w, r, s.cookies().providerToken, "/") s.setAccountCookie(w, r, value) } writeJSON(w, map[string]any{"user": value.Identity}) diff --git a/internal/webui/server.go b/internal/webui/server.go index 3ac5eced5..d26826682 100644 --- a/internal/webui/server.go +++ b/internal/webui/server.go @@ -243,6 +243,13 @@ type Server struct { latest map[string]liveUpdate } +// secureRequest reports whether the browser reached the dashboard over HTTPS, +// directly or through a trusted proxy that terminates TLS. +func (s *Server) secureRequest(r *http.Request) bool { + scheme, _ := s.expectedOrigin(r) + return scheme == "https" +} + func (s *Server) trustForwardedHeaders() bool { if s == nil { return false diff --git a/internal/webui/usage_test.go b/internal/webui/usage_test.go index 0ed2fb29f..94c7d3bdb 100644 --- a/internal/webui/usage_test.go +++ b/internal/webui/usage_test.go @@ -48,7 +48,7 @@ func TestUsageNeedsAdminOrOwner(t *testing.T) { } req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "https://archie.example/api/usage", nil) req.Header.Set("X-Archie-CSRF", "1") - req.AddCookie(&http.Cookie{Name: "archie_session", Value: "valid"}) + sendCookie(req, "archie_session", "valid") rec := httptest.NewRecorder() srv.Handler().ServeHTTP(rec, req) if rec.Code != tt.want { diff --git a/internal/worktree/http_test.go b/internal/worktree/http_test.go index ca3d2f147..35b8b4c01 100644 --- a/internal/worktree/http_test.go +++ b/internal/worktree/http_test.go @@ -2,7 +2,7 @@ package worktree import ( "net/http" - "net/http/cgi" + "net/http/cgi" //nolint:gosec // G504: serves git http-backend; the Httpoxy CVE predates Go 1.6.3. "net/http/httptest" "os" "os/exec" @@ -87,7 +87,7 @@ func TestForgeHTTPAuthentication(t *testing.T) { defer target.Close() server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if tc.foreign { - http.Redirect(w, r, target.URL+r.URL.RequestURI(), http.StatusTemporaryRedirect) + http.Redirect(w, r, target.URL+r.URL.RequestURI(), http.StatusTemporaryRedirect) //nolint:gosec // G710: the foreign redirect is what the test checks. return } user, password, ok := r.BasicAuth() @@ -101,7 +101,7 @@ func TestForgeHTTPAuthentication(t *testing.T) { return } if tc.redirect && !strings.HasPrefix(r.URL.Path, "/redirect/") { - http.Redirect(w, r, "/redirect"+r.URL.RequestURI(), http.StatusTemporaryRedirect) + http.Redirect(w, r, "/redirect"+r.URL.RequestURI(), http.StatusTemporaryRedirect) //nolint:gosec // G710: the foreign redirect is what the test checks. return } r.URL.Path = strings.TrimPrefix(r.URL.Path, "/redirect") diff --git a/internal/worktree/worktree.go b/internal/worktree/worktree.go index d06756d6e..89cf0e251 100644 --- a/internal/worktree/worktree.go +++ b/internal/worktree/worktree.go @@ -9,6 +9,7 @@ import ( "errors" "fmt" "io" + "io/fs" "log/slog" "os" "path/filepath" @@ -550,18 +551,20 @@ func cleanUntracked(dir string, tree *object.Tree) error { if err := collectTrackedPaths(tree, "", files, dirs, opaqueDirs); err != nil { return err } - return filepath.WalkDir(dir, func(path string, entry os.DirEntry, walkErr error) error { + // The agent writes this tree, so every operation goes through a root that + // refuses to follow a symlink out of it, even one swapped in mid-walk. + root, err := os.OpenRoot(dir) + if err != nil { + return err + } + defer func() { _ = root.Close() }() + return fs.WalkDir(root.FS(), ".", func(rel string, entry fs.DirEntry, walkErr error) error { if walkErr != nil { return walkErr } - if path == dir { + if rel == "." { return nil } - rel, err := filepath.Rel(dir, path) - if err != nil { - return err - } - rel = filepath.ToSlash(rel) if rel == ".git" { // Leave a .git file or directory alone. if entry.IsDir() { @@ -580,7 +583,7 @@ func cleanUntracked(dir string, tree *object.Tree) error { // directory sitting on a path the tree declares as a FILE -- is // output, not tracked content. It has to go before the reset can // write the file this path is supposed to hold. - if err := os.RemoveAll(path); err != nil { + if err := root.RemoveAll(rel); err != nil { return err } return filepath.SkipDir @@ -588,7 +591,7 @@ func cleanUntracked(dir string, tree *object.Tree) error { if _, ok := files[rel]; ok { return nil } - return os.Remove(path) + return root.Remove(rel) }) } @@ -634,7 +637,7 @@ func (m *Manager) setIdentity(r *git.Repository) error { // writeSentinel marks the worktree as fully prepared. func writeSentinel(dir string) error { - if err := os.WriteFile(filepath.Join(dir, preparedSentinel), nil, 0o644); err != nil { + if err := os.WriteFile(filepath.Join(dir, preparedSentinel), nil, 0o644); err != nil { //nolint:gosec // G306: the task container reads the sentinel as another user. return fmt.Errorf("write prepared sentinel: %w", err) } return nil @@ -1046,7 +1049,7 @@ func writeSnapshotFile(destDir string, file *object.File) error { if err != nil { return fmt.Errorf("read tracked file %s: %w", file.Name, err) } - if err := os.WriteFile(target, []byte(contents), 0o644); err != nil { + if err := os.WriteFile(target, []byte(contents), 0o644); err != nil { //nolint:gosec // G306: the task container works on these files as another user. return fmt.Errorf("write snapshot file %s: %w", file.Name, err) } return nil