60 lines
1.4 KiB
Go
60 lines
1.4 KiB
Go
package ssh
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"crypto/rsa"
|
|
"crypto/x509"
|
|
"encoding/pem"
|
|
"os"
|
|
"path/filepath"
|
|
"testing"
|
|
)
|
|
|
|
func TestAuthMethodsPreferAgentBeforeKeyFile(t *testing.T) {
|
|
keyFile := writePrivateKey(t)
|
|
methods, cleanup, err := authMethodsWithAgent("/tmp/ssh-agent.sock", nil, keyFile)
|
|
if err != nil {
|
|
t.Fatalf("authMethodsWithAgent() error = %v", err)
|
|
}
|
|
defer cleanup()
|
|
if got, want := len(methods), 2; got != want {
|
|
t.Fatalf("auth method count = %d, want %d", got, want)
|
|
}
|
|
}
|
|
|
|
func TestAuthMethodsLoadsKeyFile(t *testing.T) {
|
|
keyFile := writePrivateKey(t)
|
|
methods, cleanup, err := authMethodsWithAgent("", nil, keyFile)
|
|
if err != nil {
|
|
t.Fatalf("authMethodsWithAgent() error = %v", err)
|
|
}
|
|
defer cleanup()
|
|
if got, want := len(methods), 1; got != want {
|
|
t.Fatalf("auth method count = %d, want %d", got, want)
|
|
}
|
|
}
|
|
|
|
func TestAuthMethodsRejectsMissingAuth(t *testing.T) {
|
|
_, _, err := authMethodsWithAgent("", nil, "")
|
|
if err == nil {
|
|
t.Fatal("authMethodsWithAgent() error = nil, want error")
|
|
}
|
|
}
|
|
|
|
func writePrivateKey(t *testing.T) string {
|
|
t.Helper()
|
|
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
|
|
if err != nil {
|
|
t.Fatalf("generate key: %v", err)
|
|
}
|
|
data := pem.EncodeToMemory(&pem.Block{
|
|
Type: "RSA PRIVATE KEY",
|
|
Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
|
|
})
|
|
path := filepath.Join(t.TempDir(), "id_rsa")
|
|
if err := os.WriteFile(path, data, 0o600); err != nil {
|
|
t.Fatalf("write private key: %v", err)
|
|
}
|
|
return path
|
|
}
|