summaryrefslogtreecommitdiff
path: root/tools/network/cloudflare/cloudflare.go
blob: 84f62f65334cbb03db902916a0a91455db2767f2 (plain)
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
// Copyright (C) 2019-2023 Algorand, Inc.
// This file is part of go-algorand
//
// go-algorand is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// go-algorand is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with go-algorand.  If not, see <https://www.gnu.org/licenses/>.

package cloudflare

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"strings"
)

const (
	cloudFlareURI = "https://api.cloudflare.com/client/v4/"
	// AutomaticTTL should be used to request cloudflare's Automatic TTL setting (which is 1).
	AutomaticTTL = 1
)

// ErrUserNotPermitted is used when a user that is not permitted in a given zone attempt to perform an operation on that zone.
var ErrUserNotPermitted = fmt.Errorf("user not permitted in zone")

// ErrDuplicateZoneNameFound is used when a user that is not permitted in a given zone attempt to perform an operation on that zone.
var ErrDuplicateZoneNameFound = fmt.Errorf("more than a single zone name found to match the requested zone name")

// Cred contains the credentials used to authenticate with the cloudflare API.
type Cred struct {
	authToken string
}

// DNS is the cloudflare package main access class. Initiate an instance of this class to access the clouldflare APIs.
type DNS struct {
	zoneID string
	Cred
}

// NewCred creates a new credential structure used to authenticate with the cloudflare service.
func NewCred(authToken string) *Cred {
	return &Cred{
		authToken: authToken,
	}
}

// NewDNS create a new instance of clouldflare DNS services class
func NewDNS(zoneID string, authToken string) *DNS {
	return &DNS{
		zoneID: zoneID,
		Cred: Cred{
			authToken: authToken,
		},
	}
}

// SetDNSRecord sets the DNS record to the given content.
func (d *DNS) SetDNSRecord(ctx context.Context, recordType string, name string, content string, ttl uint, priority uint, proxied bool) error {
	entries, err := d.ListDNSRecord(ctx, "", name, "", "", "", "")
	if err != nil {
		return err
	}
	if len(entries) != 0 {
		fmt.Printf("DNS entry for '%s'='%s' already exists, updating.\n", name, content)
		return d.UpdateDNSRecord(ctx, entries[0].ID, recordType, name, content, ttl, priority, proxied)
	}
	return d.CreateDNSRecord(ctx, recordType, name, content, ttl, priority, proxied)
}

// SetSRVRecord sets the DNS SRV record to the given content.
func (d *DNS) SetSRVRecord(ctx context.Context, name string, target string, ttl uint, priority uint, port uint, service string, protocol string, weight uint) error {
	entries, err := d.ListDNSRecord(ctx, "SRV", service+"."+protocol+"."+name, target, "", "", "")

	if err != nil {
		return err
	}
	if len(entries) != 0 {
		fmt.Printf("SRV entry for '%s'='%s' already exists, updating\n", name, target)
		return d.UpdateSRVRecord(ctx, entries[0].ID, name, target, ttl, priority, port, service, protocol, weight)
	}

	return d.CreateSRVRecord(ctx, name, target, ttl, priority, port, service, protocol, weight)
}

// ClearSRVRecord clears the DNS SRV record to the given content.
func (d *DNS) ClearSRVRecord(ctx context.Context, name string, target string, service string, protocol string) error {
	entries, err := d.ListDNSRecord(ctx, "SRV", service+"."+protocol+"."+name, target, "", "", "")

	if err != nil {
		return err
	}
	if len(entries) == 0 {
		fmt.Printf("No SRV entry for '[%s.%s.]%s'='%s'.\n", service, protocol, name, target)
		return nil
	}

	return d.DeleteDNSRecord(ctx, entries[0].ID)
}

// ListDNSRecord list the dns records that matches the given parameters.
func (d *DNS) ListDNSRecord(ctx context.Context, recordType string, name string, content string, order string, direction string, match string) ([]DNSRecordResponseEntry, error) {
	result := []DNSRecordResponseEntry{}
	const perPage uint = 100
	pageIndex := uint(1)
	queryContent := content
	if recordType == "SRV" {
		queryContent = ""
	}
	for {
		request, err := listDNSRecordRequest(d.zoneID, d.authToken, recordType, name, queryContent, pageIndex, perPage, order, direction, match)
		if err != nil {
			return []DNSRecordResponseEntry{}, err
		}
		client := &http.Client{}
		response, err := client.Do(request.WithContext(ctx))
		if err != nil {
			return []DNSRecordResponseEntry{}, err
		}

		parsedReponse, err := parseListDNSRecordResponse(response)
		if err != nil {
			return []DNSRecordResponseEntry{}, fmt.Errorf("failed to list DNS records. Request url = '%v', response error : %v", request.URL, err)
		}
		if len(parsedReponse.Errors) > 0 {
			return []DNSRecordResponseEntry{}, fmt.Errorf("failed to list DNS entries. %+v", parsedReponse.Errors)
		}
		result = append(result, parsedReponse.Result...)
		if parsedReponse.ResultInfo.TotalPages <= int(pageIndex) {
			break
		}
		pageIndex++
	}
	if recordType == "SRV" && content != "" {
		content = strings.ToLower(content)
		for i := len(result) - 1; i >= 0; i-- {
			if !strings.HasSuffix(strings.ToLower(result[i].Content), content) {
				result = append(result[:i], result[i+1:]...)
			}
		}
	}
	return result, nil
}

// CreateDNSRecord creates the DNS record with the given content.
func (d *DNS) CreateDNSRecord(ctx context.Context, recordType string, name string, content string, ttl uint, priority uint, proxied bool) error {
	request, err := createDNSRecordRequest(d.zoneID, d.authToken, recordType, name, content, ttl, priority, proxied)
	if err != nil {
		return err
	}
	client := &http.Client{}
	response, err := client.Do(request.WithContext(ctx))
	if err != nil {
		return fmt.Errorf("failed to create DNS record. Request url = '%v', response : %v", request.URL, err)
	}

	parsedResponse, err := parseCreateDNSRecordResponse(response)
	if err != nil {
		return fmt.Errorf("failed to create DNS record. Request url = '%v', response error : %v", request.URL, err)
	}
	if !parsedResponse.Success {
		request, _ := createDNSRecordRequest(d.zoneID, d.authToken, recordType, name, content, ttl, priority, proxied)
		requestBody, _ := request.GetBody()
		bodyBytes, _ := io.ReadAll(requestBody)
		return fmt.Errorf("failed to create DNS record. Request url = '%v', body = %s, parsed response : %#v, response headers = %#v", request.URL, string(bodyBytes), parsedResponse, response.Header)
	}
	return nil
}

// CreateSRVRecord creates the DNS record with the given content.
func (d *DNS) CreateSRVRecord(ctx context.Context, name string, target string, ttl uint, priority uint, port uint, service string, protocol string, weight uint) error {
	request, err := createSRVRecordRequest(d.zoneID, d.authToken, name, service, protocol, weight, port, ttl, priority, target)
	if err != nil {
		return err
	}
	client := &http.Client{}
	response, err := client.Do(request.WithContext(ctx))
	if err != nil {
		return fmt.Errorf("failed to create SRV record. Request url = '%v', response : %v", request.URL, err)
	}

	parsedResponse, err := parseCreateDNSRecordResponse(response)
	if err != nil {
		return fmt.Errorf("failed to create SRV record. Request url = '%v', response error : %v", request.URL, err)
	}
	if !parsedResponse.Success {
		request, _ := createSRVRecordRequest(d.zoneID, d.authToken, name, service, protocol, weight, port, ttl, priority, target)
		requestBody, _ := request.GetBody()
		bodyBytes, _ := io.ReadAll(requestBody)
		return fmt.Errorf("failed to create SRV record. Request url = '%v', body = %s, parsedResponse = %#v, response headers = %#v", request.URL, string(bodyBytes), parsedResponse, response.Header)
	}
	return nil
}

// DeleteDNSRecord deletes a single DNS entry
func (d *DNS) DeleteDNSRecord(ctx context.Context, recordID string) error {
	request, err := deleteDNSRecordRequest(d.zoneID, d.authToken, recordID)
	if err != nil {
		return err
	}
	client := &http.Client{}
	response, err := client.Do(request.WithContext(ctx))
	if err != nil {
		return err
	}

	parsedResponse, err := parseDeleteDNSRecordResponse(response)
	if err != nil {
		return fmt.Errorf("failed to delete DNS record. Request url = '%v', response error : %v", request.URL, err)
	}
	if !parsedResponse.Success {
		request, _ := deleteDNSRecordRequest(d.zoneID, d.authToken, recordID)
		requestBody, _ := request.GetBody()
		bodyBytes, _ := io.ReadAll(requestBody)
		return fmt.Errorf("failed to delete DNS record. Request url = '%v', body = %s, parsedResponse = %#v, response headers = %#v", request.URL, string(bodyBytes), parsedResponse, response.Header)
	}
	return nil
}

// UpdateDNSRecord update the DNS record with the given content.
func (d *DNS) UpdateDNSRecord(ctx context.Context, recordID string, recordType string, name string, content string, ttl uint, priority uint, proxied bool) error {
	request, err := updateDNSRecordRequest(d.zoneID, d.authToken, recordID, recordType, name, content, ttl, priority, proxied)
	if err != nil {
		return err
	}
	client := &http.Client{}
	response, err := client.Do(request.WithContext(ctx))
	if err != nil {
		return err
	}

	parsedResponse, err := parseUpdateDNSRecordResponse(response)
	if err != nil {
		return fmt.Errorf("failed to update DNS record. Request url = '%v', response error : %v", request.URL, err)
	}

	if !parsedResponse.Success {
		request, _ := updateDNSRecordRequest(d.zoneID, d.authToken, recordID, recordType, name, content, ttl, priority, proxied)
		requestBody, _ := request.GetBody()
		bodyBytes, _ := io.ReadAll(requestBody)
		return fmt.Errorf("failed to update DNS record. Request url = '%v', body = %s, parsedResponse = %#v, response headers = %#v", request.URL, string(bodyBytes), parsedResponse, response.Header)
	}

	return nil
}

// UpdateSRVRecord update the DNS record with the given content.
func (d *DNS) UpdateSRVRecord(ctx context.Context, recordID string, name string, target string, ttl uint, priority uint, port uint, service string, protocol string, weight uint) error {
	request, err := updateSRVRecordRequest(d.zoneID, d.authToken, recordID, name, service, protocol, weight, port, ttl, priority, target)
	if err != nil {
		return err
	}
	client := &http.Client{}
	response, err := client.Do(request.WithContext(ctx))
	if err != nil {
		return err
	}

	parsedResponse, err := parseUpdateDNSRecordResponse(response)
	if err != nil {
		return fmt.Errorf("failed to update SRV record. Request url = '%v', response error : %v", request.URL, err)
	}
	if !parsedResponse.Success {
		request, _ := updateSRVRecordRequest(d.zoneID, d.authToken, recordID, name, service, protocol, weight, port, ttl, priority, target)
		requestBody, _ := request.GetBody()
		bodyBytes, _ := io.ReadAll(requestBody)
		return fmt.Errorf("failed to update SRV record. Request url = '%v', body = %s, parsedResponse = %#v, response headers = %#v", request.URL, string(bodyBytes), parsedResponse, response.Header)
	}
	return nil
}

// Zone represent a single zone on the cloudflare API.
type Zone struct {
	DomainName string
	ZoneID     string
}

// GetZones returns a list of zones that are associated with cloudflare.
func (c *Cred) GetZones(ctx context.Context) (zones []Zone, err error) {
	request, err := getZonesRequest(c.authToken)
	if err != nil {
		return nil, err
	}
	client := &http.Client{}
	response, err := client.Do(request.WithContext(ctx))
	if err != nil {
		return nil, err
	}

	parsedResponse, err := parseGetZonesResponse(response)
	if err != nil {
		return nil, fmt.Errorf("failed to get zones. Request url = '%v', response error : %v", request.URL, err)
	}
	if !parsedResponse.Success {
		request, _ := getZonesRequest(c.authToken)
		requestBody, _ := request.GetBody()
		bodyBytes, _ := io.ReadAll(requestBody)
		return nil, fmt.Errorf("failed to retrieve zone records. Request url = '%v', body = %s, parsedResponse = %#v, response headers = %#v", request.URL, string(bodyBytes), parsedResponse, response.Header)
	}

	for _, z := range parsedResponse.Result {
		zones = append(zones,
			Zone{
				DomainName: z.Name,
				ZoneID:     z.ID,
			},
		)
	}
	return zones, err
}

// GetZoneID returns a zoneID that matches the requested zoneDomainName.
func (c *Cred) GetZoneID(ctx context.Context, zoneDomainName string) (zoneID string, err error) {
	zones, err := c.GetZones(ctx)
	if err != nil {
		return
	}
	if len(zones) == 0 {
		err = ErrUserNotPermitted
		return
	}
	zoneDomainName = strings.ToLower(zoneDomainName)
	var matchingZone Zone
	for _, zone := range zones {
		if zoneDomainName == strings.ToLower(zone.DomainName) {
			// found a match.
			if matchingZone.ZoneID != "" {
				// we already had a previous match ?!
				err = ErrDuplicateZoneNameFound
				return
			}
			matchingZone = zone
		}
	}
	if matchingZone.ZoneID == "" {
		err = fmt.Errorf("no zones matching %s for specified credentials", zoneDomainName)
		return
	}
	return matchingZone.ZoneID, nil
}

// ExportZone exports the zone into a BIND config bytes array
func (d *DNS) ExportZone(ctx context.Context) (exportedZoneBytes []byte, err error) {
	request, err := exportZoneRequest(d.zoneID, d.authToken)
	if err != nil {
		return nil, err
	}
	client := &http.Client{}
	response, err := client.Do(request.WithContext(ctx))
	if err != nil {
		return nil, err
	}
	defer response.Body.Close()
	body, err := io.ReadAll(response.Body)
	if err != nil {
		return nil, err
	}
	return body, nil
}