GitOps for k8s
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

gpg.go 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package gpgtest
  2. import (
  3. "bytes"
  4. "io"
  5. "os/exec"
  6. "strings"
  7. "testing"
  8. "github.com/fluxcd/flux/cluster/kubernetes/testfiles"
  9. )
  10. // GPGKey creates a new, temporary GPG home directory and a public/private key
  11. // pair. It returns the GPG home directory, the ID of the created key, and a
  12. // cleanup function to be called after the caller is finished with this key.
  13. // Since GPG uses /dev/random, this may block while waiting for entropy to
  14. // become available.
  15. func GPGKey(t *testing.T) (string, string, func()) {
  16. newDir, cleanup := testfiles.TempDir(t)
  17. cmd := exec.Command("gpg", "--homedir", newDir, "--batch", "--gen-key")
  18. stdin, err := cmd.StdinPipe()
  19. if err != nil {
  20. cleanup()
  21. t.Fatal(err)
  22. }
  23. io.WriteString(stdin, "Key-Type: DSA\n")
  24. io.WriteString(stdin, "Key-Length: 1024\n")
  25. io.WriteString(stdin, "Key-Usage: sign\n")
  26. io.WriteString(stdin, "Name-Real: Flux\n")
  27. io.WriteString(stdin, "Name-Email: flux@weave.works\n")
  28. io.WriteString(stdin, "%no-protection\n")
  29. stdin.Close()
  30. if err := cmd.Run(); err != nil {
  31. cleanup()
  32. t.Fatal(err)
  33. }
  34. gpgCmd := exec.Command("gpg", "--homedir", newDir, "--list-keys", "--with-colons", "--with-fingerprint")
  35. grepCmd := exec.Command("grep", "^fpr")
  36. cutCmd := exec.Command("cut", "-d:", "-f10")
  37. grepIn, gpgOut := io.Pipe()
  38. cutIn, grepOut := io.Pipe()
  39. var cutOut bytes.Buffer
  40. gpgCmd.Stdout = gpgOut
  41. grepCmd.Stdin, grepCmd.Stdout = grepIn, grepOut
  42. cutCmd.Stdin, cutCmd.Stdout = cutIn, &cutOut
  43. gpgCmd.Start()
  44. grepCmd.Start()
  45. cutCmd.Start()
  46. if err := gpgCmd.Wait(); err != nil {
  47. cleanup()
  48. t.Fatal(err)
  49. }
  50. gpgOut.Close()
  51. if err := grepCmd.Wait(); err != nil {
  52. cleanup()
  53. t.Fatal(err)
  54. }
  55. grepOut.Close()
  56. if err := cutCmd.Wait(); err != nil {
  57. cleanup()
  58. t.Fatal(err)
  59. }
  60. fingerprint := strings.TrimSpace(cutOut.String())
  61. return newDir, fingerprint, cleanup
  62. }