forked from libdns/cloudflare
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprovider.go
More file actions
219 lines (185 loc) · 6.08 KB
/
provider.go
File metadata and controls
219 lines (185 loc) · 6.08 KB
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
package cloudflare
import (
"context"
"fmt"
"net/http"
"net/url"
"sync"
"github.com/libdns/libdns"
)
type HTTPClient interface {
Do(req *http.Request) (*http.Response, error)
}
// Provider implements the libdns interfaces for Cloudflare.
// TODO: Support retries and handle rate limits.
type Provider struct {
// API tokens are used for authentication. Make sure to use
// scoped API **tokens**, NOT a global API **key**.
APIToken string `json:"api_token,omitempty"` // API token with Zone.DNS:Write (can be scoped to single Zone if ZoneToken is also provided)
ZoneToken string `json:"zone_token,omitempty"` // Optional Zone:Read token (global scope)
// Traditional API key authentication
AuthEmail string `json:"auth_email,omitempty"` // Email address associated with Cloudflare account
AuthKey string `json:"auth_key,omitempty"` // Global API key (consider using token-based auth instead when possible)
// BaseURL allows overriding the API endpoint
BaseURL string `json:"base_url,omitempty"` // Custom base URL for Cloudflare API
// HTTPClient is the client used to communicate with Cloudflare.
// If nil, a default client will be used.
HTTPClient HTTPClient `json:"-"`
zones map[string]cfZone
zonesMu sync.Mutex
}
// GetRecords lists all the records in the zone.
func (p *Provider) GetRecords(ctx context.Context, zone string) ([]libdns.Record, error) {
zoneInfo, err := p.getZoneInfo(ctx, zone)
if err != nil {
return nil, err
}
page := 1
const maxPageSize = 100
var allRecords []cfDNSRecord
for {
qs := make(url.Values)
qs.Set("page", fmt.Sprintf("%d", page))
qs.Set("per_page", fmt.Sprintf("%d", maxPageSize))
reqURL := fmt.Sprintf("%s/zones/%s/dns_records?%s", p.getBaseURL(), zoneInfo.ID, qs.Encode())
req, err := http.NewRequestWithContext(ctx, http.MethodGet, reqURL, nil)
if err != nil {
return nil, err
}
var pageRecords []cfDNSRecord
response, err := p.doAPIRequest(req, &pageRecords)
if err != nil {
return nil, err
}
allRecords = append(allRecords, pageRecords...)
lastPage := (response.ResultInfo.TotalCount + response.ResultInfo.PerPage - 1) / response.ResultInfo.PerPage
if response.ResultInfo == nil || page >= lastPage || len(pageRecords) == 0 {
break
}
page++
}
recs := make([]libdns.Record, 0, len(allRecords))
for _, rec := range allRecords {
libdnsRec, err := rec.libdnsRecord(zone)
if err != nil {
return nil, fmt.Errorf("parsing Cloudflare DNS record %+v: %v", rec, err)
}
recs = append(recs, libdnsRec)
}
return recs, nil
}
// AppendRecords adds records to the zone. It returns the records that were added.
func (p *Provider) AppendRecords(ctx context.Context, zone string, records []libdns.Record) ([]libdns.Record, error) {
zoneInfo, err := p.getZoneInfo(ctx, zone)
if err != nil {
return nil, err
}
var created []libdns.Record
for _, rec := range records {
result, err := p.createRecord(ctx, zoneInfo, rec)
if err != nil {
return nil, err
}
libdnsRec, err := result.libdnsRecord(zone)
if err != nil {
return nil, fmt.Errorf("parsing Cloudflare DNS record %+v: %v", rec, err)
}
created = append(created, libdnsRec)
}
return created, nil
}
// DeleteRecords deletes the records from the zone. If a record does not have an ID,
// it will be looked up. It returns the records that were deleted.
func (p *Provider) DeleteRecords(ctx context.Context, zone string, records []libdns.Record) ([]libdns.Record, error) {
zoneInfo, err := p.getZoneInfo(ctx, zone)
if err != nil {
return nil, err
}
var recs []libdns.Record
for _, rec := range records {
// record ID is required; try to find it with what was provided
exactMatches, err := p.getDNSRecords(ctx, zoneInfo, rec, true)
if err != nil {
return nil, err
}
for _, cfRec := range exactMatches {
reqURL := fmt.Sprintf("%s/zones/%s/dns_records/%s", p.getBaseURL(), zoneInfo.ID, cfRec.ID)
req, err := http.NewRequestWithContext(ctx, "DELETE", reqURL, nil)
if err != nil {
return nil, err
}
var result cfDNSRecord
_, err = p.doAPIRequest(req, &result)
if err != nil {
return nil, err
}
libdnsRec, err := result.libdnsRecord(zone)
if err != nil {
return nil, fmt.Errorf("parsing Cloudflare DNS record %+v: %v", rec, err)
}
recs = append(recs, libdnsRec)
}
}
return recs, nil
}
// SetRecords sets the records in the zone, either by updating existing records
// or creating new ones. It returns the updated records.
func (p *Provider) SetRecords(ctx context.Context, zone string, records []libdns.Record) ([]libdns.Record, error) {
zoneInfo, err := p.getZoneInfo(ctx, zone)
if err != nil {
return nil, err
}
var results []libdns.Record
for _, rec := range records {
oldRec, err := cloudflareRecord(rec)
if err != nil {
return nil, err
}
oldRec.ZoneID = zoneInfo.ID
// the record might already exist, even if we don't know the ID yet
matches, err := p.getDNSRecords(ctx, zoneInfo, rec, false)
if err != nil {
return nil, err
}
if len(matches) == 0 {
// record doesn't exist; create it
result, err := p.createRecord(ctx, zoneInfo, rec)
if err != nil {
return nil, err
}
libdnsRec, err := result.libdnsRecord(zone)
if err != nil {
return nil, fmt.Errorf("parsing Cloudflare DNS record %+v: %v", rec, err)
}
results = append(results, libdnsRec)
continue
}
if len(matches) > 1 {
return nil, fmt.Errorf("unexpectedly found more than 1 record for %v", rec)
}
// record does exist, fill in the ID so that we can update it
oldRec.ID = matches[0].ID
// record exists; update it
cfRec, err := cloudflareRecord(rec)
if err != nil {
return nil, err
}
result, err := p.updateRecord(ctx, oldRec, cfRec)
if err != nil {
return nil, err
}
libdnsRec, err := result.libdnsRecord(zone)
if err != nil {
return nil, fmt.Errorf("parsing Cloudflare DNS record %+v: %v", rec, err)
}
results = append(results, libdnsRec)
}
return results, nil
}
// Interface guards
var (
_ libdns.RecordGetter = (*Provider)(nil)
_ libdns.RecordAppender = (*Provider)(nil)
_ libdns.RecordSetter = (*Provider)(nil)
_ libdns.RecordDeleter = (*Provider)(nil)
)