helm_test.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. package pki
  2. import (
  3. "bytes"
  4. "crypto/sha256"
  5. "crypto/x509"
  6. "encoding/hex"
  7. "encoding/json"
  8. "encoding/pem"
  9. "os"
  10. "strings"
  11. "testing"
  12. "github.com/google/go-cmp/cmp"
  13. "github.com/stretchr/testify/assert"
  14. "go.step.sm/crypto/jose"
  15. "go.step.sm/linkedca"
  16. "github.com/smallstep/certificates/cas/apiv1"
  17. )
  18. func TestPKI_WriteHelmTemplate(t *testing.T) {
  19. var preparePKI = func(t *testing.T, opts ...Option) *PKI {
  20. o := apiv1.Options{
  21. Type: "softcas",
  22. IsCreator: true,
  23. }
  24. // Add default WithHelm option
  25. opts = append(opts, WithHelm())
  26. // TODO(hs): invoking `New` doesn't perform all operations that are executed
  27. // when `ca init --helm` is executed. Ideally this logic should be handled
  28. // in one place and probably inside of the PKI initialization. For testing
  29. // purposes the missing operations to fill a Helm template fully are faked
  30. // by `setKeyPair`, `setCertificates` and `setSSHSigningKeys`
  31. p, err := New(o, opts...)
  32. assert.NoError(t, err)
  33. // setKeyPair sets a predefined JWK and a default JWK provisioner. This is one
  34. // of the things performed in the `ca init` code that's not part of `New`, but
  35. // performed after that in p.GenerateKeyPairs`. We're currently using the same
  36. // JWK for every test to keep test variance small: we're not testing JWK generation
  37. // here after all. It's a bit dangerous to redefine the function here, but it's
  38. // the simplest way to make this fully testable without refactoring the init now.
  39. // The password for the predefined encrypted key is \x01\x03\x03\x07.
  40. setKeyPair(t, p)
  41. // setCertificates sets some static intermediate and root CA certificate bytes. It
  42. // replaces the logic executed in `p.GenerateRootCertificate`, `p.WriteRootCertificate`,
  43. // and `p.GenerateIntermediateCertificate`.
  44. setCertificates(t, p)
  45. // setSSHSigningKeys sets predefined SSH user and host certificate and key bytes.
  46. // This replaces the logic in `p.GenerateSSHSigningKeys`
  47. setSSHSigningKeys(t, p)
  48. return p
  49. }
  50. type test struct {
  51. pki *PKI
  52. testFile string
  53. wantErr bool
  54. }
  55. var tests = map[string]func(t *testing.T) test{
  56. "ok/simple": func(t *testing.T) test {
  57. return test{
  58. pki: preparePKI(t),
  59. testFile: "testdata/helm/simple.yml",
  60. wantErr: false,
  61. }
  62. },
  63. "ok/with-provisioner": func(t *testing.T) test {
  64. return test{
  65. pki: preparePKI(t, WithProvisioner("a-provisioner")),
  66. testFile: "testdata/helm/with-provisioner.yml",
  67. wantErr: false,
  68. }
  69. },
  70. "ok/with-acme": func(t *testing.T) test {
  71. return test{
  72. pki: preparePKI(t, WithACME()),
  73. testFile: "testdata/helm/with-acme.yml",
  74. wantErr: false,
  75. }
  76. },
  77. "ok/with-admin": func(t *testing.T) test {
  78. return test{
  79. pki: preparePKI(t, WithAdmin()),
  80. testFile: "testdata/helm/with-admin.yml",
  81. wantErr: false,
  82. }
  83. },
  84. "ok/with-ssh": func(t *testing.T) test {
  85. return test{
  86. pki: preparePKI(t, WithSSH()),
  87. testFile: "testdata/helm/with-ssh.yml",
  88. wantErr: false,
  89. }
  90. },
  91. "ok/with-ssh-and-acme": func(t *testing.T) test {
  92. return test{
  93. pki: preparePKI(t, WithSSH(), WithACME()),
  94. testFile: "testdata/helm/with-ssh-and-acme.yml",
  95. wantErr: false,
  96. }
  97. },
  98. "fail/authority.ProvisionerToCertificates": func(t *testing.T) test {
  99. pki := preparePKI(t)
  100. pki.Authority.Provisioners = append(pki.Authority.Provisioners,
  101. &linkedca.Provisioner{
  102. Type: linkedca.Provisioner_JWK,
  103. Name: "Broken JWK",
  104. Details: nil,
  105. },
  106. )
  107. return test{
  108. pki: pki,
  109. wantErr: true,
  110. }
  111. },
  112. }
  113. for name, run := range tests {
  114. tc := run(t)
  115. t.Run(name, func(t *testing.T) {
  116. w := &bytes.Buffer{}
  117. if err := tc.pki.WriteHelmTemplate(w); (err != nil) != tc.wantErr {
  118. t.Errorf("PKI.WriteHelmTemplate() error = %v, wantErr %v", err, tc.wantErr)
  119. return
  120. }
  121. if tc.wantErr {
  122. // don't compare output if an error was expected on output
  123. return
  124. }
  125. wantBytes, err := os.ReadFile(tc.testFile)
  126. assert.NoError(t, err)
  127. if diff := cmp.Diff(wantBytes, w.Bytes()); diff != "" {
  128. t.Logf("Generated Helm template did not match reference %q\n", tc.testFile)
  129. t.Errorf("Diff follows:\n%s\n", diff)
  130. t.Errorf("Full output:\n%s\n", w.Bytes())
  131. }
  132. })
  133. }
  134. }
  135. // setKeyPair sets a predefined JWK and a default JWK provisioner.
  136. func setKeyPair(t *testing.T, p *PKI) {
  137. t.Helper()
  138. var err error
  139. p.ottPublicKey, err = jose.ParseKey([]byte(`{"use":"sig","kty":"EC","kid":"zsUmysmDVoGJ71YoPHyZ-68tNihDaDaO5Mu7xX3M-_I","crv":"P-256","alg":"ES256","x":"Pqnua4CzqKz6ua41J3yeWZ1sRkGt0UlCkbHv8H2DGuY","y":"UhoZ_2ItDen9KQTcjay-ph-SBXH0mwqhHyvrrqIFDOI"}`))
  140. if err != nil {
  141. t.Fatal(err)
  142. }
  143. p.ottPrivateKey, err = jose.ParseEncrypted("eyJhbGciOiJQQkVTMi1IUzI1NitBMTI4S1ciLCJjdHkiOiJqd2sranNvbiIsImVuYyI6IkEyNTZHQ00iLCJwMmMiOjEwMDAwMCwicDJzIjoiZjVvdGVRS2hvOXl4MmQtSGlMZi05QSJ9.eYA6tt3fNuUpoxKWDT7P0Lbn2juxhEbTxEnwEMbjlYLLQ3sxL-dYTA.ven-FhmdjlC9itH0.a2jRTarN9vPd6F_mWnNBlOn6KbfMjCApmci2t65XbAsLzYFzhI_79Ykm5ueMYTupWLTjBJctl-g51ZHmsSB55pStbpoyyLNAsUX2E1fTmHe-Ni8bRrspwLv15FoN1Xo1g0mpR-ufWIFxOsW-QIfnMmMIIkygVuHFXmg2tFpzTNNG5aS29K3dN2nyk0WJrdIq79hZSTqVkkBU25Yu3A46sgjcM86XcIJJ2XUEih_KWEa6T1YrkixGu96pebjVqbO0R6dbDckfPF7FqNnwPHVtb1ACFpEYoOJVIbUCMaARBpWsxYhjJZlEM__XA46l8snFQDkNY3CdN0p1_gF3ckA.JLmq9nmu1h9oUi1S8ZxYjA")
  144. if err != nil {
  145. t.Fatal(err)
  146. }
  147. var claims *linkedca.Claims
  148. if p.options.enableSSH {
  149. claims = &linkedca.Claims{
  150. Ssh: &linkedca.SSHClaims{
  151. Enabled: true,
  152. },
  153. }
  154. }
  155. publicKey, err := json.Marshal(p.ottPublicKey)
  156. if err != nil {
  157. t.Fatal(err)
  158. }
  159. encryptedKey, err := p.ottPrivateKey.CompactSerialize()
  160. if err != nil {
  161. t.Fatal(err)
  162. }
  163. p.Authority.Provisioners = append(p.Authority.Provisioners, &linkedca.Provisioner{
  164. Type: linkedca.Provisioner_JWK,
  165. Name: p.options.provisioner,
  166. Claims: claims,
  167. Details: &linkedca.ProvisionerDetails{
  168. Data: &linkedca.ProvisionerDetails_JWK{
  169. JWK: &linkedca.JWKProvisioner{
  170. PublicKey: publicKey,
  171. EncryptedPrivateKey: []byte(encryptedKey),
  172. },
  173. },
  174. },
  175. })
  176. }
  177. // setCertificates sets some static, gibberish intermediate and root CA certificate and key bytes.
  178. func setCertificates(_ *testing.T, p *PKI) {
  179. raw := []byte("these are just some fake root CA cert bytes")
  180. p.Files[p.Root[0]] = encodeCertificate(&x509.Certificate{Raw: raw})
  181. p.Files[p.RootKey[0]] = pem.EncodeToMemory(&pem.Block{
  182. Type: "EC PRIVATE KEY",
  183. Bytes: []byte("these are just some fake root CA key bytes"),
  184. })
  185. p.Files[p.Intermediate] = encodeCertificate(&x509.Certificate{Raw: []byte("these are just some fake intermediate CA cert bytes")})
  186. p.Files[p.IntermediateKey] = pem.EncodeToMemory(&pem.Block{
  187. Type: "EC PRIVATE KEY",
  188. Bytes: []byte("these are just some fake intermediate CA key bytes"),
  189. })
  190. sum := sha256.Sum256(raw)
  191. p.Defaults.Fingerprint = strings.ToLower(hex.EncodeToString(sum[:]))
  192. }
  193. // setSSHSigningKeys sets some static, gibberish ssh user and host CA certificate and key bytes.
  194. func setSSHSigningKeys(_ *testing.T, p *PKI) {
  195. if !p.options.enableSSH {
  196. return
  197. }
  198. p.Files[p.Ssh.HostKey] = pem.EncodeToMemory(&pem.Block{
  199. Type: "EC PRIVATE KEY",
  200. Bytes: []byte("fake ssh host key bytes"),
  201. })
  202. p.Files[p.Ssh.HostPublicKey] = []byte("ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBJ0IdS5sZm6KITBMZLEJD6b5ROVraYHcAOr3feFel8r1Wp4DRPR1oU0W00J/zjNBRBbANlJoYN4x/8WNNVZ49Ms=")
  203. p.Files[p.Ssh.UserKey] = pem.EncodeToMemory(&pem.Block{
  204. Type: "EC PRIVATE KEY",
  205. Bytes: []byte("fake ssh user key bytes"),
  206. })
  207. p.Files[p.Ssh.UserPublicKey] = []byte("ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBEWA1qUxaGwVNErsvEOGe2d6TvLMF+aiVpuOiIEvpMJ3JeJmecLQctjWqeIbpSvy6/gRa7c82Ge5rLlapYmOChs=")
  208. }