forked from cert-manager/cert-manager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
prepare.go
327 lines (289 loc) · 10.6 KB
/
prepare.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
package acme
import (
"context"
"errors"
"fmt"
"sync"
"github.com/golang/glog"
"golang.org/x/crypto/acme"
"k8s.io/api/core/v1"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
"github.com/jetstack/cert-manager/pkg/apis/certmanager/v1alpha1"
"github.com/jetstack/cert-manager/pkg/util"
"github.com/jetstack/cert-manager/pkg/util/pki"
)
const (
successObtainedAuthorization = "ObtainAuthorization"
reasonPresentChallenge = "PresentChallenge"
reasonSelfCheck = "SelfCheck"
errorGetACMEAccount = "ErrGetACMEAccount"
errorCheckAuthorization = "ErrCheckAuthorization"
errorObtainAuthorization = "ErrObtainAuthorization"
errorInvalidConfig = "ErrInvalidConfig"
messageObtainedAuthorization = "Obtained authorization for domain %s"
messagePresentChallenge = "Presenting %s challenge for domain %s"
messageSelfCheck = "Performing self-check for domain %s"
messageErrorGetACMEAccount = "Error getting ACME account: "
messageErrorCheckAuthorization = "Error checking ACME domain validation: "
messageErrorObtainAuthorization = "Error obtaining ACME domain authorization: "
messageErrorMissingConfig = "certificate.spec.acme must be specified"
)
// Prepare will ensure the issuer has been initialised and is ready to issue
// certificates for the domains listed on the Certificate resource.
//
// It will send the appropriate Letsencrypt authorizations, and complete
// challenge requests if neccessary.
func (a *Acme) Prepare(ctx context.Context, crt *v1alpha1.Certificate) error {
if crt.Spec.ACME == nil {
crt.UpdateStatusCondition(v1alpha1.CertificateConditionReady, v1alpha1.ConditionFalse, errorInvalidConfig, messageErrorMissingConfig)
return fmt.Errorf(messageErrorMissingConfig)
}
// obtain an ACME client
cl, err := a.acmeClient()
if err != nil {
s := messageErrorGetACMEAccount + err.Error()
crt.UpdateStatusCondition(v1alpha1.CertificateConditionReady, v1alpha1.ConditionFalse, errorGetACMEAccount, s)
return errors.New(s)
}
// step one: check issuer to see if we already have authorizations
toAuthorize, err := a.authorizationsToObtain(ctx, cl, crt)
if err != nil {
s := messageErrorCheckAuthorization + err.Error()
crt.UpdateStatusCondition(v1alpha1.CertificateConditionReady, v1alpha1.ConditionFalse, errorCheckAuthorization, s)
return errors.New(s)
}
// if there are no more authorizations to obtain, we are done
if len(toAuthorize) == 0 {
// TODO: set a field in the status block to show authorizations have
// been obtained so we can periodically update the auth status
return nil
}
// request authorizations from the ACME server
auths, err := getAuthorizations(ctx, cl, toAuthorize...)
if err != nil {
s := messageErrorCheckAuthorization + err.Error()
crt.UpdateStatusCondition(v1alpha1.CertificateConditionReady, v1alpha1.ConditionFalse, errorCheckAuthorization, s)
return errors.New(s)
}
// TODO: move some of this logic into it's own function
// attempt to authorize each domain. we do this in parallel to speed up
// authorizations.
var wg sync.WaitGroup
resultChan := make(chan struct {
authResponse
*acme.Authorization
error
}, len(auths))
for _, auth := range auths {
wg.Add(1)
go func(auth authResponse) {
defer wg.Done()
a, err := a.authorize(ctx, cl, crt, auth)
resultChan <- struct {
authResponse
*acme.Authorization
error
}{authResponse: auth, Authorization: a, error: err}
}(auth)
}
wg.Wait()
close(resultChan)
var errs []error
for res := range resultChan {
if res.error != nil {
errs = append(errs, res.error)
continue
}
if res.Authorization.Status != acme.StatusValid {
errs = append(errs, fmt.Errorf("authorization in %s state is not ready", res.Authorization.Status))
}
crt.Status.ACMEStatus().SaveAuthorization(v1alpha1.ACMEDomainAuthorization{
Domain: res.authResponse.domain,
URI: res.Authorization.URI,
Account: a.issuer.GetStatus().ACMEStatus().URI,
})
}
if len(errs) > 0 {
err = utilerrors.NewAggregate(errs)
s := messageErrorCheckAuthorization + err.Error()
crt.UpdateStatusCondition(v1alpha1.CertificateConditionReady, v1alpha1.ConditionFalse, errorCheckAuthorization, s)
return err
}
return nil
}
func keyForChallenge(cl *acme.Client, challenge *acme.Challenge) (string, error) {
var err error
switch challenge.Type {
case "http-01":
return cl.HTTP01ChallengeResponse(challenge.Token)
case "dns-01":
return cl.DNS01ChallengeRecord(challenge.Token)
default:
err = fmt.Errorf("unsupported challenge type %s", challenge.Type)
}
return "", err
}
func (a *Acme) authorize(ctx context.Context, cl *acme.Client, crt *v1alpha1.Certificate, auth authResponse) (*acme.Authorization, error) {
if crt.Spec.ACME == nil {
return nil, fmt.Errorf("certificate.spec.acme must be set")
}
glog.V(4).Infof("picking challenge type for domain %q", auth.domain)
challengeType, err := a.pickChallengeType(auth.domain, auth.auth, crt.Spec.ACME.Config)
if err != nil {
return nil, fmt.Errorf("error picking challenge type to use for domain '%s': %s", auth.domain, err.Error())
}
glog.V(4).Infof("using challenge type %q for domain %q", challengeType, auth.domain)
challenge, err := challengeForAuthorization(cl, auth.auth, challengeType)
if err != nil {
return nil, fmt.Errorf("error getting challenge for domain '%s': %s", auth.domain, err.Error())
}
token := challenge.Token
key, err := keyForChallenge(cl, challenge)
if err != nil {
return nil, err
}
solver, err := a.solverFor(challengeType)
if err != nil {
return nil, err
}
defer func() {
err := solver.CleanUp(ctx, crt, auth.domain, token, key)
if err != nil {
glog.Errorf("Error cleaning up solver: %s", err.Error())
}
}()
a.recorder.Eventf(crt, v1.EventTypeNormal, reasonPresentChallenge, messagePresentChallenge, challengeType, auth.domain)
err = solver.Present(ctx, crt, auth.domain, token, key)
if err != nil {
return nil, fmt.Errorf("error presenting acme authorization for domain %q: %s", auth.domain, err.Error())
}
a.recorder.Eventf(crt, v1.EventTypeNormal, reasonSelfCheck, messageSelfCheck, auth.domain)
err = solver.Wait(ctx, crt, auth.domain, token, key)
if err != nil {
return nil, fmt.Errorf("error waiting for key to be available for domain %q: %s", auth.domain, err.Error())
}
challenge, err = cl.Accept(ctx, challenge)
if err != nil {
return nil, fmt.Errorf("error accepting acme challenge for domain %q: %s", auth.domain, err.Error())
}
glog.V(4).Infof("waiting for authorization for domain %s (%s)...", auth.domain, challenge.URI)
authorization, err := cl.WaitAuthorization(ctx, challenge.URI)
if err != nil {
return nil, fmt.Errorf("error waiting for authorization for domain %q: %s", auth.domain, err.Error())
}
if authorization.Status != acme.StatusValid {
return nil, fmt.Errorf("expected acme domain authorization status for %q to be valid, but it is %q", auth.domain, authorization.Status)
}
a.recorder.Eventf(crt, v1.EventTypeNormal, successObtainedAuthorization, messageObtainedAuthorization, auth.domain)
return authorization, nil
}
func checkAuthorization(ctx context.Context, cl *acme.Client, uri string) (bool, error) {
a, err := cl.GetAuthorization(ctx, uri)
if err != nil {
if err, ok := err.(*acme.Error); ok {
// response code is 404 when authorization has expired
if err.StatusCode == 404 {
return false, nil
}
}
return false, err
}
if a.Status == acme.StatusValid {
return true, nil
}
return false, nil
}
func authorizationsMap(list []v1alpha1.ACMEDomainAuthorization) map[string]v1alpha1.ACMEDomainAuthorization {
out := make(map[string]v1alpha1.ACMEDomainAuthorization, len(list))
for _, a := range list {
out[a.Domain] = a
}
return out
}
func (a *Acme) authorizationsToObtain(ctx context.Context, cl *acme.Client, crt *v1alpha1.Certificate) ([]string, error) {
authMap := authorizationsMap(crt.Status.ACMEStatus().Authorizations)
expectedDNSNames, err := pki.DNSNamesForCertificate(crt)
if err != nil {
return nil, err
}
toAuthorize := util.StringFilter(func(domain string) (bool, error) {
auth, ok := authMap[domain]
glog.Infof("Compare %q with %q", auth.Account, a.issuer.GetStatus().ACMEStatus().URI)
if !ok || auth.Account != a.issuer.GetStatus().ACMEStatus().URI {
return false, nil
}
return checkAuthorization(ctx, cl, auth.URI)
}, expectedDNSNames...)
domains := make([]string, len(toAuthorize))
for i, v := range toAuthorize {
if v.Err != nil {
return nil, fmt.Errorf("error checking authorization status for %s: %s", v.String, v.Err)
}
domains[i] = v.String
}
return domains, nil
}
type authResponses []authResponse
type authResponse struct {
domain string
auth *acme.Authorization
err error
}
// Error returns an error if any one of the authResponses contains an error
func (a authResponses) Error() error {
var errs []error
for _, r := range a {
if r.err != nil {
errs = append(errs, fmt.Errorf("'%s': %s", r.domain, r.err))
}
}
if len(errs) > 0 {
return fmt.Errorf("error getting authorization for domains: %v", errs)
}
return nil
}
func getAuthorizations(ctx context.Context, cl *acme.Client, domains ...string) ([]authResponse, error) {
respCh := make(chan authResponse)
defer close(respCh)
for _, d := range domains {
go func(domain string) {
auth, err := cl.Authorize(ctx, domain)
if err != nil {
respCh <- authResponse{"", nil, fmt.Errorf("getting acme authorization failed: %s", err.Error())}
return
}
respCh <- authResponse{domain, auth, nil}
}(d)
}
responses := make([]authResponse, len(domains))
for i := 0; i < len(domains); i++ {
responses[i] = <-respCh
}
return responses, authResponses(responses).Error()
}
func (a *Acme) pickChallengeType(domain string, auth *acme.Authorization, cfg []v1alpha1.ACMECertificateDomainConfig) (string, error) {
for _, d := range cfg {
for _, dom := range d.Domains {
if dom == domain {
for _, challenge := range auth.Challenges {
switch {
case challenge.Type == "http-01" && d.HTTP01 != nil && a.issuer.GetSpec().ACME.HTTP01 != nil:
return challenge.Type, nil
case challenge.Type == "dns-01" && d.DNS01 != nil && a.issuer.GetSpec().ACME.DNS01 != nil:
return challenge.Type, nil
}
}
}
}
}
return "", fmt.Errorf("no configured and supported challenge type found")
}
func challengeForAuthorization(cl *acme.Client, auth *acme.Authorization, challengeType string) (*acme.Challenge, error) {
for _, challenge := range auth.Challenges {
if challenge.Type != challengeType {
continue
}
return challenge, nil
}
return nil, fmt.Errorf("challenge mechanism '%s' not allowed for domain", challengeType)
}