/
http01.go
504 lines (445 loc) · 19 KB
/
http01.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
/*
Copyright 2020 The cert-manager Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package certificate
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"strings"
"time"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
corev1 "k8s.io/api/core/v1"
networkingv1 "k8s.io/api/networking/v1"
networkingv1beta1 "k8s.io/api/networking/v1beta1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/util/retry"
"k8s.io/utils/pointer"
cmacme "github.com/jetstack/cert-manager/pkg/apis/acme/v1"
v1 "github.com/jetstack/cert-manager/pkg/apis/certmanager/v1"
cmmeta "github.com/jetstack/cert-manager/pkg/apis/meta/v1"
"github.com/jetstack/cert-manager/test/e2e/framework"
"github.com/jetstack/cert-manager/test/e2e/framework/helper/featureset"
"github.com/jetstack/cert-manager/test/e2e/framework/helper/validation"
"github.com/jetstack/cert-manager/test/e2e/framework/log"
. "github.com/jetstack/cert-manager/test/e2e/framework/matcher"
"github.com/jetstack/cert-manager/test/e2e/util"
e2eutil "github.com/jetstack/cert-manager/test/e2e/util"
"github.com/jetstack/cert-manager/test/unit/gen"
)
var _ = framework.CertManagerDescribe("ACME Certificate (HTTP01)", func() {
f := framework.NewDefaultFramework("create-acme-certificate-http01")
var acmeIngressDomain string
issuerName := "test-acme-issuer"
certificateName := "test-acme-certificate"
certificateSecretName := "test-acme-certificate"
// fixedIngressName is the name of an ingress resource that is configured
// with a challenge solve.
// To utilise this solver, add the 'testing.cert-manager.io/fixed-ingress: "true"' label.
fixedIngressName := "testingress"
// ACME Issuer does not return a ca.crt. See:
// https://github.com/jetstack/cert-manager/issues/1571
unsupportedFeatures := featureset.NewFeatureSet(featureset.SaveCAToSecret)
validations := validation.CertificateSetForUnsupportedFeatureSet(unsupportedFeatures)
BeforeEach(func() {
solvers := []cmacme.ACMEChallengeSolver{
{
HTTP01: &cmacme.ACMEChallengeSolverHTTP01{
Ingress: &cmacme.ACMEChallengeSolverHTTP01Ingress{
Class: &f.Config.Addons.IngressController.IngressClass,
},
},
},
{
Selector: &cmacme.CertificateDNSNameSelector{
MatchLabels: map[string]string{
"testing.cert-manager.io/fixed-ingress": "true",
},
},
HTTP01: &cmacme.ACMEChallengeSolverHTTP01{
Ingress: &cmacme.ACMEChallengeSolverHTTP01Ingress{
Name: fixedIngressName,
},
},
},
}
acmeIssuer := gen.Issuer(issuerName,
gen.SetIssuerNamespace(f.Namespace.Name),
gen.SetIssuerACMEEmail(f.Config.Addons.ACMEServer.TestingACMEEmail),
gen.SetIssuerACMEURL(f.Config.Addons.ACMEServer.URL),
gen.SetIssuerACMEPrivKeyRef(f.Config.Addons.ACMEServer.TestingACMEPrivateKey),
gen.SetIssuerACMESkipTLSVerify(true),
gen.SetIssuerACMESolvers(solvers))
By("Creating an Issuer")
_, err := f.CertManagerClientSet.CertmanagerV1().Issuers(f.Namespace.Name).Create(context.TODO(), acmeIssuer, metav1.CreateOptions{})
Expect(err).NotTo(HaveOccurred())
By("Waiting for Issuer to become Ready")
err = util.WaitForIssuerCondition(f.CertManagerClientSet.CertmanagerV1().Issuers(f.Namespace.Name),
issuerName,
v1.IssuerCondition{
Type: v1.IssuerConditionReady,
Status: cmmeta.ConditionTrue,
})
Expect(err).NotTo(HaveOccurred())
By("Verifying the ACME account URI is set")
err = util.WaitForIssuerStatusFunc(f.CertManagerClientSet.CertmanagerV1().Issuers(f.Namespace.Name),
issuerName,
func(i *v1.Issuer) (bool, error) {
if i.GetStatus().ACMEStatus().URI == "" {
return false, nil
}
return true, nil
})
Expect(err).NotTo(HaveOccurred())
By("Verifying ACME account private key exists")
secret, err := f.KubeClientSet.CoreV1().Secrets(f.Namespace.Name).Get(context.TODO(), f.Config.Addons.ACMEServer.TestingACMEPrivateKey, metav1.GetOptions{})
Expect(err).NotTo(HaveOccurred())
if len(secret.Data) != 1 {
Fail("Expected 1 key in ACME account private key secret, but there was %d", len(secret.Data))
}
})
JustBeforeEach(func() {
acmeIngressDomain = e2eutil.RandomSubdomain(f.Config.Addons.IngressController.Domain)
})
AfterEach(func() {
By("Cleaning up")
f.CertManagerClientSet.CertmanagerV1().Issuers(f.Namespace.Name).Delete(context.TODO(), issuerName, metav1.DeleteOptions{})
f.KubeClientSet.CoreV1().Secrets(f.Namespace.Name).Delete(context.TODO(), f.Config.Addons.ACMEServer.TestingACMEPrivateKey, metav1.DeleteOptions{})
})
It("should allow updating an existing failing certificate that had a blocked dns name", func() {
certClient := f.CertManagerClientSet.CertmanagerV1().Certificates(f.Namespace.Name)
By("Creating a failing Certificate")
// In "devel/addon/pebble/chart/templates/configmap.yaml"
// the "google.com" domain is configured in the pebble blocklist.
cert := gen.Certificate(certificateName,
gen.SetCertificateSecretName(certificateSecretName),
gen.SetCertificateIssuer(cmmeta.ObjectReference{Name: issuerName}),
gen.SetCertificateDNSNames("google.com"),
)
cert.Namespace = f.Namespace.Name
cert, err := certClient.Create(context.TODO(), cert, metav1.CreateOptions{})
Expect(err).NotTo(HaveOccurred())
By("Making sure the Order failed with a 400 since google.com is invalid")
order := &cmacme.Order{}
err = wait.PollImmediate(1*time.Second, 1*time.Minute, func() (done bool, err error) {
orders, err := listOwnedOrders(f.CertManagerClientSet, cert)
Expect(err).NotTo(HaveOccurred())
if len(orders) == 0 || len(orders) > 1 {
log.Logf("Waiting as one Order should exist, but we found %d", len(orders))
return false, nil
}
order = orders[0]
expected := `400 urn:ietf:params:acme:error:rejectedIdentifier`
if !strings.Contains(order.Status.Reason, expected) {
log.Logf("Waiting for Order's reason, current: %s, should contain: %s", order.Status.Reason, expected)
return false, nil
}
return true, nil
})
Expect(err).NotTo(HaveOccurred())
By("Waiting for the Certificate to be not ready")
cert, err = f.Helper().WaitForCertificateNotReadyAndDoneIssuing(cert, 30*time.Second)
Expect(err).NotTo(HaveOccurred())
err = retry.RetryOnConflict(retry.DefaultRetry, func() error {
By("Getting the latest version of the Certificate")
cert, err = certClient.Get(context.TODO(), certificateName, metav1.GetOptions{})
if err != nil {
return err
}
By("Replacing dnsNames with a valid dns name")
cert = cert.DeepCopy()
cert.Spec.DNSNames = []string{e2eutil.RandomSubdomain(acmeIngressDomain)}
_, err = certClient.Update(context.TODO(), cert, metav1.UpdateOptions{})
if err != nil {
return err
}
return nil
})
Expect(err).NotTo(HaveOccurred())
By("Waiting for the Certificate to have the Ready=True condition")
cert, err = f.Helper().WaitForCertificateReadyAndDoneIssuing(cert, time.Minute*5)
Expect(err).NotTo(HaveOccurred())
By("Sanity checking the issued Certificate")
err = f.Helper().ValidateCertificate(cert, validations...)
Expect(err).NotTo(HaveOccurred())
By("Checking that the secret contains this dns name")
err = f.Helper().ValidateCertificate(cert, func(cert *v1.Certificate, secret *corev1.Secret) error {
dnsnames, err := findDNSNames(secret)
if err != nil {
return err
}
Expect(cert.Spec.DNSNames).To(ContainElements(dnsnames))
return nil
})
Expect(err).NotTo(HaveOccurred())
})
It("should fail to obtain a certificate for a blocked ACME dns name", func() {
By("Creating a Certificate")
// In "devel/addon/pebble/chart/templates/configmap.yaml"
// the "google.com" domain is configured in the pebble blocklist.
cert := gen.Certificate(certificateName,
gen.SetCertificateSecretName(certificateSecretName),
gen.SetCertificateIssuer(cmmeta.ObjectReference{Name: issuerName}),
gen.SetCertificateDNSNames("google.com"),
)
cert.Namespace = f.Namespace.Name
cert, err := f.CertManagerClientSet.CertmanagerV1().Certificates(f.Namespace.Name).Create(context.TODO(), cert, metav1.CreateOptions{})
Expect(err).NotTo(HaveOccurred())
notReadyCondition := v1.CertificateCondition{
Type: v1.CertificateConditionReady,
Status: cmmeta.ConditionFalse,
}
Eventually(cert, "30s", "1s").Should(HaveCondition(f, notReadyCondition))
Consistently(cert, "1m", "10s").Should(HaveCondition(f, notReadyCondition))
})
It("should obtain a signed certificate with a single CN from the ACME server when putting an annotation on an ingress resource", func() {
switch {
case util.HasIngresses(f.KubeClientSet.Discovery(), networkingv1.SchemeGroupVersion.String()):
ingClient := f.KubeClientSet.NetworkingV1().Ingresses(f.Namespace.Name)
By("Creating an Ingress with the issuer name annotation set")
_, err := ingClient.Create(context.TODO(), util.NewIngress(certificateSecretName, certificateSecretName, map[string]string{
"cert-manager.io/issuer": issuerName,
}, acmeIngressDomain), metav1.CreateOptions{})
Expect(err).NotTo(HaveOccurred())
case util.HasIngresses(f.KubeClientSet.Discovery(), networkingv1beta1.SchemeGroupVersion.String()):
ingClient := f.KubeClientSet.NetworkingV1beta1().Ingresses(f.Namespace.Name)
By("Creating an Ingress with the issuer name annotation set")
_, err := ingClient.Create(context.TODO(), util.NewV1Beta1Ingress(certificateSecretName, certificateSecretName, map[string]string{
"cert-manager.io/issuer": issuerName,
}, acmeIngressDomain), metav1.CreateOptions{})
Expect(err).NotTo(HaveOccurred())
default:
Fail("Neither " + networkingv1.SchemeGroupVersion.String() + " nor " + networkingv1beta1.SchemeGroupVersion.String() + " were discovered in the API server")
}
By("Waiting for Certificate to exist")
cert, err := f.Helper().WaitForCertificateToExist(f.Namespace.Name, certificateSecretName, time.Second*60)
Expect(err).NotTo(HaveOccurred())
By("Waiting for the Certificate to be issued...")
cert, err = f.Helper().WaitForCertificateReadyAndDoneIssuing(cert, time.Minute*5)
Expect(err).NotTo(HaveOccurred())
By("Validating the issued Certificate...")
err = f.Helper().ValidateCertificate(cert, validations...)
Expect(err).NotTo(HaveOccurred())
})
It("should obtain a signed certificate with a single CN from the ACME server when redirected", func() {
certClient := f.CertManagerClientSet.CertmanagerV1().Certificates(f.Namespace.Name)
// force-ssl-redirect should make every request turn into a redirect,
// but I haven't been able to make this happen. Create a TLS cert via
// the self-sign issuer to make it have a "proper" TLS cert
// TODO: investigate if we still need to use the self-signed issuer here
issuer := gen.Issuer("selfsign",
gen.SetIssuerNamespace(f.Namespace.Name),
gen.SetIssuerSelfSigned(v1.SelfSignedIssuer{}))
_, err := f.CertManagerClientSet.CertmanagerV1().Issuers(f.Namespace.Name).Create(context.TODO(), issuer, metav1.CreateOptions{})
Expect(err).NotTo(HaveOccurred())
By("Waiting for (selfsign) Issuer to become Ready")
err = util.WaitForIssuerCondition(f.CertManagerClientSet.CertmanagerV1().Issuers(f.Namespace.Name),
issuerName,
v1.IssuerCondition{
Type: v1.IssuerConditionReady,
Status: cmmeta.ConditionTrue,
})
Expect(err).NotTo(HaveOccurred())
const dummycert = "dummy-tls"
const secretname = "dummy-tls-secret"
selfcert := util.NewCertManagerBasicCertificate("dummy-tls", secretname, "selfsign", v1.IssuerKind, nil, nil, acmeIngressDomain)
selfcert, err = certClient.Create(context.TODO(), selfcert, metav1.CreateOptions{})
Expect(err).NotTo(HaveOccurred())
By("Waiting for the Certificate to be issued...")
selfcert, err = f.Helper().WaitForCertificateReadyAndDoneIssuing(selfcert, time.Minute*5)
Expect(err).NotTo(HaveOccurred())
By("Validating the issued Certificate...")
err = f.Helper().ValidateCertificate(selfcert, validations...)
Expect(err).NotTo(HaveOccurred())
// create an ingress that points at nothing, but has the TLS redirect annotation set
// using the TLS secret that we just got from the self-sign
switch {
case util.HasIngresses(f.KubeClientSet.Discovery(), networkingv1.SchemeGroupVersion.String()):
ingress := f.KubeClientSet.NetworkingV1().Ingresses(f.Namespace.Name)
_, err = ingress.Create(context.TODO(), &networkingv1.Ingress{
ObjectMeta: metav1.ObjectMeta{
Name: fixedIngressName,
Annotations: map[string]string{
"nginx.ingress.kubernetes.io/force-ssl-redirect": "true",
},
},
Spec: networkingv1.IngressSpec{
IngressClassName: pointer.StringPtr("nginx"),
TLS: []networkingv1.IngressTLS{
{
Hosts: []string{acmeIngressDomain},
SecretName: secretname,
},
},
Rules: []networkingv1.IngressRule{
{
Host: acmeIngressDomain,
IngressRuleValue: networkingv1.IngressRuleValue{
HTTP: &networkingv1.HTTPIngressRuleValue{
Paths: []networkingv1.HTTPIngressPath{
{
Path: "/",
PathType: func() *networkingv1.PathType { s := networkingv1.PathTypePrefix; return &s }(),
Backend: networkingv1.IngressBackend{
Service: &networkingv1.IngressServiceBackend{
Name: "doesnotexist",
Port: networkingv1.ServiceBackendPort{
Number: 443,
},
},
},
},
},
},
},
},
},
},
}, metav1.CreateOptions{})
Expect(err).NotTo(HaveOccurred())
case util.HasIngresses(f.KubeClientSet.Discovery(), networkingv1beta1.SchemeGroupVersion.String()):
ingress := f.KubeClientSet.NetworkingV1beta1().Ingresses(f.Namespace.Name)
_, err = ingress.Create(context.TODO(), &networkingv1beta1.Ingress{
ObjectMeta: metav1.ObjectMeta{
Name: fixedIngressName,
Annotations: map[string]string{
"nginx.ingress.kubernetes.io/force-ssl-redirect": "true",
},
},
Spec: networkingv1beta1.IngressSpec{
IngressClassName: pointer.StringPtr("nginx"),
TLS: []networkingv1beta1.IngressTLS{
{
Hosts: []string{acmeIngressDomain},
SecretName: secretname,
},
},
Rules: []networkingv1beta1.IngressRule{
{
Host: acmeIngressDomain,
IngressRuleValue: networkingv1beta1.IngressRuleValue{
HTTP: &networkingv1beta1.HTTPIngressRuleValue{
Paths: []networkingv1beta1.HTTPIngressPath{
{
Path: "/",
Backend: networkingv1beta1.IngressBackend{
ServiceName: "doesnotexist",
ServicePort: intstr.FromInt(443),
},
},
},
},
},
},
},
},
}, metav1.CreateOptions{})
Expect(err).NotTo(HaveOccurred())
default:
Fail("Neither " + networkingv1.SchemeGroupVersion.String() + " nor " + networkingv1beta1.SchemeGroupVersion.String() + " were discovered in the API server")
}
// This is a special cert for the test suite, where we specify an ingress rather than a
// class
By("Creating a Certificate")
cert := gen.Certificate(certificateName,
gen.SetCertificateSecretName(certificateSecretName),
gen.SetCertificateIssuer(cmmeta.ObjectReference{Name: issuerName}),
gen.SetCertificateDNSNames(acmeIngressDomain),
)
cert.Namespace = f.Namespace.Name
cert.Labels = map[string]string{
"testing.cert-manager.io/fixed-ingress": "true",
}
cert, err = certClient.Create(context.TODO(), cert, metav1.CreateOptions{})
Expect(err).NotTo(HaveOccurred())
By("Waiting for the Certificate to be issued...")
cert, err = f.Helper().WaitForCertificateReadyAndDoneIssuing(cert, time.Minute*5)
Expect(err).NotTo(HaveOccurred())
By("Validating the issued Certificate...")
err = f.Helper().ValidateCertificate(cert, validations...)
Expect(err).NotTo(HaveOccurred())
})
It("should automatically recreate challenge pod and still obtain a certificate if it is manually deleted", func() {
certClient := f.CertManagerClientSet.CertmanagerV1().Certificates(f.Namespace.Name)
By("Creating a Certificate")
cert := gen.Certificate(certificateName,
gen.SetCertificateSecretName(certificateSecretName),
gen.SetCertificateIssuer(cmmeta.ObjectReference{Name: issuerName}),
gen.SetCertificateDNSNames(acmeIngressDomain),
)
cert.Namespace = f.Namespace.Name
cert, err := certClient.Create(context.TODO(), cert, metav1.CreateOptions{})
Expect(err).NotTo(HaveOccurred())
By("killing the solver pod")
podClient := f.KubeClientSet.CoreV1().Pods(f.Namespace.Name)
var pod corev1.Pod
err = wait.PollImmediate(1*time.Second, time.Minute,
func() (bool, error) {
log.Logf("Waiting for solver pod to exist")
podlist, err := podClient.List(context.TODO(), metav1.ListOptions{})
if err != nil {
return false, err
}
for _, p := range podlist.Items {
log.Logf("solver pod %s", p.Name)
// TODO(dmo): make this cleaner instead of just going by name
if strings.Contains(p.Name, "http-solver") {
pod = p
return true, nil
}
}
return false, nil
},
)
Expect(err).NotTo(HaveOccurred())
err = podClient.Delete(context.TODO(), pod.Name, metav1.DeleteOptions{})
Expect(err).NotTo(HaveOccurred())
By("Waiting for Certificate to exist")
cert, err = f.Helper().WaitForCertificateToExist(f.Namespace.Name, certificateName, time.Second*60)
Expect(err).NotTo(HaveOccurred())
// The pod should get remade and the certificate should be made valid.
// Killing the pod could potentially make the validation invalid if pebble
// were to ask us for the challenge after the pod was killed, but because
// we kill it so early, we should always be in the self-check phase
By("Waiting for the Certificate to be issued...")
cert, err = f.Helper().WaitForCertificateReadyAndDoneIssuing(cert, time.Minute*5)
Expect(err).NotTo(HaveOccurred())
By("Validating the issued Certificate...")
err = f.Helper().ValidateCertificate(cert, validations...)
Expect(err).NotTo(HaveOccurred())
})
})
// findDNSNames decodes and returns the dns names (SANs) contained in a
// certificate secret.
func findDNSNames(s *corev1.Secret) ([]string, error) {
if s.Data == nil {
return nil, fmt.Errorf("secret contains no data")
}
pkData := s.Data[corev1.TLSPrivateKeyKey]
certData := s.Data[corev1.TLSCertKey]
if len(pkData) == 0 || len(certData) == 0 {
return nil, fmt.Errorf("missing data in CA secret")
}
cert, err := tls.X509KeyPair(certData, pkData)
if err != nil {
return nil, fmt.Errorf("failed to parse data in CA secret: %w", err)
}
x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
if err != nil {
return nil, fmt.Errorf("internal error parsing x509 certificate: %w", err)
}
return x509Cert.DNSNames, nil
}