1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
|
package git
import (
"path/filepath"
"regexp"
"testing"
"github.com/stretchr/testify/require"
"gitlab.com/gitlab-org/gitaly/v16/internal/testhelper"
)
func TestBuildSSHInvocation(t *testing.T) {
ctx := testhelper.Context(t)
const tmpDirPattern = "=(\\S+)/(ssh-key|known-hosts)"
reTmpDir := regexp.MustCompile(tmpDirPattern)
for _, tc := range []struct {
desc string
sshKey string
knownHosts string
}{
{
desc: "no arguments",
},
{
desc: "ssh key given",
sshKey: "ssh-key-content",
},
{
desc: "known hosts given",
knownHosts: "known-hosts-content",
},
{
desc: "both given",
sshKey: "ssh-key-content",
knownHosts: "known-hosts-content",
},
} {
t.Run(tc.desc, func(t *testing.T) {
sshCommand, clean, err := BuildSSHInvocation(ctx, tc.sshKey, tc.knownHosts)
require.NoError(t, err)
defer clean()
var tmpDir string
if tc.sshKey != "" || tc.knownHosts != "" {
matches := reTmpDir.FindStringSubmatch(sshCommand)
require.Greater(t, len(matches), 1, "expected to find at least one file configured")
tmpDir = matches[1]
require.DirExists(t, tmpDir)
} else {
require.False(t, reTmpDir.MatchString(sshCommand))
}
sshKeyPath := filepath.Join(tmpDir, "ssh-key")
knownHostsPath := filepath.Join(tmpDir, "known-hosts")
expectedCommand := "ssh"
if tc.sshKey != "" {
content := testhelper.MustReadFile(t, sshKeyPath)
require.Equal(t, tc.sshKey, string(content))
expectedCommand += " -oIdentitiesOnly=yes -oIdentityFile=" + sshKeyPath
} else {
require.NoFileExists(t, sshKeyPath)
}
if tc.knownHosts != "" {
content := testhelper.MustReadFile(t, knownHostsPath)
require.Equal(t, tc.knownHosts, string(content))
expectedCommand += " -oStrictHostKeyChecking=yes -oCheckHostIP=no -oUserKnownHostsFile=" + knownHostsPath
} else {
require.NoFileExists(t, knownHostsPath)
}
require.Equal(t, expectedCommand, sshCommand)
clean()
require.NoDirExists(t, tmpDir)
})
}
}
|