Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 20 additions & 7 deletions pkg/agent/dockerless.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -77,17 +80,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 {
Expand Down
72 changes: 72 additions & 0 deletions pkg/agent/dockerless_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package agent

import (
"errors"
"os"
"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")

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)
}
}

// 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
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")
}
}

// TestFinishBuild_NoCleanup checks that a nil cleanup is tolerated and the
// image env is still applied.
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")
}
}
15 changes: 15 additions & 0 deletions pkg/copy/copy.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package copy

import (
"errors"
"fmt"
"io"
"io/fs"
Expand Down Expand Up @@ -64,6 +65,20 @@ 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
}

// 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
Expand Down
45 changes: 45 additions & 0 deletions pkg/copy/copy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -271,3 +271,48 @@ func TestChownRSameOwnerSucceeds(t *testing.T) {
t.Fatalf("ChownR same owner: %v", err)
}
}

// 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")

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)
}
}

// 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,
}}
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)
}
})
}
}
22 changes: 17 additions & 5 deletions pkg/devcontainer/setup/setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -722,14 +722,26 @@ 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")
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
Expand Down
45 changes: 45 additions & 0 deletions pkg/devcontainer/setup/setup_unix_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -62,3 +65,45 @@ func TestWriteResultFileTo_RejectsFIFOWithoutBlocking(t *testing.T) {
t.Fatal("writeResultFileTo blocked for 2s+ opening a FIFO with no peer")
}
}

// resultForRemoteUser returns a minimal setup result whose remote user is
// name.
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)
}
}

// 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")
}
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")
}
}
Loading