bunny.go raw
1 // Package bunny implements a DNS provider for solving the DNS-01 challenge using Bunny DNS.
2 package bunny
3
4 import (
5 "context"
6 "errors"
7 "fmt"
8 "net/http"
9 "slices"
10 "time"
11
12 "github.com/go-acme/lego/v4/challenge"
13 "github.com/go-acme/lego/v4/challenge/dns01"
14 "github.com/go-acme/lego/v4/platform/config/env"
15 "github.com/go-acme/lego/v4/providers/dns/internal/clientdebug"
16 "github.com/go-acme/lego/v4/providers/dns/internal/ptr"
17 "github.com/go-acme/lego/v4/providers/dns/internal/useragent"
18 "github.com/nrdcg/bunny-go"
19 "golang.org/x/net/publicsuffix"
20 )
21
22 // Environment variables names.
23 const (
24 envNamespace = "BUNNY_"
25
26 EnvAPIKey = envNamespace + "API_KEY"
27
28 EnvTTL = envNamespace + "TTL"
29 EnvPropagationTimeout = envNamespace + "PROPAGATION_TIMEOUT"
30 EnvPollingInterval = envNamespace + "POLLING_INTERVAL"
31 EnvHTTPTimeout = envNamespace + "HTTP_TIMEOUT"
32 )
33
34 const minTTL = 60
35
36 var _ challenge.ProviderTimeout = (*DNSProvider)(nil)
37
38 // Config is used to configure the creation of the DNSProvider.
39 type Config struct {
40 APIKey string
41
42 PropagationTimeout time.Duration
43 PollingInterval time.Duration
44 TTL int
45 HTTPClient *http.Client
46 }
47
48 // NewDefaultConfig returns a default configuration for the DNSProvider.
49 func NewDefaultConfig() *Config {
50 return &Config{
51 TTL: env.GetOrDefaultInt(EnvTTL, minTTL),
52 PropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, 120*time.Second),
53 PollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, dns01.DefaultPollingInterval),
54 HTTPClient: &http.Client{
55 Timeout: env.GetOrDefaultSecond(EnvHTTPTimeout, 30*time.Second),
56 },
57 }
58 }
59
60 // DNSProvider implements the challenge.Provider interface.
61 type DNSProvider struct {
62 config *Config
63 client *bunny.Client
64 }
65
66 // NewDNSProvider returns a DNSProvider instance configured for bunny.
67 // Credentials must be passed in the environment variable: BUNNY_API_KEY.
68 func NewDNSProvider() (*DNSProvider, error) {
69 values, err := env.Get(EnvAPIKey)
70 if err != nil {
71 return nil, fmt.Errorf("bunny: %w", err)
72 }
73
74 config := NewDefaultConfig()
75 config.APIKey = values[EnvAPIKey]
76
77 return NewDNSProviderConfig(config)
78 }
79
80 // NewDNSProviderConfig return a DNSProvider instance configured for bunny.
81 func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
82 if config == nil {
83 return nil, errors.New("bunny: the configuration of the DNS provider is nil")
84 }
85
86 if config.APIKey == "" {
87 return nil, errors.New("bunny: credentials missing")
88 }
89
90 if config.TTL < minTTL {
91 return nil, fmt.Errorf("bunny: invalid TTL, TTL (%d) must be greater than %d", config.TTL, minTTL)
92 }
93
94 if config.HTTPClient == nil {
95 config.HTTPClient = &http.Client{Timeout: 30 * time.Second}
96 }
97
98 config.HTTPClient = clientdebug.Wrap(config.HTTPClient)
99
100 return &DNSProvider{
101 config: config,
102 client: bunny.NewClient(config.APIKey,
103 bunny.WithUserAgent(useragent.Get()),
104 bunny.WithHTTPClient(config.HTTPClient),
105 ),
106 }, nil
107 }
108
109 // Timeout returns the timeout and interval to use when checking for DNS propagation.
110 // Adjusting here to cope with spikes in propagation times.
111 func (d *DNSProvider) Timeout() (timeout, interval time.Duration) {
112 return d.config.PropagationTimeout, d.config.PollingInterval
113 }
114
115 // Present creates a TXT record to fulfill the dns-01 challenge.
116 func (d *DNSProvider) Present(domain, token, keyAuth string) error {
117 info := dns01.GetChallengeInfo(domain, keyAuth)
118
119 ctx := context.Background()
120
121 zone, err := d.findZone(ctx, dns01.UnFqdn(info.EffectiveFQDN))
122 if err != nil {
123 return fmt.Errorf("bunny: %w", err)
124 }
125
126 subDomain, err := dns01.ExtractSubDomain(info.EffectiveFQDN, ptr.Deref(zone.Domain))
127 if err != nil {
128 return fmt.Errorf("bunny: %w", err)
129 }
130
131 record := &bunny.AddOrUpdateDNSRecordOptions{
132 Type: ptr.Pointer(bunny.DNSRecordTypeTXT),
133 Name: ptr.Pointer(subDomain),
134 Value: ptr.Pointer(info.Value),
135 TTL: ptr.Pointer(int32(d.config.TTL)),
136 }
137
138 if _, err := d.client.DNSZone.AddDNSRecord(ctx, ptr.Deref(zone.ID), record); err != nil {
139 return fmt.Errorf("bunny: failed to add TXT record: fqdn=%s, zoneID=%d: %w", info.EffectiveFQDN, ptr.Deref(zone.ID), err)
140 }
141
142 return nil
143 }
144
145 // CleanUp removes the TXT record matching the specified parameters.
146 func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error {
147 info := dns01.GetChallengeInfo(domain, keyAuth)
148
149 ctx := context.Background()
150
151 zone, err := d.findZone(ctx, dns01.UnFqdn(info.EffectiveFQDN))
152 if err != nil {
153 return fmt.Errorf("bunny: %w", err)
154 }
155
156 subDomain, err := dns01.ExtractSubDomain(info.EffectiveFQDN, ptr.Deref(zone.Domain))
157 if err != nil {
158 return fmt.Errorf("bunny: %w", err)
159 }
160
161 var record *bunny.DNSRecord
162
163 for _, r := range zone.Records {
164 if ptr.Deref(r.Name) == subDomain && ptr.Deref(r.Type) == bunny.DNSRecordTypeTXT {
165 r := r
166 record = &r
167
168 break
169 }
170 }
171
172 if record == nil {
173 return fmt.Errorf("bunny: could not find TXT record zone=%d, subdomain=%s", ptr.Deref(zone.ID), subDomain)
174 }
175
176 if err := d.client.DNSZone.DeleteDNSRecord(ctx, ptr.Deref(zone.ID), ptr.Deref(record.ID)); err != nil {
177 return fmt.Errorf("bunny: failed to delete TXT record: id=%d, name=%s: %w", ptr.Deref(record.ID), ptr.Deref(record.Name), err)
178 }
179
180 return nil
181 }
182
183 func (d *DNSProvider) findZone(ctx context.Context, authZone string) (*bunny.DNSZone, error) {
184 zones, err := d.client.DNSZone.List(ctx, nil)
185 if err != nil {
186 return nil, err
187 }
188
189 zone := findZone(zones, authZone)
190 if zone == nil {
191 return nil, fmt.Errorf("could not find DNSZone domain=%s", authZone)
192 }
193
194 return zone, nil
195 }
196
197 func findZone(zones *bunny.DNSZones, domain string) *bunny.DNSZone {
198 domains := possibleDomains(domain)
199
200 var domainLength int
201
202 var zone *bunny.DNSZone
203
204 for _, item := range zones.Items {
205 if item == nil {
206 continue
207 }
208
209 curr := ptr.Deref(item.Domain)
210
211 if slices.Contains(domains, curr) && domainLength < len(curr) {
212 domainLength = len(curr)
213
214 zone = item
215 }
216 }
217
218 return zone
219 }
220
221 func possibleDomains(domain string) []string {
222 var domains []string
223
224 tld, _ := publicsuffix.PublicSuffix(domain)
225 for d := range dns01.DomainsSeq(domain) {
226 if tld == d {
227 // skip the TLD
228 break
229 }
230
231 domains = append(domains, dns01.UnFqdn(d))
232 }
233
234 return domains
235 }
236