Skip to content

Commit d1d9b71

Browse files
committed
Add SSH_AUTH_SOCK lookup to exec command
1 parent 0b8644d commit d1d9b71

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

internal/pkg/devcontainers/dockerutils.go

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,10 +171,21 @@ func ExecInDevContainer(containerIDOrName string, workDir string, args []string)
171171
return err
172172
}
173173

174+
sshAuthSockValue, err := getSshAuthSockValue(containerID)
175+
if err != nil {
176+
// output error and continue without SSH_AUTH_SOCK value
177+
sshAuthSockValue = ""
178+
fmt.Printf("Warning: Failed to get SSH_AUTH_SOCK value: %s\n", err)
179+
fmt.Println("Continuing without setting SSH_AUTH_SOCK...")
180+
}
181+
174182
dockerArgs := []string{"exec", "-it", "--workdir", workDir}
175183
if userName != "" {
176184
dockerArgs = append(dockerArgs, "--user", userName)
177185
}
186+
if sshAuthSockValue != "" {
187+
dockerArgs = append(dockerArgs, "--env", "SSH_AUTH_SOCK="+sshAuthSockValue)
188+
}
178189
dockerArgs = append(dockerArgs, containerID)
179190
dockerArgs = append(dockerArgs, args...)
180191

@@ -192,3 +203,35 @@ func ExecInDevContainer(containerIDOrName string, workDir string, args []string)
192203
}
193204
return nil
194205
}
206+
207+
// getSshAuthSockValue returns the value to use for the SSH_AUTH_SOCK env var when exec'ing into the container, or empty string if no value is found
208+
func getSshAuthSockValue(containerID string) (string, error) {
209+
210+
// If the host has SSH_AUTH_SOCK set then VS Code spins up forwarding for key requests
211+
// inside the dev container to the SSH agent on the host.
212+
213+
hostSshAuthSockValue := os.Getenv("SSH_AUTH_SOCK")
214+
if hostSshAuthSockValue == "" {
215+
// Nothing to see, move along
216+
return "", nil
217+
}
218+
219+
// Host has SSH_AUTH_SOCK set, so expecting the dev container to have forwarding set up
220+
// Find the latest /tmp/vscode-ssh-auth-<...>.sock
221+
222+
dockerArgs := []string{"exec", containerID, "bash", "-c", "ls -t -d -1 \"${TMPDIR:-/tmp}\"/vscode-ssh-auth-*"}
223+
224+
dockerCmd := exec.Command("docker", dockerArgs...)
225+
buf, err := dockerCmd.CombinedOutput()
226+
if err != nil {
227+
errMessage := string(buf)
228+
return "", fmt.Errorf("Docker exec error: %s (%s)", err, strings.TrimSpace(errMessage))
229+
}
230+
231+
output := string(buf)
232+
lines := strings.Split(output, "\n")
233+
if len(lines) <= 0 {
234+
return "", nil
235+
}
236+
return strings.TrimSpace(lines[0]), nil
237+
}

0 commit comments

Comments
 (0)