ns1.go raw
1 // Package ns1 implements a DNS provider for solving the DNS-01 challenge using NS1 DNS.
2 package ns1
3
4 import (
5 "errors"
6 "fmt"
7 "net/http"
8 "time"
9
10 "github.com/go-acme/lego/v4/challenge"
11 "github.com/go-acme/lego/v4/challenge/dns01"
12 "github.com/go-acme/lego/v4/log"
13 "github.com/go-acme/lego/v4/platform/config/env"
14 "github.com/go-acme/lego/v4/providers/dns/internal/clientdebug"
15 "gopkg.in/ns1/ns1-go.v2/rest"
16 "gopkg.in/ns1/ns1-go.v2/rest/model/dns"
17 )
18
19 // Environment variables names.
20 const (
21 envNamespace = "NS1_"
22
23 EnvAPIKey = envNamespace + "API_KEY"
24
25 EnvTTL = envNamespace + "TTL"
26 EnvPropagationTimeout = envNamespace + "PROPAGATION_TIMEOUT"
27 EnvPollingInterval = envNamespace + "POLLING_INTERVAL"
28 EnvHTTPTimeout = envNamespace + "HTTP_TIMEOUT"
29 )
30
31 var _ challenge.ProviderTimeout = (*DNSProvider)(nil)
32
33 // Config is used to configure the creation of the DNSProvider.
34 type Config struct {
35 APIKey string
36 PropagationTimeout time.Duration
37 PollingInterval time.Duration
38 TTL int
39 HTTPClient *http.Client
40 }
41
42 // NewDefaultConfig returns a default configuration for the DNSProvider.
43 func NewDefaultConfig() *Config {
44 return &Config{
45 TTL: env.GetOrDefaultInt(EnvTTL, dns01.DefaultTTL),
46 PropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, dns01.DefaultPropagationTimeout),
47 PollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, dns01.DefaultPollingInterval),
48 HTTPClient: &http.Client{
49 Timeout: env.GetOrDefaultSecond(EnvHTTPTimeout, 10*time.Second),
50 },
51 }
52 }
53
54 // DNSProvider implements the challenge.Provider interface.
55 type DNSProvider struct {
56 client *rest.Client
57 config *Config
58 }
59
60 // NewDNSProvider returns a DNSProvider instance configured for NS1.
61 // Credentials must be passed in the environment variables: NS1_API_KEY.
62 func NewDNSProvider() (*DNSProvider, error) {
63 values, err := env.Get(EnvAPIKey)
64 if err != nil {
65 return nil, fmt.Errorf("ns1: %w", err)
66 }
67
68 config := NewDefaultConfig()
69 config.APIKey = values[EnvAPIKey]
70
71 return NewDNSProviderConfig(config)
72 }
73
74 // NewDNSProviderConfig return a DNSProvider instance configured for NS1.
75 func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
76 if config == nil {
77 return nil, errors.New("ns1: the configuration of the DNS provider is nil")
78 }
79
80 if config.APIKey == "" {
81 return nil, errors.New("ns1: credentials missing")
82 }
83
84 if config.HTTPClient == nil {
85 // Because the rest.NewClient uses the http.DefaultClient.
86 config.HTTPClient = &http.Client{Timeout: 10 * time.Second}
87 }
88
89 client := rest.NewClient(clientdebug.Wrap(config.HTTPClient), rest.SetAPIKey(config.APIKey))
90
91 return &DNSProvider{client: client, config: config}, nil
92 }
93
94 // Present creates a TXT record to fulfill the dns-01 challenge.
95 func (d *DNSProvider) Present(domain, token, keyAuth string) error {
96 info := dns01.GetChallengeInfo(domain, keyAuth)
97
98 zone, err := d.getHostedZone(info.EffectiveFQDN)
99 if err != nil {
100 return fmt.Errorf("ns1: %w", err)
101 }
102
103 record, _, err := d.client.Records.Get(zone.Zone, dns01.UnFqdn(info.EffectiveFQDN), "TXT")
104
105 // Create a new record
106 if errors.Is(err, rest.ErrRecordMissing) || record == nil {
107 log.Infof("Create a new record for [zone: %s, fqdn: %s, domain: %s]", zone.Zone, info.EffectiveFQDN, domain)
108
109 // Work through a bug in the NS1 API library that causes 400 Input validation failed (Value None for field '<obj>.filters' is not of type ...)
110 // So the `tags` and `blockedTags` parameters should be initialized to empty.
111 record = dns.NewRecord(zone.Zone, dns01.UnFqdn(info.EffectiveFQDN), "TXT", make(map[string]string), make([]string, 0))
112 record.TTL = d.config.TTL
113 record.Answers = []*dns.Answer{{Rdata: []string{info.Value}}}
114
115 _, err = d.client.Records.Create(record)
116 if err != nil {
117 return fmt.Errorf("ns1: failed to create record [zone: %q, fqdn: %q]: %w", zone.Zone, info.EffectiveFQDN, err)
118 }
119
120 return nil
121 }
122
123 if err != nil {
124 return fmt.Errorf("ns1: failed to get the existing record: %w", err)
125 }
126
127 // Update the existing records
128 record.Answers = append(record.Answers, &dns.Answer{Rdata: []string{info.Value}})
129
130 log.Infof("Update an existing record for [zone: %s, fqdn: %s, domain: %s]", zone.Zone, info.EffectiveFQDN, domain)
131
132 _, err = d.client.Records.Update(record)
133 if err != nil {
134 return fmt.Errorf("ns1: failed to update record [zone: %q, fqdn: %q]: %w", zone.Zone, info.EffectiveFQDN, err)
135 }
136
137 return nil
138 }
139
140 // CleanUp removes the TXT record matching the specified parameters.
141 func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error {
142 info := dns01.GetChallengeInfo(domain, keyAuth)
143
144 zone, err := d.getHostedZone(info.EffectiveFQDN)
145 if err != nil {
146 return fmt.Errorf("ns1: %w", err)
147 }
148
149 name := dns01.UnFqdn(info.EffectiveFQDN)
150
151 _, err = d.client.Records.Delete(zone.Zone, name, "TXT")
152 if err != nil {
153 return fmt.Errorf("ns1: failed to delete record [zone: %q, domain: %q]: %w", zone.Zone, name, err)
154 }
155
156 return nil
157 }
158
159 // Timeout returns the timeout and interval to use when checking for DNS propagation.
160 // Adjusting here to cope with spikes in propagation times.
161 func (d *DNSProvider) Timeout() (timeout, interval time.Duration) {
162 return d.config.PropagationTimeout, d.config.PollingInterval
163 }
164
165 func (d *DNSProvider) getHostedZone(fqdn string) (*dns.Zone, error) {
166 authZone, err := dns01.FindZoneByFqdn(fqdn)
167 if err != nil {
168 return nil, fmt.Errorf("could not find zone: %w", err)
169 }
170
171 authZone = dns01.UnFqdn(authZone)
172
173 zone, _, err := d.client.Zones.Get(authZone, false)
174 if err != nil {
175 return nil, fmt.Errorf("failed to get zone [authZone: %q, fqdn: %q]: %w", authZone, fqdn, err)
176 }
177
178 return zone, nil
179 }
180