From db5d2fb19f59560c0937c7e2fc90f4f6db2602be Mon Sep 17 00:00:00 2001 From: renatoathaydes Date: Thu, 8 Oct 2026 15:30:54 +0200 Subject: [PATCH 1/3] fix(setup): ignore a vanished ssh agent socket directory when chowning it chownAgentSock meant to skip an SSH_AUTH_SOCK directory that no longer exists, but checked ChownR's result with os.IsNotExist. ChownR returns a ChownFailures aggregate, which os.IsNotExist does not unwrap, so a gone socket directory aborted container setup with "chown ssh agent sock file: 1 entries could not be chowned ... no such file or directory". Add ChownFailures.AllVanished, matching AllDenied, and treat a result where every entry vanished as nothing to do. Any other failure, including a mix of vanished and denied entries, is still returned. Co-Authored-By: Claude Opus 5.5 --- pkg/copy/copy.go | 12 +++++++ pkg/copy/copy_test.go | 41 +++++++++++++++++++++++ pkg/devcontainer/setup/setup.go | 19 ++++++++--- pkg/devcontainer/setup/setup_unix_test.go | 41 +++++++++++++++++++++++ 4 files changed, 108 insertions(+), 5 deletions(-) diff --git a/pkg/copy/copy.go b/pkg/copy/copy.go index bc371577f6..9944825ff5 100644 --- a/pkg/copy/copy.go +++ b/pkg/copy/copy.go @@ -1,6 +1,7 @@ package copy import ( + "errors" "fmt" "io" "io/fs" @@ -64,6 +65,17 @@ func (fs ChownFailures) AllDenied() bool { return len(fs) > 0 } +// AllVanished reports whether every failure is an entry that no longer +// exists, e.g. a socket directory removed before or during the walk. +func (fs ChownFailures) AllVanished() bool { + for _, f := range fs { + if !errors.Is(f.Err, os.ErrNotExist) { + return false + } + } + return len(fs) > 0 +} + func ChownR(path string, userName string) error { if userName == "" { return nil diff --git a/pkg/copy/copy_test.go b/pkg/copy/copy_test.go index 0f690ffb0f..3f4fb2a543 100644 --- a/pkg/copy/copy_test.go +++ b/pkg/copy/copy_test.go @@ -271,3 +271,44 @@ func TestChownRSameOwnerSucceeds(t *testing.T) { t.Fatalf("ChownR same owner: %v", err) } } + +func TestChownRMissingRootIsVanished(t *testing.T) { + missing := filepath.Join(t.TempDir(), "gone") + + err := ChownR(missing, currentUserName(t)) + var failures ChownFailures + if !errors.As(err, &failures) { + t.Fatalf("ChownR err = %v, want ChownFailures", err) + } + if !failures.AllVanished() { + t.Errorf("AllVanished() = false for %v", failures) + } +} + +func TestAllVanishedRequiresEveryFailureToBeNotExist(t *testing.T) { + notExist := ChownFailure{Path: "/gone", Err: &os.PathError{ + Op: "lstat", Path: "/gone", Err: syscall.ENOENT, + }} + denied := ChownFailure{Path: "/denied", Err: &os.PathError{ + Op: "lchown", Path: "/denied", Err: syscall.EPERM, + }} + + tests := []struct { + name string + failures ChownFailures + want bool + }{ + {name: "empty", failures: ChownFailures{}, want: false}, + {name: "nil", failures: nil, want: false}, + {name: "only not exist", failures: ChownFailures{notExist}, want: true}, + {name: "not exist and denied", failures: ChownFailures{notExist, denied}, want: false}, + {name: "only denied", failures: ChownFailures{denied}, want: false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := tt.failures.AllVanished(); got != tt.want { + t.Errorf("AllVanished() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/pkg/devcontainer/setup/setup.go b/pkg/devcontainer/setup/setup.go index 2a88de982b..49cfbcb75b 100644 --- a/pkg/devcontainer/setup/setup.go +++ b/pkg/devcontainer/setup/setup.go @@ -725,11 +725,20 @@ func buildEnvMarker( func chownAgentSock(setupInfo *config.Result) error { user := config.GetRemoteUser(setupInfo) agentSockFile := os.Getenv("SSH_AUTH_SOCK") - if agentSockFile != "" { - err := copy2.ChownR(filepath.Dir(agentSockFile), user) - if err != nil && !os.IsNotExist(err) { - return err - } + if agentSockFile == "" { + return nil + } + + err := copy2.ChownR(filepath.Dir(agentSockFile), user) + var failures copy2.ChownFailures + switch { + case err == nil: + case errors.As(err, &failures) && failures.AllVanished(): + // The socket directory belongs to an SSH connection that may have + // closed, taking the directory with it: nothing is left to chown. + log.Debugf("skip chown: ssh agent socket %s is gone: %v", agentSockFile, err) + default: + return err } return nil diff --git a/pkg/devcontainer/setup/setup_unix_test.go b/pkg/devcontainer/setup/setup_unix_test.go index dbec14a3ac..764ef79af9 100644 --- a/pkg/devcontainer/setup/setup_unix_test.go +++ b/pkg/devcontainer/setup/setup_unix_test.go @@ -4,10 +4,13 @@ package setup import ( "os" + "os/user" "path/filepath" "syscall" "testing" "time" + + "github.com/devsy-org/devsy/pkg/devcontainer/config" ) // TestWriteResultFileTo_RejectsSymlinkWithoutFollowing guards against a @@ -62,3 +65,41 @@ func TestWriteResultFileTo_RejectsFIFOWithoutBlocking(t *testing.T) { t.Fatal("writeResultFileTo blocked for 2s+ opening a FIFO with no peer") } } + +func resultForRemoteUser(name string) *config.Result { + return &config.Result{ + MergedConfig: &config.MergedDevContainerConfig{ + DevContainerConfigBase: config.DevContainerConfigBase{RemoteUser: name}, + }, + } +} + +// TestChownAgentSock_VanishedSocketDirIsNotAnError covers an SSH_AUTH_SOCK +// whose directory went away with the connection that created it. +func TestChownAgentSock_VanishedSocketDirIsNotAnError(t *testing.T) { + currentUser, err := user.Current() + if err != nil { + t.Fatalf("current user: %v", err) + } + sock := filepath.Join(t.TempDir(), "devsy-ssh-agent-gone", "listener.sock") + t.Setenv("SSH_AUTH_SOCK", sock) + + if err := chownAgentSock(resultForRemoteUser(currentUser.Username)); err != nil { + t.Errorf("chownAgentSock() = %v, want nil", err) + } +} + +func TestChownAgentSock_DeniedChownIsAnError(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("requires an unprivileged user") + } + dir := filepath.Join(t.TempDir(), "devsy-ssh-agent-present") + if err := os.Mkdir(dir, 0o700); err != nil { + t.Fatalf("mkdir: %v", err) + } + t.Setenv("SSH_AUTH_SOCK", filepath.Join(dir, "listener.sock")) + + if err := chownAgentSock(resultForRemoteUser("root")); err == nil { + t.Error("chownAgentSock() = nil, want the chown failure") + } +} From 7a691691e1633cab1604919f4fcc4cb28dfb93e1 Mon Sep 17 00:00:00 2001 From: renatoathaydes Date: Thu, 8 Oct 2026 16:04:37 +0200 Subject: [PATCH 2/3] fix(agent): restore credentials env before applying the built image's env After a dockerless build, setup carries on in the same agent process. applyContainerEnv applies the built image's environment to that process, but the docker credentials cleanup ran deferred, after it, and restored the builder's PATH and DOCKER_CONFIG. patchEtcEnvironment then resolved remoteEnv against the builder's PATH and saved it, and the container daemon started with it, so on kubernetes every workspace ended up with PATH=/usr/local/bin:/.dockerless:/.dockerless/bin and could not find the image's tools. It used to go unnoticed because the "chown ssh agent sock file" failure stopped setup right before that step, and the next `up` started a new agent process, which loads the env file at startup. Run the cleanup first, then apply the image's environment, in a small finishBuild function with tests for the order and for a failed build. Co-Authored-By: Claude Opus 5.5 --- pkg/agent/dockerless.go | 24 ++++++++++---- pkg/agent/dockerless_test.go | 64 ++++++++++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+), 7 deletions(-) create mode 100644 pkg/agent/dockerless_test.go diff --git a/pkg/agent/dockerless.go b/pkg/agent/dockerless.go index c4a8f7513e..dbd41da531 100644 --- a/pkg/agent/dockerless.go +++ b/pkg/agent/dockerless.go @@ -77,17 +77,27 @@ func executeBuild(opts DockerlessBuildOptions) error { } cleanup := setupDockerCredentials(opts) - if cleanup != nil { - defer cleanup() - } - args := buildDockerlessArgs(binaryPath, opts) + buildErr := runDockerlessBuild(opts.Context, args, opts.Debug) - if err := runDockerlessBuild(opts.Context, args, opts.Debug); err != nil { - return err + return finishBuild(cleanup, buildErr, func() error { + return applyContainerEnv(opts.ImageConfigOutput) + }) +} + +// finishBuild runs the credentials cleanup and then, if the build succeeded, +// applies the built image's environment. The cleanup restores the builder's +// PATH and DOCKER_CONFIG, so it must run first: run after, it would overwrite +// the image's PATH in this process, which setup keeps using. +func finishBuild(cleanup func(), buildErr error, applyImageEnv func() error) error { + if cleanup != nil { + cleanup() + } + if buildErr != nil { + return buildErr } - return applyContainerEnv(opts.ImageConfigOutput) + return applyImageEnv() } func validateBuildOptions(opts DockerlessBuildOptions) error { diff --git a/pkg/agent/dockerless_test.go b/pkg/agent/dockerless_test.go new file mode 100644 index 0000000000..08e60f4d30 --- /dev/null +++ b/pkg/agent/dockerless_test.go @@ -0,0 +1,64 @@ +package agent + +import ( + "errors" + "os" + "testing" +) + +func TestFinishBuild_ImageEnvWinsOverCredentialsCleanup(t *testing.T) { + t.Setenv("PATH", "/builder/bin") + + var calls []string + cleanup := func() { + calls = append(calls, "cleanup") + _ = os.Setenv("PATH", "/builder/bin") + } + applyImageEnv := func() error { + calls = append(calls, "apply") + return os.Setenv("PATH", "/image/bin") + } + + if err := finishBuild(cleanup, nil, applyImageEnv); err != nil { + t.Fatalf("finishBuild: %v", err) + } + if got := os.Getenv("PATH"); got != "/image/bin" { + t.Errorf("PATH = %q, want the image's %q", got, "/image/bin") + } + if len(calls) != 2 || calls[0] != "cleanup" || calls[1] != "apply" { + t.Errorf("calls = %v, want [cleanup apply]", calls) + } +} + +func TestFinishBuild_FailedBuildCleansUpAndSkipsImageEnv(t *testing.T) { + buildErr := errors.New("build failed") + cleanups := 0 + applied := false + + err := finishBuild( + func() { cleanups++ }, + buildErr, + func() error { applied = true; return nil }, + ) + + if !errors.Is(err, buildErr) { + t.Errorf("err = %v, want %v", err, buildErr) + } + if cleanups != 1 { + t.Errorf("cleanup ran %d times, want 1", cleanups) + } + if applied { + t.Error("image env applied after a failed build") + } +} + +func TestFinishBuild_NoCleanup(t *testing.T) { + applied := false + + if err := finishBuild(nil, nil, func() error { applied = true; return nil }); err != nil { + t.Fatalf("finishBuild: %v", err) + } + if !applied { + t.Error("image env not applied") + } +} From fef1674b9279356eb71c40db0abe5c8c5b640fa2 Mon Sep 17 00:00:00 2001 From: renatoathaydes Date: Thu, 8 Oct 2026 18:08:24 +0200 Subject: [PATCH 3/3] docs: document functions touched by the chown and dockerless env fixes Co-Authored-By: Claude Opus 5.5 --- pkg/agent/dockerless.go | 3 +++ pkg/agent/dockerless_test.go | 8 ++++++++ pkg/copy/copy.go | 3 +++ pkg/copy/copy_test.go | 4 ++++ pkg/devcontainer/setup/setup.go | 3 +++ pkg/devcontainer/setup/setup_unix_test.go | 4 ++++ 6 files changed, 25 insertions(+) diff --git a/pkg/agent/dockerless.go b/pkg/agent/dockerless.go index dbd41da531..5055cdd9ec 100644 --- a/pkg/agent/dockerless.go +++ b/pkg/agent/dockerless.go @@ -64,6 +64,9 @@ func DockerlessBuild(opts DockerlessBuildOptions) error { return executeBuild(opts) } +// executeBuild runs the dockerless image build with the builder's registry +// credentials in place and, on success, applies the built image's environment +// to the current process. func executeBuild(opts DockerlessBuildOptions) error { buildContext := GetDockerlessBuildContext() if err := prepareBuildDirectory(buildContext); err != nil { diff --git a/pkg/agent/dockerless_test.go b/pkg/agent/dockerless_test.go index 08e60f4d30..d647722ea6 100644 --- a/pkg/agent/dockerless_test.go +++ b/pkg/agent/dockerless_test.go @@ -6,6 +6,9 @@ import ( "testing" ) +// TestFinishBuild_ImageEnvWinsOverCredentialsCleanup checks that the +// credentials cleanup runs before the image env is applied, so the image's +// PATH is the one left in the process. func TestFinishBuild_ImageEnvWinsOverCredentialsCleanup(t *testing.T) { t.Setenv("PATH", "/builder/bin") @@ -30,6 +33,9 @@ func TestFinishBuild_ImageEnvWinsOverCredentialsCleanup(t *testing.T) { } } +// TestFinishBuild_FailedBuildCleansUpAndSkipsImageEnv checks that a failed +// build still runs the cleanup once, returns the build error and never +// applies the image env. func TestFinishBuild_FailedBuildCleansUpAndSkipsImageEnv(t *testing.T) { buildErr := errors.New("build failed") cleanups := 0 @@ -52,6 +58,8 @@ func TestFinishBuild_FailedBuildCleansUpAndSkipsImageEnv(t *testing.T) { } } +// TestFinishBuild_NoCleanup checks that a nil cleanup is tolerated and the +// image env is still applied. func TestFinishBuild_NoCleanup(t *testing.T) { applied := false diff --git a/pkg/copy/copy.go b/pkg/copy/copy.go index 9944825ff5..79ccc75e92 100644 --- a/pkg/copy/copy.go +++ b/pkg/copy/copy.go @@ -76,6 +76,9 @@ func (fs ChownFailures) AllVanished() bool { return len(fs) > 0 } +// ChownR recursively changes the owner of path and everything under it to +// userName, without following symlinks. It keeps going past per-entry errors +// and returns them all as ChownFailures. An empty userName is a no-op. func ChownR(path string, userName string) error { if userName == "" { return nil diff --git a/pkg/copy/copy_test.go b/pkg/copy/copy_test.go index 3f4fb2a543..91efb7cf3d 100644 --- a/pkg/copy/copy_test.go +++ b/pkg/copy/copy_test.go @@ -272,6 +272,8 @@ func TestChownRSameOwnerSucceeds(t *testing.T) { } } +// TestChownRMissingRootIsVanished checks that chowning a path that does not +// exist yields ChownFailures that AllVanished recognises. func TestChownRMissingRootIsVanished(t *testing.T) { missing := filepath.Join(t.TempDir(), "gone") @@ -285,6 +287,8 @@ func TestChownRMissingRootIsVanished(t *testing.T) { } } +// TestAllVanishedRequiresEveryFailureToBeNotExist checks that AllVanished is +// true only for a non-empty set of failures that are all ErrNotExist. func TestAllVanishedRequiresEveryFailureToBeNotExist(t *testing.T) { notExist := ChownFailure{Path: "/gone", Err: &os.PathError{ Op: "lstat", Path: "/gone", Err: syscall.ENOENT, diff --git a/pkg/devcontainer/setup/setup.go b/pkg/devcontainer/setup/setup.go index 49cfbcb75b..a8b25c04fc 100644 --- a/pkg/devcontainer/setup/setup.go +++ b/pkg/devcontainer/setup/setup.go @@ -722,6 +722,9 @@ func buildEnvMarker( strings.Join(unsetKeys, "\n") } +// chownAgentSock hands the directory of SSH_AUTH_SOCK to the remote user so +// they can reach the forwarded SSH agent. A directory that has vanished along +// with its SSH connection is skipped rather than reported as an error. func chownAgentSock(setupInfo *config.Result) error { user := config.GetRemoteUser(setupInfo) agentSockFile := os.Getenv("SSH_AUTH_SOCK") diff --git a/pkg/devcontainer/setup/setup_unix_test.go b/pkg/devcontainer/setup/setup_unix_test.go index 764ef79af9..8f7ffb23e4 100644 --- a/pkg/devcontainer/setup/setup_unix_test.go +++ b/pkg/devcontainer/setup/setup_unix_test.go @@ -66,6 +66,8 @@ func TestWriteResultFileTo_RejectsFIFOWithoutBlocking(t *testing.T) { } } +// resultForRemoteUser returns a minimal setup result whose remote user is +// name. func resultForRemoteUser(name string) *config.Result { return &config.Result{ MergedConfig: &config.MergedDevContainerConfig{ @@ -89,6 +91,8 @@ func TestChownAgentSock_VanishedSocketDirIsNotAnError(t *testing.T) { } } +// TestChownAgentSock_DeniedChownIsAnError checks that a chown that fails for +// a reason other than a vanished directory is still reported. func TestChownAgentSock_DeniedChownIsAnError(t *testing.T) { if os.Geteuid() == 0 { t.Skip("requires an unprivileged user")