Skip to content

Commit

Permalink
refactor(ssh): improve find extended agent (#31)
Browse files Browse the repository at this point in the history
1. add `Library/Group Containers/2BUA8C4S2C.com.1password/t/agent.sock`
path
2. support macos built-in agent fallback

Signed-off-by: Black-Hole1 <[email protected]>
  • Loading branch information
BlackHole1 authored Jan 18, 2024
1 parent c08f982 commit 8921092
Showing 1 changed file with 27 additions and 17 deletions.
44 changes: 27 additions & 17 deletions pkg/sshagentsock/sshagentsock.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"os/exec"
"path/filepath"
"strconv"
"strings"

"github.com/oomol-lab/ovm-ssh-agent/pkg/identity"
"github.com/oomol-lab/ovm-ssh-agent/pkg/sshagent"
Expand All @@ -17,37 +18,46 @@ import (

var knownAgentPaths = []string{
".1password/agent.sock",
"Library/Group Containers/2BUA8C4S2C.com.1password/t/agent.sock",
}

// FindExtendedAgent finds the extended agent path.
// The find will be done in the following order:
//
// 1. Check if the environment variable SSH_AUTH_SOCK exists (if it is the built-in agent in macOS, it will be used as an alternative).
// 2. Check if any known third-party agent exists at the specified path.
// 3. Get the ssh auth sock of the current system using launchctl.
// 4. If all the above steps fail, use the alternative. Otherwise, return empty
func FindExtendedAgent() (socketPath string, ok bool) {
if p, ok := os.LookupEnv("SSH_AUTH_SOCK"); ok {
return p, true
if strings.Contains(p, "com.apple.launchd.") {
socketPath = p
} else {
return p, true
}
}

home, err := os.UserHomeDir()
if err != nil {
if home, err := os.UserHomeDir(); err != nil {
goto LAUNCHD
}

for _, p := range knownAgentPaths {
p = filepath.Join(home, p)
if _, err := os.Stat(p); err == nil {
return p, true
} else {
for _, p := range knownAgentPaths {
p = filepath.Join(home, p)
if _, err := os.Stat(p); err == nil {
return p, true
}
}
}

LAUNCHD:
output, err := exec.Command("/bin/launchctl", "asuser", strconv.Itoa(os.Getuid()), "launchctl", "getenv", "SSH_AUTH_SOCK").CombinedOutput()
if err != nil {
return "", false
}

out := string(bytes.TrimSpace(output))
if _, err := os.Stat(out); err == nil {
return out, true
if err == nil {
out := string(bytes.TrimSpace(output))
if _, err := os.Stat(out); err == nil {
return out, true
}
}

return "", false
return socketPath, false
}

func Start(sshAuthSocketPath string, log *logger.Context) (*sshagent.SSHAgent, error) {
Expand Down

0 comments on commit 8921092

Please sign in to comment.