Skip to content

Commit

Permalink
fix: parse username from git url when using SSH key auth (#5156)
Browse files Browse the repository at this point in the history
  • Loading branch information
chtcvl authored Apr 6, 2021
1 parent 7276bc3 commit 9b6c8b4
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
19 changes: 16 additions & 3 deletions workflow/artifacts/git/git.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"

log "github.com/sirupsen/logrus"
Expand All @@ -31,7 +32,18 @@ type ArtifactDriver struct {

var _ common.ArtifactDriver = &ArtifactDriver{}

func (g *ArtifactDriver) auth() (func(), transport.AuthMethod, []string, error) {
var sshURLRegex = regexp.MustCompile("^(ssh://)?([^/:]*?)@[^@]+$")

func GetUser(url string) string {
matches := sshURLRegex.FindStringSubmatch(url)
if len(matches) > 2 {
return matches[2]
}
// default to `git` user unless username is specified in SSH url
return "git"
}

func (g *ArtifactDriver) auth(sshUser string) (func(), transport.AuthMethod, []string, error) {
if g.SSHPrivateKey != "" {
signer, err := ssh.ParsePrivateKey([]byte(g.SSHPrivateKey))
if err != nil {
Expand All @@ -45,7 +57,7 @@ func (g *ArtifactDriver) auth() (func(), transport.AuthMethod, []string, error)
if err != nil {
return nil, nil, nil, err
}
auth := &ssh2.PublicKeys{User: "git", Signer: signer}
auth := &ssh2.PublicKeys{User: sshUser, Signer: signer}
if g.InsecureIgnoreHostKey {
auth.HostKeyCallback = ssh.InsecureIgnoreHostKey()
}
Expand Down Expand Up @@ -100,7 +112,8 @@ func (g *ArtifactDriver) Save(string, *wfv1.Artifact) error {
}

func (g *ArtifactDriver) Load(inputArtifact *wfv1.Artifact, path string) error {
closer, auth, env, err := g.auth()
sshUser := GetUser(path)
closer, auth, env, err := g.auth(sshUser)
if err != nil {
return err
}
Expand Down
16 changes: 16 additions & 0 deletions workflow/artifacts/git/git_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,3 +98,19 @@ func TestGitArtifactDriverLoad_SSL(t *testing.T) {
})
}
}

func TestGetUser(t *testing.T) {
for _, tt := range []struct {
name string
url string
user string
}{
{"Username in SSH url", "gitaly@github.com:argoproj/argo-workflows.git", "gitaly"},
{"Default username", "https://github.com/argoproj/argo-workflows.git", "git"},
} {
t.Run(tt.name, func(t *testing.T) {
sshUser := GetUser(tt.url)
assert.Equal(t, sshUser, tt.user)
})
}
}

0 comments on commit 9b6c8b4

Please sign in to comment.