helm_test.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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. "github.com/smallstep/linkedca"
  15. "go.step.sm/crypto/jose"
  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-acme-and-duplicate-provisioner-name": func(t *testing.T) test {
  78. return test{
  79. pki: preparePKI(t, WithProvisioner("acme"), WithACME()),
  80. testFile: "testdata/helm/with-acme-and-duplicate-provisioner-name.yml",
  81. wantErr: false,
  82. }
  83. },
  84. "ok/with-admin": func(t *testing.T) test {
  85. return test{
  86. pki: preparePKI(t, WithAdmin()),
  87. testFile: "testdata/helm/with-admin.yml",
  88. wantErr: false,
  89. }
  90. },
  91. "ok/with-ssh": func(t *testing.T) test {
  92. return test{
  93. pki: preparePKI(t, WithSSH()),
  94. testFile: "testdata/helm/with-ssh.yml",
  95. wantErr: false,
  96. }
  97. },
  98. "ok/with-ssh-and-duplicate-provisioner-name": func(t *testing.T) test {
  99. return test{
  100. pki: preparePKI(t, WithProvisioner("sshpop"), WithSSH()),
  101. testFile: "testdata/helm/with-ssh-and-duplicate-provisioner-name.yml",
  102. wantErr: false,
  103. }
  104. },
  105. "ok/with-ssh-and-acme": func(t *testing.T) test {
  106. return test{
  107. pki: preparePKI(t, WithSSH(), WithACME()),
  108. testFile: "testdata/helm/with-ssh-and-acme.yml",
  109. wantErr: false,
  110. }
  111. },
  112. "fail/authority.ProvisionerToCertificates": func(t *testing.T) test {
  113. pki := preparePKI(t)
  114. pki.Authority.Provisioners = append(pki.Authority.Provisioners,
  115. &linkedca.Provisioner{
  116. Type: linkedca.Provisioner_JWK,
  117. Name: "Broken JWK",
  118. Details: nil,
  119. },
  120. )
  121. return test{
  122. pki: pki,
  123. wantErr: true,
  124. }
  125. },
  126. }
  127. for name, run := range tests {
  128. tc := run(t)
  129. t.Run(name, func(t *testing.T) {
  130. w := &bytes.Buffer{}
  131. if err := tc.pki.WriteHelmTemplate(w); (err != nil) != tc.wantErr {
  132. t.Errorf("PKI.WriteHelmTemplate() error = %v, wantErr %v", err, tc.wantErr)
  133. return
  134. }
  135. if tc.wantErr {
  136. // don't compare output if an error was expected on output
  137. return
  138. }
  139. wantBytes, err := os.ReadFile(tc.testFile)
  140. assert.NoError(t, err)
  141. if diff := cmp.Diff(wantBytes, w.Bytes()); diff != "" {
  142. t.Logf("Generated Helm template did not match reference %q\n", tc.testFile)
  143. t.Errorf("Diff follows:\n%s\n", diff)
  144. t.Errorf("Full output:\n%s\n", w.Bytes())
  145. }
  146. })
  147. }
  148. }
  149. // setKeyPair sets a predefined JWK and a default JWK provisioner.
  150. func setKeyPair(t *testing.T, p *PKI) {
  151. t.Helper()
  152. var err error
  153. 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"}`))
  154. if err != nil {
  155. t.Fatal(err)
  156. }
  157. p.ottPrivateKey, err = jose.ParseEncrypted("eyJhbGciOiJQQkVTMi1IUzI1NitBMTI4S1ciLCJjdHkiOiJqd2sranNvbiIsImVuYyI6IkEyNTZHQ00iLCJwMmMiOjEwMDAwMCwicDJzIjoiZjVvdGVRS2hvOXl4MmQtSGlMZi05QSJ9.eYA6tt3fNuUpoxKWDT7P0Lbn2juxhEbTxEnwEMbjlYLLQ3sxL-dYTA.ven-FhmdjlC9itH0.a2jRTarN9vPd6F_mWnNBlOn6KbfMjCApmci2t65XbAsLzYFzhI_79Ykm5ueMYTupWLTjBJctl-g51ZHmsSB55pStbpoyyLNAsUX2E1fTmHe-Ni8bRrspwLv15FoN1Xo1g0mpR-ufWIFxOsW-QIfnMmMIIkygVuHFXmg2tFpzTNNG5aS29K3dN2nyk0WJrdIq79hZSTqVkkBU25Yu3A46sgjcM86XcIJJ2XUEih_KWEa6T1YrkixGu96pebjVqbO0R6dbDckfPF7FqNnwPHVtb1ACFpEYoOJVIbUCMaARBpWsxYhjJZlEM__XA46l8snFQDkNY3CdN0p1_gF3ckA.JLmq9nmu1h9oUi1S8ZxYjA")
  158. if err != nil {
  159. t.Fatal(err)
  160. }
  161. var claims *linkedca.Claims
  162. if p.options.enableSSH {
  163. claims = &linkedca.Claims{
  164. Ssh: &linkedca.SSHClaims{
  165. Enabled: true,
  166. },
  167. }
  168. }
  169. publicKey, err := json.Marshal(p.ottPublicKey)
  170. if err != nil {
  171. t.Fatal(err)
  172. }
  173. encryptedKey, err := p.ottPrivateKey.CompactSerialize()
  174. if err != nil {
  175. t.Fatal(err)
  176. }
  177. p.Authority.Provisioners = append(p.Authority.Provisioners, &linkedca.Provisioner{
  178. Type: linkedca.Provisioner_JWK,
  179. Name: p.options.provisioner,
  180. Claims: claims,
  181. Details: &linkedca.ProvisionerDetails{
  182. Data: &linkedca.ProvisionerDetails_JWK{
  183. JWK: &linkedca.JWKProvisioner{
  184. PublicKey: publicKey,
  185. EncryptedPrivateKey: []byte(encryptedKey),
  186. },
  187. },
  188. },
  189. })
  190. }
  191. // setCertificates sets some static, gibberish intermediate and root CA certificate and key bytes.
  192. func setCertificates(_ *testing.T, p *PKI) {
  193. raw := []byte("these are just some fake root CA cert bytes")
  194. p.Files[p.Root[0]] = encodeCertificate(&x509.Certificate{Raw: raw})
  195. p.Files[p.RootKey[0]] = pem.EncodeToMemory(&pem.Block{
  196. Type: "EC PRIVATE KEY",
  197. Bytes: []byte("these are just some fake root CA key bytes"),
  198. })
  199. p.Files[p.Intermediate] = encodeCertificate(&x509.Certificate{Raw: []byte("these are just some fake intermediate CA cert bytes")})
  200. p.Files[p.IntermediateKey] = pem.EncodeToMemory(&pem.Block{
  201. Type: "EC PRIVATE KEY",
  202. Bytes: []byte("these are just some fake intermediate CA key bytes"),
  203. })
  204. sum := sha256.Sum256(raw)
  205. p.Defaults.Fingerprint = strings.ToLower(hex.EncodeToString(sum[:]))
  206. }
  207. // setSSHSigningKeys sets some static, gibberish ssh user and host CA certificate and key bytes.
  208. func setSSHSigningKeys(_ *testing.T, p *PKI) {
  209. if !p.options.enableSSH {
  210. return
  211. }
  212. p.Files[p.Ssh.HostKey] = pem.EncodeToMemory(&pem.Block{
  213. Type: "EC PRIVATE KEY",
  214. Bytes: []byte("fake ssh host key bytes"),
  215. })
  216. p.Files[p.Ssh.HostPublicKey] = []byte("ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBJ0IdS5sZm6KITBMZLEJD6b5ROVraYHcAOr3feFel8r1Wp4DRPR1oU0W00J/zjNBRBbANlJoYN4x/8WNNVZ49Ms=")
  217. p.Files[p.Ssh.UserKey] = pem.EncodeToMemory(&pem.Block{
  218. Type: "EC PRIVATE KEY",
  219. Bytes: []byte("fake ssh user key bytes"),
  220. })
  221. p.Files[p.Ssh.UserPublicKey] = []byte("ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBEWA1qUxaGwVNErsvEOGe2d6TvLMF+aiVpuOiIEvpMJ3JeJmecLQctjWqeIbpSvy6/gRa7c82Ge5rLlapYmOChs=")
  222. }