manager_test.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. /*
  2. Copyright 2019 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package renewal
  14. import (
  15. "crypto/x509"
  16. "crypto/x509/pkix"
  17. "fmt"
  18. "net"
  19. "os"
  20. "path/filepath"
  21. "testing"
  22. "time"
  23. certutil "k8s.io/client-go/util/cert"
  24. kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm"
  25. certtestutil "k8s.io/kubernetes/cmd/kubeadm/app/util/certs"
  26. "k8s.io/kubernetes/cmd/kubeadm/app/util/pkiutil"
  27. testutil "k8s.io/kubernetes/cmd/kubeadm/test"
  28. )
  29. var (
  30. testCACertCfg = &pkiutil.CertConfig{
  31. Config: certutil.Config{CommonName: "kubernetes"},
  32. }
  33. testCACert, testCAKey, _ = pkiutil.NewCertificateAuthority(testCACertCfg)
  34. testCertCfg = &pkiutil.CertConfig{
  35. Config: certutil.Config{
  36. CommonName: "test-common-name",
  37. Organization: []string{"sig-cluster-lifecycle"},
  38. AltNames: certutil.AltNames{
  39. IPs: []net.IP{net.ParseIP("10.100.0.1")},
  40. DNSNames: []string{"test-domain.space"},
  41. },
  42. Usages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
  43. },
  44. }
  45. )
  46. func TestNewManager(t *testing.T) {
  47. tests := []struct {
  48. name string
  49. cfg *kubeadmapi.ClusterConfiguration
  50. expectedCertificates int
  51. }{
  52. {
  53. name: "cluster with local etcd",
  54. cfg: &kubeadmapi.ClusterConfiguration{},
  55. expectedCertificates: 10, //[admin apiserver apiserver-etcd-client apiserver-kubelet-client controller-manager etcd/healthcheck-client etcd/peer etcd/server front-proxy-client scheduler]
  56. },
  57. {
  58. name: "cluster with external etcd",
  59. cfg: &kubeadmapi.ClusterConfiguration{
  60. Etcd: kubeadmapi.Etcd{
  61. External: &kubeadmapi.ExternalEtcd{},
  62. },
  63. },
  64. expectedCertificates: 6, // [admin apiserver apiserver-kubelet-client controller-manager front-proxy-client scheduler]
  65. },
  66. }
  67. for _, test := range tests {
  68. t.Run(test.name, func(t *testing.T) {
  69. rm, err := NewManager(test.cfg, "")
  70. if err != nil {
  71. t.Fatalf("Failed to create the certificate renewal manager: %v", err)
  72. }
  73. if len(rm.Certificates()) != test.expectedCertificates {
  74. t.Errorf("Expected %d certificates, saw %d", test.expectedCertificates, len(rm.Certificates()))
  75. }
  76. })
  77. }
  78. }
  79. func TestRenewUsingLocalCA(t *testing.T) {
  80. dir := testutil.SetupTempDir(t)
  81. defer os.RemoveAll(dir)
  82. if err := pkiutil.WriteCertAndKey(dir, "ca", testCACert, testCAKey); err != nil {
  83. t.Fatalf("couldn't write out CA certificate to %s", dir)
  84. }
  85. cfg := &kubeadmapi.ClusterConfiguration{
  86. CertificatesDir: dir,
  87. }
  88. rm, err := NewManager(cfg, dir)
  89. if err != nil {
  90. t.Fatalf("Failed to create the certificate renewal manager: %v", err)
  91. }
  92. tests := []struct {
  93. name string
  94. certName string
  95. createCertFunc func() *x509.Certificate
  96. }{
  97. {
  98. name: "Certificate renewal for a PKI certificate",
  99. certName: "apiserver",
  100. createCertFunc: func() *x509.Certificate {
  101. return writeTestCertificate(t, dir, "apiserver", testCACert, testCAKey)
  102. },
  103. },
  104. {
  105. name: "Certificate renewal for a certificate embedded in a kubeconfig file",
  106. certName: "admin.conf",
  107. createCertFunc: func() *x509.Certificate {
  108. return writeTestKubeconfig(t, dir, "admin.conf", testCACert, testCAKey)
  109. },
  110. },
  111. }
  112. for _, test := range tests {
  113. t.Run(test.name, func(t *testing.T) {
  114. cert := test.createCertFunc()
  115. time.Sleep(1 * time.Second)
  116. _, err := rm.RenewUsingLocalCA(test.certName)
  117. if err != nil {
  118. t.Fatalf("error renewing certificate: %v", err)
  119. }
  120. newCert, err := rm.certificates[test.certName].readwriter.Read()
  121. if err != nil {
  122. t.Fatalf("error reading renewed certificate: %v", err)
  123. }
  124. if newCert.SerialNumber.Cmp(cert.SerialNumber) == 0 {
  125. t.Fatal("expected new certificate, but renewed certificate has same serial number")
  126. }
  127. if !newCert.NotAfter.After(cert.NotAfter) {
  128. t.Fatalf("expected new certificate with updated expiration, but renewed certificate has same NotAfter value: saw %s, expected greather than %s", newCert.NotAfter, cert.NotAfter)
  129. }
  130. certtestutil.AssertCertificateIsSignedByCa(t, newCert, testCACert)
  131. certtestutil.AssertCertificateHasClientAuthUsage(t, newCert)
  132. certtestutil.AssertCertificateHasOrganizations(t, newCert, testCertCfg.Organization...)
  133. certtestutil.AssertCertificateHasCommonName(t, newCert, testCertCfg.CommonName)
  134. certtestutil.AssertCertificateHasDNSNames(t, newCert, testCertCfg.AltNames.DNSNames...)
  135. certtestutil.AssertCertificateHasIPAddresses(t, newCert, testCertCfg.AltNames.IPs...)
  136. })
  137. }
  138. }
  139. func TestCreateRenewCSR(t *testing.T) {
  140. dir := testutil.SetupTempDir(t)
  141. defer os.RemoveAll(dir)
  142. outdir := filepath.Join(dir, "out")
  143. if err := os.MkdirAll(outdir, 0755); err != nil {
  144. t.Fatalf("couldn't create %s", outdir)
  145. }
  146. if err := pkiutil.WriteCertAndKey(dir, "ca", testCACert, testCAKey); err != nil {
  147. t.Fatalf("couldn't write out CA certificate to %s", dir)
  148. }
  149. cfg := &kubeadmapi.ClusterConfiguration{
  150. CertificatesDir: dir,
  151. }
  152. rm, err := NewManager(cfg, dir)
  153. if err != nil {
  154. t.Fatalf("Failed to create the certificate renewal manager: %v", err)
  155. }
  156. tests := []struct {
  157. name string
  158. certName string
  159. createCertFunc func() *x509.Certificate
  160. }{
  161. {
  162. name: "Creation of a CSR request for renewal of a PKI certificate",
  163. certName: "apiserver",
  164. createCertFunc: func() *x509.Certificate {
  165. return writeTestCertificate(t, dir, "apiserver", testCACert, testCAKey)
  166. },
  167. },
  168. {
  169. name: "Creation of a CSR request for renewal of a certificate embedded in a kubeconfig file",
  170. certName: "admin.conf",
  171. createCertFunc: func() *x509.Certificate {
  172. return writeTestKubeconfig(t, dir, "admin.conf", testCACert, testCAKey)
  173. },
  174. },
  175. }
  176. for _, test := range tests {
  177. t.Run(test.name, func(t *testing.T) {
  178. test.createCertFunc()
  179. time.Sleep(1 * time.Second)
  180. err := rm.CreateRenewCSR(test.certName, outdir)
  181. if err != nil {
  182. t.Fatalf("error renewing certificate: %v", err)
  183. }
  184. file := fmt.Sprintf("%s.key", test.certName)
  185. if _, err := os.Stat(filepath.Join(outdir, file)); os.IsNotExist(err) {
  186. t.Errorf("Expected file %s does not exist", file)
  187. }
  188. file = fmt.Sprintf("%s.csr", test.certName)
  189. if _, err := os.Stat(filepath.Join(outdir, file)); os.IsNotExist(err) {
  190. t.Errorf("Expected file %s does not exist", file)
  191. }
  192. })
  193. }
  194. }
  195. func TestCertToConfig(t *testing.T) {
  196. expectedConfig := &certutil.Config{
  197. CommonName: "test-common-name",
  198. Organization: []string{"sig-cluster-lifecycle"},
  199. AltNames: certutil.AltNames{
  200. IPs: []net.IP{net.ParseIP("10.100.0.1")},
  201. DNSNames: []string{"test-domain.space"},
  202. },
  203. Usages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
  204. }
  205. cert := &x509.Certificate{
  206. Subject: pkix.Name{
  207. CommonName: "test-common-name",
  208. Organization: []string{"sig-cluster-lifecycle"},
  209. },
  210. ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
  211. DNSNames: []string{"test-domain.space"},
  212. IPAddresses: []net.IP{net.ParseIP("10.100.0.1")},
  213. }
  214. cfg := certToConfig(cert)
  215. if cfg.CommonName != expectedConfig.CommonName {
  216. t.Errorf("expected common name %q, got %q", expectedConfig.CommonName, cfg.CommonName)
  217. }
  218. if len(cfg.Organization) != 1 || cfg.Organization[0] != expectedConfig.Organization[0] {
  219. t.Errorf("expected organization %v, got %v", expectedConfig.Organization, cfg.Organization)
  220. }
  221. if len(cfg.Usages) != 1 || cfg.Usages[0] != expectedConfig.Usages[0] {
  222. t.Errorf("expected ext key usage %v, got %v", expectedConfig.Usages, cfg.Usages)
  223. }
  224. if len(cfg.AltNames.IPs) != 1 || cfg.AltNames.IPs[0].String() != expectedConfig.AltNames.IPs[0].String() {
  225. t.Errorf("expected SAN IPs %v, got %v", expectedConfig.AltNames.IPs, cfg.AltNames.IPs)
  226. }
  227. if len(cfg.AltNames.DNSNames) != 1 || cfg.AltNames.DNSNames[0] != expectedConfig.AltNames.DNSNames[0] {
  228. t.Errorf("expected SAN DNSNames %v, got %v", expectedConfig.AltNames.DNSNames, cfg.AltNames.DNSNames)
  229. }
  230. }