/
route53.go
402 lines (325 loc) · 11.6 KB
/
route53.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
// Package route53 implements a DNS provider for solving the DNS-01 challenge using AWS Route 53 DNS.
package route53
import (
"context"
"errors"
"fmt"
"math/rand"
"strings"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/aws/retry"
awsconfig "github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/credentials/stscreds"
"github.com/aws/aws-sdk-go-v2/service/route53"
awstypes "github.com/aws/aws-sdk-go-v2/service/route53/types"
"github.com/aws/aws-sdk-go-v2/service/sts"
"github.com/go-acme/lego/v4/challenge/dns01"
"github.com/go-acme/lego/v4/platform/config/env"
"github.com/go-acme/lego/v4/platform/wait"
)
// Environment variables names.
const (
envNamespace = "AWS_"
EnvAccessKeyID = envNamespace + "ACCESS_KEY_ID"
EnvSecretAccessKey = envNamespace + "SECRET_ACCESS_KEY"
EnvRegion = envNamespace + "REGION"
EnvHostedZoneID = envNamespace + "HOSTED_ZONE_ID"
EnvMaxRetries = envNamespace + "MAX_RETRIES"
EnvAssumeRoleArn = envNamespace + "ASSUME_ROLE_ARN"
EnvExternalID = envNamespace + "EXTERNAL_ID"
EnvWaitForRecordSetsChanged = envNamespace + "WAIT_FOR_RECORD_SETS_CHANGED"
EnvTTL = envNamespace + "TTL"
EnvPropagationTimeout = envNamespace + "PROPAGATION_TIMEOUT"
EnvPollingInterval = envNamespace + "POLLING_INTERVAL"
)
// Config is used to configure the creation of the DNSProvider.
type Config struct {
// Static credential chain.
// These are not set via environment for the time being and are only used if they are explicitly provided.
AccessKeyID string
SecretAccessKey string
SessionToken string
Region string
HostedZoneID string
MaxRetries int
AssumeRoleArn string
ExternalID string
WaitForRecordSetsChanged bool
TTL int
PropagationTimeout time.Duration
PollingInterval time.Duration
Client *route53.Client
}
// NewDefaultConfig returns a default configuration for the DNSProvider.
func NewDefaultConfig() *Config {
return &Config{
HostedZoneID: env.GetOrFile(EnvHostedZoneID),
MaxRetries: env.GetOrDefaultInt(EnvMaxRetries, 5),
AssumeRoleArn: env.GetOrDefaultString(EnvAssumeRoleArn, ""),
ExternalID: env.GetOrDefaultString(EnvExternalID, ""),
WaitForRecordSetsChanged: env.GetOrDefaultBool(EnvWaitForRecordSetsChanged, true),
TTL: env.GetOrDefaultInt(EnvTTL, 10),
PropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, 2*time.Minute),
PollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, 4*time.Second),
}
}
// DNSProvider implements the challenge.Provider interface.
type DNSProvider struct {
client *route53.Client
config *Config
}
// NewDNSProvider returns a DNSProvider instance configured for the AWS Route 53 service.
//
// AWS Credentials are automatically detected in the following locations and prioritized in the following order:
// 1. Environment variables: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY,
// AWS_REGION, [AWS_SESSION_TOKEN]
// 2. Shared credentials file (defaults to ~/.aws/credentials)
// 3. Amazon EC2 IAM role
//
// If AWS_HOSTED_ZONE_ID is not set, Lego tries to determine the correct public hosted zone via the FQDN.
//
// See also: https://github.com/aws/aws-sdk-go/wiki/configuring-sdk
func NewDNSProvider() (*DNSProvider, error) {
return NewDNSProviderConfig(NewDefaultConfig())
}
// NewDNSProviderConfig takes a given config and returns a custom configured DNSProvider instance.
func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
if config == nil {
return nil, errors.New("route53: the configuration of the Route53 DNS provider is nil")
}
if config.Client != nil {
return &DNSProvider{client: config.Client, config: config}, nil
}
ctx := context.Background()
cfg, err := createAWSConfig(ctx, config)
if err != nil {
return nil, err
}
return &DNSProvider{
client: route53.NewFromConfig(cfg),
config: config,
}, nil
}
// Timeout returns the timeout and interval to use when checking for DNS propagation.
func (d *DNSProvider) Timeout() (timeout, interval time.Duration) {
return d.config.PropagationTimeout, d.config.PollingInterval
}
// Present creates a TXT record using the specified parameters.
func (d *DNSProvider) Present(domain, token, keyAuth string) error {
ctx := context.Background()
info := dns01.GetChallengeInfo(domain, keyAuth)
hostedZoneID, err := d.getHostedZoneID(ctx, info.EffectiveFQDN)
if err != nil {
return fmt.Errorf("route53: failed to determine hosted zone ID: %w", err)
}
records, err := d.getExistingRecordSets(ctx, hostedZoneID, info.EffectiveFQDN)
if err != nil {
return fmt.Errorf("route53: %w", err)
}
realValue := `"` + info.Value + `"`
var found bool
for _, record := range records {
if deref(record.Value) == realValue {
found = true
}
}
if !found {
records = append(records, awstypes.ResourceRecord{Value: aws.String(realValue)})
}
recordSet := &awstypes.ResourceRecordSet{
Name: aws.String(info.EffectiveFQDN),
Type: "TXT",
TTL: aws.Int64(int64(d.config.TTL)),
ResourceRecords: records,
}
err = d.changeRecord(ctx, awstypes.ChangeActionUpsert, hostedZoneID, recordSet)
if err != nil {
return fmt.Errorf("route53: %w", err)
}
return nil
}
// CleanUp removes the TXT record matching the specified parameters.
func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error {
ctx := context.Background()
info := dns01.GetChallengeInfo(domain, keyAuth)
hostedZoneID, err := d.getHostedZoneID(ctx, info.EffectiveFQDN)
if err != nil {
return fmt.Errorf("failed to determine Route 53 hosted zone ID: %w", err)
}
existingRecords, err := d.getExistingRecordSets(ctx, hostedZoneID, info.EffectiveFQDN)
if err != nil {
return fmt.Errorf("route53: %w", err)
}
if len(existingRecords) == 0 {
return nil
}
var nonLegoRecords []awstypes.ResourceRecord
for _, record := range existingRecords {
if deref(record.Value) != `"`+info.Value+`"` {
nonLegoRecords = append(nonLegoRecords, record)
}
}
action := awstypes.ChangeActionUpsert
recordSet := &awstypes.ResourceRecordSet{
Name: aws.String(info.EffectiveFQDN),
Type: "TXT",
TTL: aws.Int64(int64(d.config.TTL)),
ResourceRecords: nonLegoRecords,
}
// If the records are only records created by lego.
if len(nonLegoRecords) == 0 {
action = awstypes.ChangeActionDelete
recordSet.ResourceRecords = existingRecords
}
err = d.changeRecord(ctx, action, hostedZoneID, recordSet)
if err != nil {
return fmt.Errorf("route53: %w", err)
}
return nil
}
func (d *DNSProvider) changeRecord(ctx context.Context, action awstypes.ChangeAction, hostedZoneID string, recordSet *awstypes.ResourceRecordSet) error {
recordSetInput := &route53.ChangeResourceRecordSetsInput{
HostedZoneId: aws.String(hostedZoneID),
ChangeBatch: &awstypes.ChangeBatch{
Comment: aws.String("Managed by Lego"),
Changes: []awstypes.Change{{
Action: action,
ResourceRecordSet: recordSet,
}},
},
}
resp, err := d.client.ChangeResourceRecordSets(ctx, recordSetInput)
if err != nil {
return fmt.Errorf("failed to change record set: %w", err)
}
changeID := resp.ChangeInfo.Id
if d.config.WaitForRecordSetsChanged {
return wait.For("route53", d.config.PropagationTimeout, d.config.PollingInterval, func() (bool, error) {
resp, err := d.client.GetChange(ctx, &route53.GetChangeInput{Id: changeID})
if err != nil {
return false, fmt.Errorf("failed to query change status: %w", err)
}
if resp.ChangeInfo.Status == awstypes.ChangeStatusInsync {
return true, nil
}
return false, fmt.Errorf("unable to retrieve change: ID=%s", deref(changeID))
})
}
return nil
}
func (d *DNSProvider) getExistingRecordSets(ctx context.Context, hostedZoneID, fqdn string) ([]awstypes.ResourceRecord, error) {
listInput := &route53.ListResourceRecordSetsInput{
HostedZoneId: aws.String(hostedZoneID),
StartRecordName: aws.String(fqdn),
StartRecordType: "TXT",
}
recordSetsOutput, err := d.client.ListResourceRecordSets(ctx, listInput)
if err != nil {
return nil, err
}
if recordSetsOutput == nil {
return nil, nil
}
var records []awstypes.ResourceRecord
for _, recordSet := range recordSetsOutput.ResourceRecordSets {
if deref(recordSet.Name) == fqdn {
records = append(records, recordSet.ResourceRecords...)
}
}
return records, nil
}
func (d *DNSProvider) getHostedZoneID(ctx context.Context, fqdn string) (string, error) {
if d.config.HostedZoneID != "" {
return d.config.HostedZoneID, nil
}
authZone, err := dns01.FindZoneByFqdn(fqdn)
if err != nil {
return "", fmt.Errorf("could not find zone for FQDN %q: %w", fqdn, err)
}
// .DNSName should not have a trailing dot
reqParams := &route53.ListHostedZonesByNameInput{
DNSName: aws.String(dns01.UnFqdn(authZone)),
}
resp, err := d.client.ListHostedZonesByName(ctx, reqParams)
if err != nil {
return "", err
}
var hostedZoneID string
for _, hostedZone := range resp.HostedZones {
// .Name has a trailing dot
if !hostedZone.Config.PrivateZone && deref(hostedZone.Name) == authZone {
hostedZoneID = deref(hostedZone.Id)
break
}
}
if hostedZoneID == "" {
return "", fmt.Errorf("zone %s not found for domain %s", authZone, fqdn)
}
hostedZoneID = strings.TrimPrefix(hostedZoneID, "/hostedzone/")
return hostedZoneID, nil
}
func createAWSConfig(ctx context.Context, config *Config) (aws.Config, error) {
if err := createAWSConfigCheckParams(config); err != nil {
return aws.Config{}, err
}
optFns := []func(options *awsconfig.LoadOptions) error{
awsconfig.WithRetryer(func() aws.Retryer {
return retry.NewStandard(func(options *retry.StandardOptions) {
options.MaxAttempts = config.MaxRetries
// It uses a basic exponential backoff algorithm that returns an initial
// delay of ~400ms with an upper limit of ~30 seconds which should prevent
// causing a high number of consecutive throttling errors.
// For reference: Route 53 enforces an account-wide(!) 5req/s query limit.
options.Backoff = retry.BackoffDelayerFunc(func(attempt int, err error) (time.Duration, error) {
retryCount := attempt
if retryCount > 7 {
retryCount = 7
}
delay := (1 << uint(retryCount)) * (rand.Intn(50) + 200)
return time.Duration(delay) * time.Millisecond, nil
})
})
}),
}
if config.AccessKeyID != "" && config.SecretAccessKey != "" {
optFns = append(optFns,
awsconfig.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(config.AccessKeyID, config.SecretAccessKey, config.SessionToken)),
)
}
if config.Region != "" {
optFns = append(optFns, awsconfig.WithRegion(config.Region))
}
cfg, err := awsconfig.LoadDefaultConfig(ctx, optFns...)
if err != nil {
return aws.Config{}, err
}
if config.AssumeRoleArn != "" {
cfg.Credentials = stscreds.NewAssumeRoleProvider(sts.NewFromConfig(cfg), config.AssumeRoleArn, func(options *stscreds.AssumeRoleOptions) {
if config.ExternalID != "" {
options.ExternalID = &config.ExternalID
}
})
}
return cfg, nil
}
func createAWSConfigCheckParams(config *Config) error {
if config == nil {
return errors.New("config is nil")
}
switch {
case config.SessionToken != "" && config.AccessKeyID == "" && config.SecretAccessKey == "":
return errors.New("SessionToken must be supplied with AccessKeyID and SecretAccessKey")
case config.AccessKeyID == "" && config.SecretAccessKey != "" || config.AccessKeyID != "" && config.SecretAccessKey == "":
return errors.New("AccessKeyID and SecretAccessKey must be supplied together")
}
return nil
}
func deref[T string | int | int32 | int64 | bool](v *T) T {
if v == nil {
var zero T
return zero
}
return *v
}