forked from StackExchange/dnscontrol
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rest.go
461 lines (430 loc) · 12.5 KB
/
rest.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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
package cloudflare
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"github.com/StackExchange/dnscontrol/models"
"github.com/pkg/errors"
)
const (
baseURL = "https://api.cloudflare.com/client/v4/"
zonesURL = baseURL + "zones/"
recordsURL = zonesURL + "%s/dns_records/"
pageRulesURL = zonesURL + "%s/pagerules/"
singlePageRuleURL = pageRulesURL + "%s"
singleRecordURL = recordsURL + "%s"
)
// get list of domains for account. Cache so the ids can be looked up from domain name
func (c *CloudflareApi) fetchDomainList() error {
c.domainIndex = map[string]string{}
c.nameservers = map[string][]string{}
page := 1
for {
zr := &zoneResponse{}
url := fmt.Sprintf("%s?page=%d&per_page=50", zonesURL, page)
if err := c.get(url, zr); err != nil {
return errors.Errorf("Error fetching domain list from cloudflare: %s", err)
}
if !zr.Success {
return errors.Errorf("Error fetching domain list from cloudflare: %s", stringifyErrors(zr.Errors))
}
for _, zone := range zr.Result {
c.domainIndex[zone.Name] = zone.ID
for _, ns := range zone.Nameservers {
c.nameservers[zone.Name] = append(c.nameservers[zone.Name], ns)
}
}
ri := zr.ResultInfo
if len(zr.Result) == 0 || ri.Page*ri.PerPage >= ri.TotalCount {
break
}
page++
}
return nil
}
// get all records for a domain
func (c *CloudflareApi) getRecordsForDomain(id string, domain string) ([]*models.RecordConfig, error) {
url := fmt.Sprintf(recordsURL, id)
page := 1
records := []*models.RecordConfig{}
for {
reqURL := fmt.Sprintf("%s?page=%d&per_page=100", url, page)
var data recordsResponse
if err := c.get(reqURL, &data); err != nil {
return nil, errors.Errorf("Error fetching record list from cloudflare: %s", err)
}
if !data.Success {
return nil, errors.Errorf("Error fetching record list cloudflare: %s", stringifyErrors(data.Errors))
}
for _, rec := range data.Result {
// fmt.Printf("REC: %+v\n", rec)
records = append(records, rec.nativeToRecord(domain))
}
ri := data.ResultInfo
if len(data.Result) == 0 || ri.Page*ri.PerPage >= ri.TotalCount {
break
}
page++
}
// fmt.Printf("DEBUG REORDS=%v\n", records)
return records, nil
}
// create a correction to delete a record
func (c *CloudflareApi) deleteRec(rec *cfRecord, domainID string) *models.Correction {
return &models.Correction{
Msg: fmt.Sprintf("DELETE record: %s %s %d %s (id=%s)", rec.Name, rec.Type, rec.TTL, rec.Content, rec.ID),
F: func() error {
endpoint := fmt.Sprintf(singleRecordURL, domainID, rec.ID)
req, err := http.NewRequest("DELETE", endpoint, nil)
if err != nil {
return err
}
c.setHeaders(req)
_, err = handleActionResponse(http.DefaultClient.Do(req))
return err
},
}
}
func (c *CloudflareApi) createZone(domainName string) (string, error) {
type createZone struct {
Name string `json:"name"`
}
var id string
cz := &createZone{
Name: domainName}
buf := &bytes.Buffer{}
encoder := json.NewEncoder(buf)
if err := encoder.Encode(cz); err != nil {
return "", err
}
req, err := http.NewRequest("POST", zonesURL, buf)
if err != nil {
return "", err
}
c.setHeaders(req)
id, err = handleActionResponse(http.DefaultClient.Do(req))
return id, err
}
func cfSrvData(rec *models.RecordConfig) *cfRecData {
serverParts := strings.Split(rec.GetLabelFQDN(), ".")
return &cfRecData{
Service: serverParts[0],
Proto: serverParts[1],
Name: strings.Join(serverParts[2:], "."),
Port: rec.SrvPort,
Priority: rec.SrvPriority,
Weight: rec.SrvWeight,
Target: rec.GetTargetField(),
}
}
func cfCaaData(rec *models.RecordConfig) *cfRecData {
return &cfRecData{
Tag: rec.CaaTag,
Flags: rec.CaaFlag,
Value: rec.GetTargetField(),
}
}
func (c *CloudflareApi) createRec(rec *models.RecordConfig, domainID string) []*models.Correction {
type createRecord struct {
Name string `json:"name"`
Type string `json:"type"`
Content string `json:"content"`
TTL uint32 `json:"ttl"`
Priority uint16 `json:"priority"`
Data *cfRecData `json:"data"`
}
var id string
content := rec.GetTargetField()
if rec.Metadata[metaOriginalIP] != "" {
content = rec.Metadata[metaOriginalIP]
}
prio := ""
if rec.Type == "MX" {
prio = fmt.Sprintf(" %d ", rec.MxPreference)
}
arr := []*models.Correction{{
Msg: fmt.Sprintf("CREATE record: %s %s %d%s %s", rec.GetLabel(), rec.Type, rec.TTL, prio, content),
F: func() error {
cf := &createRecord{
Name: rec.GetLabel(),
Type: rec.Type,
TTL: rec.TTL,
Content: content,
Priority: rec.MxPreference,
}
if rec.Type == "SRV" {
cf.Data = cfSrvData(rec)
cf.Name = rec.GetLabelFQDN()
} else if rec.Type == "CAA" {
cf.Data = cfCaaData(rec)
cf.Name = rec.GetLabelFQDN()
cf.Content = ""
}
endpoint := fmt.Sprintf(recordsURL, domainID)
buf := &bytes.Buffer{}
encoder := json.NewEncoder(buf)
if err := encoder.Encode(cf); err != nil {
return err
}
req, err := http.NewRequest("POST", endpoint, buf)
if err != nil {
return err
}
c.setHeaders(req)
id, err = handleActionResponse(http.DefaultClient.Do(req))
return err
},
}}
if rec.Metadata[metaProxy] != "off" {
arr = append(arr, &models.Correction{
Msg: fmt.Sprintf("ACTIVATE PROXY for new record %s %s %d %s", rec.GetLabel(), rec.Type, rec.TTL, rec.GetTargetField()),
F: func() error { return c.modifyRecord(domainID, id, true, rec) },
})
}
return arr
}
func (c *CloudflareApi) modifyRecord(domainID, recID string, proxied bool, rec *models.RecordConfig) error {
if domainID == "" || recID == "" {
return errors.Errorf("cannot modify record if domain or record id are empty")
}
type record struct {
ID string `json:"id"`
Proxied bool `json:"proxied"`
Name string `json:"name"`
Type string `json:"type"`
Content string `json:"content"`
Priority uint16 `json:"priority"`
TTL uint32 `json:"ttl"`
Data *cfRecData `json:"data"`
}
r := record{
ID: recID,
Proxied: proxied,
Name: rec.GetLabel(),
Type: rec.Type,
Content: rec.GetTargetField(),
Priority: rec.MxPreference,
TTL: rec.TTL,
Data: nil,
}
if rec.Type == "SRV" {
r.Data = cfSrvData(rec)
r.Name = rec.GetLabelFQDN()
} else if rec.Type == "CAA" {
r.Data = cfCaaData(rec)
r.Name = rec.GetLabelFQDN()
r.Content = ""
}
endpoint := fmt.Sprintf(singleRecordURL, domainID, recID)
buf := &bytes.Buffer{}
encoder := json.NewEncoder(buf)
if err := encoder.Encode(r); err != nil {
return err
}
req, err := http.NewRequest("PUT", endpoint, buf)
if err != nil {
return err
}
c.setHeaders(req)
_, err = handleActionResponse(http.DefaultClient.Do(req))
return err
}
// common error handling for all action responses
func handleActionResponse(resp *http.Response, err error) (id string, e error) {
if err != nil {
return "", err
}
defer resp.Body.Close()
result := &basicResponse{}
decoder := json.NewDecoder(resp.Body)
if err = decoder.Decode(result); err != nil {
return "", errors.Errorf("Unknown error. Status code: %d", resp.StatusCode)
}
if resp.StatusCode != 200 {
return "", errors.Errorf(stringifyErrors(result.Errors))
}
return result.Result.ID, nil
}
func (c *CloudflareApi) setHeaders(req *http.Request) {
req.Header.Set("X-Auth-Key", c.ApiKey)
req.Header.Set("X-Auth-Email", c.ApiUser)
}
// generic get handler. makes request and unmarshalls response to given interface
func (c *CloudflareApi) get(endpoint string, target interface{}) error {
req, err := http.NewRequest("GET", endpoint, nil)
if err != nil {
return err
}
c.setHeaders(req)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return errors.Errorf("bad status code from cloudflare: %d not 200", resp.StatusCode)
}
decoder := json.NewDecoder(resp.Body)
return decoder.Decode(target)
}
func (c *CloudflareApi) getPageRules(id string, domain string) ([]*models.RecordConfig, error) {
url := fmt.Sprintf(pageRulesURL, id)
data := pageRuleResponse{}
if err := c.get(url, &data); err != nil {
return nil, errors.Errorf("Error fetching page rule list from cloudflare: %s", err)
}
if !data.Success {
return nil, errors.Errorf("Error fetching page rule list cloudflare: %s", stringifyErrors(data.Errors))
}
recs := []*models.RecordConfig{}
for _, pr := range data.Result {
// only interested in forwarding rules. Lets be very specific, and skip anything else
if len(pr.Actions) != 1 || len(pr.Targets) != 1 {
continue
}
if pr.Actions[0].ID != "forwarding_url" {
continue
}
err := json.Unmarshal([]byte(pr.Actions[0].Value), &pr.ForwardingInfo)
if err != nil {
return nil, err
}
var thisPr = pr
r := &models.RecordConfig{
Type: "PAGE_RULE",
Original: thisPr,
TTL: 1,
}
r.SetLabel("@", domain)
r.SetTarget(fmt.Sprintf("%s,%s,%d,%d", // $FROM,$TO,$PRIO,$CODE
pr.Targets[0].Constraint.Value,
pr.ForwardingInfo.URL,
pr.Priority,
pr.ForwardingInfo.StatusCode))
recs = append(recs, r)
}
return recs, nil
}
func (c *CloudflareApi) deletePageRule(recordID, domainID string) error {
endpoint := fmt.Sprintf(singlePageRuleURL, domainID, recordID)
req, err := http.NewRequest("DELETE", endpoint, nil)
if err != nil {
return err
}
c.setHeaders(req)
_, err = handleActionResponse(http.DefaultClient.Do(req))
return err
}
func (c *CloudflareApi) updatePageRule(recordID, domainID string, target string) error {
if err := c.deletePageRule(recordID, domainID); err != nil {
return err
}
return c.createPageRule(domainID, target)
}
func (c *CloudflareApi) createPageRule(domainID string, target string) error {
endpoint := fmt.Sprintf(pageRulesURL, domainID)
return c.sendPageRule(endpoint, "POST", target)
}
func (c *CloudflareApi) sendPageRule(endpoint, method string, data string) error {
// from to priority code
parts := strings.Split(data, ",")
priority, _ := strconv.Atoi(parts[2])
code, _ := strconv.Atoi(parts[3])
fwdInfo := &pageRuleFwdInfo{
StatusCode: code,
URL: parts[1],
}
dat, _ := json.Marshal(fwdInfo)
pr := &pageRule{
Status: "active",
Priority: priority,
Targets: []pageRuleTarget{
{Target: "url", Constraint: pageRuleConstraint{Operator: "matches", Value: parts[0]}},
},
Actions: []pageRuleAction{
{ID: "forwarding_url", Value: json.RawMessage(dat)},
},
}
buf := &bytes.Buffer{}
enc := json.NewEncoder(buf)
if err := enc.Encode(pr); err != nil {
return err
}
req, err := http.NewRequest(method, endpoint, buf)
if err != nil {
return err
}
c.setHeaders(req)
_, err = handleActionResponse(http.DefaultClient.Do(req))
return err
}
func stringifyErrors(errors []interface{}) string {
dat, err := json.Marshal(errors)
if err != nil {
return "???"
}
return string(dat)
}
type recordsResponse struct {
basicResponse
Result []*cfRecord `json:"result"`
ResultInfo pagingInfo `json:"result_info"`
}
type basicResponse struct {
Success bool `json:"success"`
Errors []interface{} `json:"errors"`
Messages []interface{} `json:"messages"`
Result struct {
ID string `json:"id"`
} `json:"result"`
}
type pageRuleResponse struct {
basicResponse
Result []*pageRule `json:"result"`
ResultInfo pagingInfo `json:"result_info"`
}
type pageRule struct {
ID string `json:"id,omitempty"`
Targets []pageRuleTarget `json:"targets"`
Actions []pageRuleAction `json:"actions"`
Priority int `json:"priority"`
Status string `json:"status"`
ModifiedOn time.Time `json:"modified_on,omitempty"`
CreatedOn time.Time `json:"created_on,omitempty"`
ForwardingInfo *pageRuleFwdInfo `json:"-"`
}
type pageRuleTarget struct {
Target string `json:"target"`
Constraint pageRuleConstraint `json:"constraint"`
}
type pageRuleConstraint struct {
Operator string `json:"operator"`
Value string `json:"value"`
}
type pageRuleAction struct {
ID string `json:"id"`
Value json.RawMessage `json:"value"`
}
type pageRuleFwdInfo struct {
URL string `json:"url"`
StatusCode int `json:"status_code"`
}
type zoneResponse struct {
basicResponse
Result []struct {
ID string `json:"id"`
Name string `json:"name"`
Nameservers []string `json:"name_servers"`
} `json:"result"`
ResultInfo pagingInfo `json:"result_info"`
}
type pagingInfo struct {
Page int `json:"page"`
PerPage int `json:"per_page"`
Count int `json:"count"`
TotalCount int `json:"total_count"`
}