sshagentkms_test.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. package sshagentkms
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto"
  6. "crypto/ecdsa"
  7. "crypto/elliptic"
  8. "crypto/rand"
  9. "crypto/x509"
  10. "encoding/pem"
  11. "net"
  12. "os"
  13. "os/exec"
  14. "path/filepath"
  15. "reflect"
  16. "strconv"
  17. "strings"
  18. "testing"
  19. "github.com/smallstep/certificates/kms/apiv1"
  20. "golang.org/x/crypto/ssh"
  21. "golang.org/x/crypto/ssh/agent"
  22. "go.step.sm/crypto/pemutil"
  23. )
  24. // Some helpers with inspiration from crypto/ssh/agent/client_test.go
  25. // startOpenSSHAgent executes ssh-agent, and returns an Agent interface to it.
  26. func startOpenSSHAgent(t *testing.T) (client agent.Agent, socket string, cleanup func()) {
  27. /* Always test with OpenSSHAgent
  28. if testing.Short() {
  29. // ssh-agent is not always available, and the key
  30. // types supported vary by platform.
  31. t.Skip("skipping test due to -short")
  32. }
  33. */
  34. bin, err := exec.LookPath("ssh-agent")
  35. if err != nil {
  36. t.Skip("could not find ssh-agent")
  37. }
  38. cmd := exec.Command(bin, "-s")
  39. cmd.Env = []string{} // Do not let the user's environment influence ssh-agent behavior.
  40. cmd.Stderr = new(bytes.Buffer)
  41. out, err := cmd.Output()
  42. if err != nil {
  43. t.Fatalf("%s failed: %v\n%s", strings.Join(cmd.Args, " "), err, cmd.Stderr)
  44. }
  45. // Output looks like:
  46. //
  47. // SSH_AUTH_SOCK=/tmp/ssh-P65gpcqArqvH/agent.15541; export SSH_AUTH_SOCK;
  48. // SSH_AGENT_PID=15542; export SSH_AGENT_PID;
  49. // echo Agent pid 15542;
  50. fields := bytes.Split(out, []byte(";"))
  51. line := bytes.SplitN(fields[0], []byte("="), 2)
  52. line[0] = bytes.TrimLeft(line[0], "\n")
  53. if string(line[0]) != "SSH_AUTH_SOCK" {
  54. t.Fatalf("could not find key SSH_AUTH_SOCK in %q", fields[0])
  55. }
  56. socket = string(line[1])
  57. line = bytes.SplitN(fields[2], []byte("="), 2)
  58. line[0] = bytes.TrimLeft(line[0], "\n")
  59. if string(line[0]) != "SSH_AGENT_PID" {
  60. t.Fatalf("could not find key SSH_AGENT_PID in %q", fields[2])
  61. }
  62. pidStr := line[1]
  63. pid, err := strconv.Atoi(string(pidStr))
  64. if err != nil {
  65. t.Fatalf("Atoi(%q): %v", pidStr, err)
  66. }
  67. conn, err := net.Dial("unix", string(socket))
  68. if err != nil {
  69. t.Fatalf("net.Dial: %v", err)
  70. }
  71. ac := agent.NewClient(conn)
  72. return ac, socket, func() {
  73. proc, _ := os.FindProcess(pid)
  74. if proc != nil {
  75. proc.Kill()
  76. }
  77. conn.Close()
  78. os.RemoveAll(filepath.Dir(socket))
  79. }
  80. }
  81. func startAgent(t *testing.T, sshagent agent.Agent) (client agent.Agent, cleanup func()) {
  82. c1, c2, err := netPipe()
  83. if err != nil {
  84. t.Fatalf("netPipe: %v", err)
  85. }
  86. go agent.ServeAgent(sshagent, c2)
  87. return agent.NewClient(c1), func() {
  88. c1.Close()
  89. c2.Close()
  90. }
  91. }
  92. // startKeyringAgent uses Keyring to simulate a ssh-agent Server and returns a client.
  93. func startKeyringAgent(t *testing.T) (client agent.Agent, cleanup func()) {
  94. return startAgent(t, agent.NewKeyring())
  95. }
  96. type startTestAgentFunc func(t *testing.T, keysToAdd ...agent.AddedKey) (sshagent agent.Agent)
  97. func startTestOpenSSHAgent(t *testing.T, keysToAdd ...agent.AddedKey) (sshagent agent.Agent) {
  98. sshagent, _, cleanup := startOpenSSHAgent(t)
  99. for _, keyToAdd := range keysToAdd {
  100. err := sshagent.Add(keyToAdd)
  101. if err != nil {
  102. t.Fatalf("sshagent.add: %v", err)
  103. }
  104. }
  105. t.Cleanup(cleanup)
  106. //testAgentInterface(t, sshagent, key, cert, lifetimeSecs)
  107. return sshagent
  108. }
  109. func startTestKeyringAgent(t *testing.T, keysToAdd ...agent.AddedKey) (sshagent agent.Agent) {
  110. sshagent, cleanup := startKeyringAgent(t)
  111. for _, keyToAdd := range keysToAdd {
  112. err := sshagent.Add(keyToAdd)
  113. if err != nil {
  114. t.Fatalf("sshagent.add: %v", err)
  115. }
  116. }
  117. t.Cleanup(cleanup)
  118. //testAgentInterface(t, agent, key, cert, lifetimeSecs)
  119. return sshagent
  120. }
  121. // netPipe is analogous to net.Pipe, but it uses a real net.Conn, and
  122. // therefore is buffered (net.Pipe deadlocks if both sides start with
  123. // a write.)
  124. func netPipe() (net.Conn, net.Conn, error) {
  125. listener, err := netListener()
  126. if err != nil {
  127. return nil, nil, err
  128. }
  129. defer listener.Close()
  130. c1, err := net.Dial("tcp", listener.Addr().String())
  131. if err != nil {
  132. return nil, nil, err
  133. }
  134. c2, err := listener.Accept()
  135. if err != nil {
  136. c1.Close()
  137. return nil, nil, err
  138. }
  139. return c1, c2, nil
  140. }
  141. // netListener creates a localhost network listener.
  142. func netListener() (net.Listener, error) {
  143. listener, err := net.Listen("tcp", "127.0.0.1:0")
  144. if err != nil {
  145. listener, err = net.Listen("tcp", "[::1]:0")
  146. if err != nil {
  147. return nil, err
  148. }
  149. }
  150. return listener, nil
  151. }
  152. func TestNew(t *testing.T) {
  153. comment := "Key from OpenSSHAgent"
  154. // Ensure we don't "inherit" any SSH_AUTH_SOCK
  155. os.Unsetenv("SSH_AUTH_SOCK")
  156. sshagent, socket, cleanup := startOpenSSHAgent(t)
  157. os.Setenv("SSH_AUTH_SOCK", socket)
  158. t.Cleanup(func() {
  159. os.Unsetenv("SSH_AUTH_SOCK")
  160. cleanup()
  161. })
  162. // Test that we can't find any signers in the agent before we have loaded them
  163. t.Run("No keys with OpenSSHAgent", func(t *testing.T) {
  164. kms, err := New(context.Background(), apiv1.Options{})
  165. if kms == nil || err != nil {
  166. t.Errorf("New() = %v, %v", kms, err)
  167. }
  168. signer, err := kms.CreateSigner(&apiv1.CreateSignerRequest{SigningKey: "sshagentkms:" + comment})
  169. if err == nil || signer != nil {
  170. t.Errorf("SSHAgentKMS.CreateSigner() error = \"%v\", signer = \"%v\"", err, signer)
  171. }
  172. })
  173. // Load ssh test fixtures
  174. b, err := os.ReadFile("testdata/ssh")
  175. if err != nil {
  176. t.Fatal(err)
  177. }
  178. privateKey, err := ssh.ParseRawPrivateKey(b)
  179. if err != nil {
  180. t.Fatal(err)
  181. }
  182. // And add that key to the agent
  183. err = sshagent.Add(agent.AddedKey{PrivateKey: privateKey, Comment: comment})
  184. if err != nil {
  185. t.Fatalf("sshagent.add: %v", err)
  186. }
  187. // And test that we can find it when it's loaded
  188. t.Run("Keys with OpenSSHAgent", func(t *testing.T) {
  189. kms, err := New(context.Background(), apiv1.Options{})
  190. if kms == nil || err != nil {
  191. t.Errorf("New() = %v, %v", kms, err)
  192. }
  193. signer, err := kms.CreateSigner(&apiv1.CreateSignerRequest{SigningKey: "sshagentkms:" + comment})
  194. if err != nil || signer == nil {
  195. t.Errorf("SSHAgentKMS.CreateSigner() error = \"%v\", signer = \"%v\"", err, signer)
  196. }
  197. })
  198. }
  199. func TestNewFromAgent(t *testing.T) {
  200. type args struct {
  201. ctx context.Context
  202. opts apiv1.Options
  203. }
  204. tests := []struct {
  205. name string
  206. args args
  207. sshagentstarter startTestAgentFunc
  208. wantErr bool
  209. }{
  210. {"ok OpenSSHAgent", args{context.Background(), apiv1.Options{}}, startTestOpenSSHAgent, false},
  211. {"ok KeyringAgent", args{context.Background(), apiv1.Options{}}, startTestKeyringAgent, false},
  212. }
  213. for _, tt := range tests {
  214. t.Run(tt.name, func(t *testing.T) {
  215. got, err := NewFromAgent(tt.args.ctx, tt.args.opts, tt.sshagentstarter(t))
  216. if (err != nil) != tt.wantErr {
  217. t.Errorf("NewFromAgent() error = %v, wantErr %v", err, tt.wantErr)
  218. return
  219. }
  220. if got == nil {
  221. t.Errorf("NewFromAgent() = %v", got)
  222. }
  223. })
  224. }
  225. }
  226. func TestSSHAgentKMS_Close(t *testing.T) {
  227. tests := []struct {
  228. name string
  229. wantErr bool
  230. }{
  231. {"ok", false},
  232. }
  233. for _, tt := range tests {
  234. t.Run(tt.name, func(t *testing.T) {
  235. k := &SSHAgentKMS{}
  236. if err := k.Close(); (err != nil) != tt.wantErr {
  237. t.Errorf("SSHAgentKMS.Close() error = %v, wantErr %v", err, tt.wantErr)
  238. }
  239. })
  240. }
  241. }
  242. func TestSSHAgentKMS_CreateSigner(t *testing.T) {
  243. pk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  244. if err != nil {
  245. t.Fatal(err)
  246. }
  247. pemBlock, err := pemutil.Serialize(pk)
  248. if err != nil {
  249. t.Fatal(err)
  250. }
  251. pemBlockPassword, err := pemutil.Serialize(pk, pemutil.WithPassword([]byte("pass")))
  252. if err != nil {
  253. t.Fatal(err)
  254. }
  255. // Read and decode file using standard packages
  256. b, err := os.ReadFile("testdata/priv.pem")
  257. if err != nil {
  258. t.Fatal(err)
  259. }
  260. block, _ := pem.Decode(b)
  261. block.Bytes, err = x509.DecryptPEMBlock(block, []byte("pass")) //nolint
  262. if err != nil {
  263. t.Fatal(err)
  264. }
  265. pk2, err := x509.ParseECPrivateKey(block.Bytes)
  266. if err != nil {
  267. t.Fatal(err)
  268. }
  269. // Create a public PEM
  270. b, err = x509.MarshalPKIXPublicKey(pk.Public())
  271. if err != nil {
  272. t.Fatal(err)
  273. }
  274. pub := pem.EncodeToMemory(&pem.Block{
  275. Type: "PUBLIC KEY",
  276. Bytes: b,
  277. })
  278. // Load ssh test fixtures
  279. sshPubKeyStr, err := os.ReadFile("testdata/ssh.pub")
  280. if err != nil {
  281. t.Fatal(err)
  282. }
  283. _, comment, _, _, err := ssh.ParseAuthorizedKey(sshPubKeyStr)
  284. if err != nil {
  285. t.Fatal(err)
  286. }
  287. b, err = os.ReadFile("testdata/ssh")
  288. if err != nil {
  289. t.Fatal(err)
  290. }
  291. privateKey, err := ssh.ParseRawPrivateKey(b)
  292. if err != nil {
  293. t.Fatal(err)
  294. }
  295. sshPrivateKey, err := ssh.NewSignerFromKey(privateKey)
  296. if err != nil {
  297. t.Fatal(err)
  298. }
  299. wrappedSSHPrivateKey := NewWrappedSignerFromSSHSigner(sshPrivateKey)
  300. type args struct {
  301. req *apiv1.CreateSignerRequest
  302. }
  303. tests := []struct {
  304. name string
  305. args args
  306. want crypto.Signer
  307. wantErr bool
  308. }{
  309. {"signer", args{&apiv1.CreateSignerRequest{Signer: pk}}, pk, false},
  310. {"pem", args{&apiv1.CreateSignerRequest{SigningKeyPEM: pem.EncodeToMemory(pemBlock)}}, pk, false},
  311. {"pem password", args{&apiv1.CreateSignerRequest{SigningKeyPEM: pem.EncodeToMemory(pemBlockPassword), Password: []byte("pass")}}, pk, false},
  312. {"file", args{&apiv1.CreateSignerRequest{SigningKey: "testdata/priv.pem", Password: []byte("pass")}}, pk2, false},
  313. {"sshagent", args{&apiv1.CreateSignerRequest{SigningKey: "sshagentkms:" + comment}}, wrappedSSHPrivateKey, false},
  314. {"sshagent Nonexistant", args{&apiv1.CreateSignerRequest{SigningKey: "sshagentkms:Nonexistant"}}, nil, true},
  315. {"fail", args{&apiv1.CreateSignerRequest{}}, nil, true},
  316. {"fail bad pem", args{&apiv1.CreateSignerRequest{SigningKeyPEM: []byte("bad pem")}}, nil, true},
  317. {"fail bad password", args{&apiv1.CreateSignerRequest{SigningKey: "testdata/priv.pem", Password: []byte("bad-pass")}}, nil, true},
  318. {"fail not a signer", args{&apiv1.CreateSignerRequest{SigningKeyPEM: pub}}, nil, true},
  319. {"fail not a signer from file", args{&apiv1.CreateSignerRequest{SigningKey: "testdata/pub.pem"}}, nil, true},
  320. {"fail missing", args{&apiv1.CreateSignerRequest{SigningKey: "testdata/missing"}}, nil, true},
  321. }
  322. starters := []struct {
  323. name string
  324. starter startTestAgentFunc
  325. }{
  326. {"startTestOpenSSHAgent", startTestOpenSSHAgent},
  327. {"startTestKeyringAgent", startTestKeyringAgent},
  328. }
  329. for _, starter := range starters {
  330. k, err := NewFromAgent(context.Background(), apiv1.Options{}, starter.starter(t, agent.AddedKey{PrivateKey: privateKey, Comment: comment}))
  331. if err != nil {
  332. t.Fatal(err)
  333. }
  334. for _, tt := range tests {
  335. t.Run(starter.name+"/"+tt.name, func(t *testing.T) {
  336. got, err := k.CreateSigner(tt.args.req)
  337. if (err != nil) != tt.wantErr {
  338. t.Errorf("SSHAgentKMS.CreateSigner() error = %v, wantErr %v", err, tt.wantErr)
  339. return
  340. }
  341. // nolint:gocritic
  342. switch s := got.(type) {
  343. case *WrappedSSHSigner:
  344. gotPkS := s.Sshsigner.PublicKey().(*agent.Key).String() + "\n"
  345. wantPkS := string(sshPubKeyStr)
  346. if !reflect.DeepEqual(gotPkS, wantPkS) {
  347. t.Errorf("SSHAgentKMS.CreateSigner() = %T, want %T", gotPkS, wantPkS)
  348. t.Errorf("SSHAgentKMS.CreateSigner() = %v, want %v", gotPkS, wantPkS)
  349. }
  350. default:
  351. if !reflect.DeepEqual(got, tt.want) {
  352. t.Errorf("SSHAgentKMS.CreateSigner() = %T, want %T", got, tt.want)
  353. t.Errorf("SSHAgentKMS.CreateSigner() = %v, want %v", got, tt.want)
  354. }
  355. }
  356. })
  357. }
  358. }
  359. }
  360. /*
  361. func restoreGenerateKey() func() {
  362. oldGenerateKey := generateKey
  363. return func() {
  364. generateKey = oldGenerateKey
  365. }
  366. }
  367. */
  368. /*
  369. func TestSSHAgentKMS_CreateKey(t *testing.T) {
  370. fn := restoreGenerateKey()
  371. defer fn()
  372. p256, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  373. if err != nil {
  374. t.Fatal(err)
  375. }
  376. rsa2048, err := rsa.GenerateKey(rand.Reader, 2048)
  377. if err != nil {
  378. t.Fatal(err)
  379. }
  380. edpub, edpriv, err := ed25519.GenerateKey(rand.Reader)
  381. if err != nil {
  382. t.Fatal(err)
  383. }
  384. type args struct {
  385. req *apiv1.CreateKeyRequest
  386. }
  387. type params struct {
  388. kty string
  389. crv string
  390. size int
  391. }
  392. tests := []struct {
  393. name string
  394. args args
  395. generateKey func() (interface{}, interface{}, error)
  396. want *apiv1.CreateKeyResponse
  397. wantParams params
  398. wantErr bool
  399. }{
  400. {"p256", args{&apiv1.CreateKeyRequest{Name: "p256", SignatureAlgorithm: apiv1.ECDSAWithSHA256}}, func() (interface{}, interface{}, error) {
  401. return p256.Public(), p256, nil
  402. }, &apiv1.CreateKeyResponse{Name: "p256", PublicKey: p256.Public(), PrivateKey: p256, CreateSignerRequest: apiv1.CreateSignerRequest{Signer: p256}}, params{"EC", "P-256", 0}, false},
  403. {"rsa", args{&apiv1.CreateKeyRequest{Name: "rsa3072", SignatureAlgorithm: apiv1.SHA256WithRSA}}, func() (interface{}, interface{}, error) {
  404. return rsa2048.Public(), rsa2048, nil
  405. }, &apiv1.CreateKeyResponse{Name: "rsa3072", PublicKey: rsa2048.Public(), PrivateKey: rsa2048, CreateSignerRequest: apiv1.CreateSignerRequest{Signer: rsa2048}}, params{"RSA", "", 0}, false},
  406. {"rsa2048", args{&apiv1.CreateKeyRequest{Name: "rsa2048", SignatureAlgorithm: apiv1.SHA256WithRSA, Bits: 2048}}, func() (interface{}, interface{}, error) {
  407. return rsa2048.Public(), rsa2048, nil
  408. }, &apiv1.CreateKeyResponse{Name: "rsa2048", PublicKey: rsa2048.Public(), PrivateKey: rsa2048, CreateSignerRequest: apiv1.CreateSignerRequest{Signer: rsa2048}}, params{"RSA", "", 2048}, false},
  409. {"rsaPSS2048", args{&apiv1.CreateKeyRequest{Name: "rsa2048", SignatureAlgorithm: apiv1.SHA256WithRSAPSS, Bits: 2048}}, func() (interface{}, interface{}, error) {
  410. return rsa2048.Public(), rsa2048, nil
  411. }, &apiv1.CreateKeyResponse{Name: "rsa2048", PublicKey: rsa2048.Public(), PrivateKey: rsa2048, CreateSignerRequest: apiv1.CreateSignerRequest{Signer: rsa2048}}, params{"RSA", "", 2048}, false},
  412. {"ed25519", args{&apiv1.CreateKeyRequest{Name: "ed25519", SignatureAlgorithm: apiv1.PureEd25519}}, func() (interface{}, interface{}, error) {
  413. return edpub, edpriv, nil
  414. }, &apiv1.CreateKeyResponse{Name: "ed25519", PublicKey: edpub, PrivateKey: edpriv, CreateSignerRequest: apiv1.CreateSignerRequest{Signer: edpriv}}, params{"OKP", "Ed25519", 0}, false},
  415. {"default", args{&apiv1.CreateKeyRequest{Name: "default"}}, func() (interface{}, interface{}, error) {
  416. return p256.Public(), p256, nil
  417. }, &apiv1.CreateKeyResponse{Name: "default", PublicKey: p256.Public(), PrivateKey: p256, CreateSignerRequest: apiv1.CreateSignerRequest{Signer: p256}}, params{"EC", "P-256", 0}, false},
  418. {"fail algorithm", args{&apiv1.CreateKeyRequest{Name: "fail", SignatureAlgorithm: apiv1.SignatureAlgorithm(100)}}, func() (interface{}, interface{}, error) {
  419. return p256.Public(), p256, nil
  420. }, nil, params{}, true},
  421. {"fail generate key", args{&apiv1.CreateKeyRequest{Name: "fail", SignatureAlgorithm: apiv1.ECDSAWithSHA256}}, func() (interface{}, interface{}, error) {
  422. return nil, nil, fmt.Errorf("an error")
  423. }, nil, params{"EC", "P-256", 0}, true},
  424. {"fail no signer", args{&apiv1.CreateKeyRequest{Name: "fail", SignatureAlgorithm: apiv1.ECDSAWithSHA256}}, func() (interface{}, interface{}, error) {
  425. return 1, 2, nil
  426. }, nil, params{"EC", "P-256", 0}, true},
  427. }
  428. for _, tt := range tests {
  429. t.Run(tt.name, func(t *testing.T) {
  430. k := &SSHAgentKMS{}
  431. generateKey = func(kty, crv string, size int) (interface{}, interface{}, error) {
  432. if tt.wantParams.kty != kty {
  433. t.Errorf("GenerateKey() kty = %s, want %s", kty, tt.wantParams.kty)
  434. }
  435. if tt.wantParams.crv != crv {
  436. t.Errorf("GenerateKey() crv = %s, want %s", crv, tt.wantParams.crv)
  437. }
  438. if tt.wantParams.size != size {
  439. t.Errorf("GenerateKey() size = %d, want %d", size, tt.wantParams.size)
  440. }
  441. return tt.generateKey()
  442. }
  443. got, err := k.CreateKey(tt.args.req)
  444. if (err != nil) != tt.wantErr {
  445. t.Errorf("SSHAgentKMS.CreateKey() error = %v, wantErr %v", err, tt.wantErr)
  446. return
  447. }
  448. if !reflect.DeepEqual(got, tt.want) {
  449. t.Errorf("SSHAgentKMS.CreateKey() = %v, want %v", got, tt.want)
  450. }
  451. })
  452. }
  453. }
  454. */
  455. func TestSSHAgentKMS_GetPublicKey(t *testing.T) {
  456. b, err := os.ReadFile("testdata/pub.pem")
  457. if err != nil {
  458. t.Fatal(err)
  459. }
  460. block, _ := pem.Decode(b)
  461. pub, err := x509.ParsePKIXPublicKey(block.Bytes)
  462. if err != nil {
  463. t.Fatal(err)
  464. }
  465. // Load ssh test fixtures
  466. b, err = os.ReadFile("testdata/ssh.pub")
  467. if err != nil {
  468. t.Fatal(err)
  469. }
  470. sshPubKey, comment, _, _, err := ssh.ParseAuthorizedKey(b)
  471. if err != nil {
  472. t.Fatal(err)
  473. }
  474. b, err = os.ReadFile("testdata/ssh")
  475. if err != nil {
  476. t.Fatal(err)
  477. }
  478. // crypto.PrivateKey
  479. sshPrivateKey, err := ssh.ParseRawPrivateKey(b)
  480. if err != nil {
  481. t.Fatal(err)
  482. }
  483. type args struct {
  484. req *apiv1.GetPublicKeyRequest
  485. }
  486. tests := []struct {
  487. name string
  488. args args
  489. want crypto.PublicKey
  490. wantErr bool
  491. }{
  492. {"key", args{&apiv1.GetPublicKeyRequest{Name: "testdata/pub.pem"}}, pub, false},
  493. {"cert", args{&apiv1.GetPublicKeyRequest{Name: "testdata/cert.crt"}}, pub, false},
  494. {"sshagent", args{&apiv1.GetPublicKeyRequest{Name: "sshagentkms:" + comment}}, sshPubKey, false},
  495. {"sshagent Nonexistant", args{&apiv1.GetPublicKeyRequest{Name: "sshagentkms:Nonexistant"}}, nil, true},
  496. {"fail not exists", args{&apiv1.GetPublicKeyRequest{Name: "testdata/missing"}}, nil, true},
  497. {"fail type", args{&apiv1.GetPublicKeyRequest{Name: "testdata/cert.key"}}, nil, true},
  498. }
  499. starters := []struct {
  500. name string
  501. starter startTestAgentFunc
  502. }{
  503. {"startTestOpenSSHAgent", startTestOpenSSHAgent},
  504. {"startTestKeyringAgent", startTestKeyringAgent},
  505. }
  506. for _, starter := range starters {
  507. k, err := NewFromAgent(context.Background(), apiv1.Options{}, starter.starter(t, agent.AddedKey{PrivateKey: sshPrivateKey, Comment: comment}))
  508. if err != nil {
  509. t.Fatal(err)
  510. }
  511. for _, tt := range tests {
  512. t.Run(starter.name+"/"+tt.name, func(t *testing.T) {
  513. got, err := k.GetPublicKey(tt.args.req)
  514. if (err != nil) != tt.wantErr {
  515. t.Errorf("SSHAgentKMS.GetPublicKey() error = %v, wantErr %v", err, tt.wantErr)
  516. return
  517. }
  518. // nolint:gocritic
  519. switch tt.want.(type) {
  520. case ssh.PublicKey:
  521. // If we want a ssh.PublicKey, protote got to a
  522. got, err = ssh.NewPublicKey(got)
  523. if err != nil {
  524. t.Fatal(err)
  525. }
  526. }
  527. if !reflect.DeepEqual(got, tt.want) {
  528. t.Errorf("SSHAgentKMS.GetPublicKey() = %T, want %T", got, tt.want)
  529. t.Errorf("SSHAgentKMS.GetPublicKey() = %v, want %v", got, tt.want)
  530. }
  531. })
  532. }
  533. }
  534. }
  535. func TestSSHAgentKMS_CreateKey(t *testing.T) {
  536. starters := []struct {
  537. name string
  538. starter startTestAgentFunc
  539. }{
  540. {"startTestOpenSSHAgent", startTestOpenSSHAgent},
  541. {"startTestKeyringAgent", startTestKeyringAgent},
  542. }
  543. for _, starter := range starters {
  544. k, err := NewFromAgent(context.Background(), apiv1.Options{}, starter.starter(t))
  545. if err != nil {
  546. t.Fatal(err)
  547. }
  548. t.Run(starter.name+"/CreateKey", func(t *testing.T) {
  549. got, err := k.CreateKey(&apiv1.CreateKeyRequest{
  550. Name: "sshagentkms:0",
  551. SignatureAlgorithm: apiv1.ECDSAWithSHA256,
  552. })
  553. if got != nil {
  554. t.Error("SSHAgentKMS.CreateKey() shoudn't return a value")
  555. }
  556. if err == nil {
  557. t.Error("SSHAgentKMS.CreateKey() didn't return a value")
  558. }
  559. })
  560. }
  561. }