-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
357 lines (284 loc) · 8.25 KB
/
client.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
package internal
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"time"
"github.com/entrustcorporation/dv/dns01"
"github.com/entrustcorporation/dv/providers/internal/errutils"
)
const defaultBaseURL = "https://api.cloudns.net/dns/"
// Client the ClouDNS client.
type Client struct {
authID string
subAuthID string
authPassword string
BaseURL *url.URL
HTTPClient *http.Client
}
// NewClient creates a ClouDNS client.
func NewClient(authID, subAuthID, authPassword string) (*Client, error) {
if authID == "" && subAuthID == "" {
return nil, errors.New("credentials missing: authID or subAuthID")
}
if authPassword == "" {
return nil, errors.New("credentials missing: authPassword")
}
baseURL, err := url.Parse(defaultBaseURL)
if err != nil {
return nil, err
}
return &Client{
authID: authID,
subAuthID: subAuthID,
authPassword: authPassword,
BaseURL: baseURL,
HTTPClient: &http.Client{Timeout: 10 * time.Second},
}, nil
}
// GetZone Get domain name information for a FQDN.
func (c *Client) GetZone(ctx context.Context, authFQDN string) (*Zone, error) {
authZone, err := dns01.FindZoneByFqdn(authFQDN)
if err != nil {
return nil, fmt.Errorf("could not find zone for FQDN %q: %w", authFQDN, err)
}
authZoneName := dns01.UnFqdn(authZone)
endpoint := c.BaseURL.JoinPath("get-zone-info.json")
q := endpoint.Query()
q.Set("domain-name", authZoneName)
endpoint.RawQuery = q.Encode()
req, err := c.newRequest(ctx, http.MethodGet, endpoint)
if err != nil {
return nil, err
}
rawMessage, err := c.do(req)
if err != nil {
return nil, err
}
var zone Zone
if len(rawMessage) > 0 {
if err = json.Unmarshal(rawMessage, &zone); err != nil {
return nil, errutils.NewUnmarshalError(req, http.StatusOK, rawMessage, err)
}
}
if zone.Name == authZoneName {
return &zone, nil
}
return nil, fmt.Errorf("zone %s not found for authFQDN %s", authZoneName, authFQDN)
}
// FindTxtRecord returns the TXT record a zone ID and a FQDN.
func (c *Client) FindTxtRecord(ctx context.Context, zoneName, fqdn string) (*TXTRecord, error) {
subDomain, err := dns01.ExtractSubDomain(fqdn, zoneName)
if err != nil {
return nil, err
}
endpoint := c.BaseURL.JoinPath("records.json")
q := endpoint.Query()
q.Set("domain-name", zoneName)
q.Set("host", subDomain)
q.Set("type", "TXT")
endpoint.RawQuery = q.Encode()
req, err := c.newRequest(ctx, http.MethodGet, endpoint)
if err != nil {
return nil, err
}
rawMessage, err := c.do(req)
if err != nil {
return nil, err
}
// the API returns [] when there is no records.
if string(rawMessage) == "[]" {
return nil, nil
}
var records map[string]TXTRecord
if err = json.Unmarshal(rawMessage, &records); err != nil {
return nil, errutils.NewUnmarshalError(req, http.StatusOK, rawMessage, err)
}
for _, record := range records {
if record.Host == subDomain && record.Type == "TXT" {
return &record, nil
}
}
return nil, nil
}
// ListTxtRecords returns the TXT records a zone ID and a FQDN.
func (c *Client) ListTxtRecords(ctx context.Context, zoneName, fqdn string) ([]TXTRecord, error) {
subDomain, err := dns01.ExtractSubDomain(fqdn, zoneName)
if err != nil {
return nil, err
}
endpoint := c.BaseURL.JoinPath("records.json")
q := endpoint.Query()
q.Set("domain-name", zoneName)
q.Set("host", subDomain)
q.Set("type", "TXT")
endpoint.RawQuery = q.Encode()
req, err := c.newRequest(ctx, http.MethodGet, endpoint)
if err != nil {
return nil, err
}
rawMessage, err := c.do(req)
if err != nil {
return nil, err
}
// the API returns [] when there is no records.
if string(rawMessage) == "[]" {
return nil, nil
}
var raw map[string]TXTRecord
if err = json.Unmarshal(rawMessage, &raw); err != nil {
return nil, errutils.NewUnmarshalError(req, http.StatusOK, rawMessage, err)
}
var records []TXTRecord
for _, record := range raw {
if record.Host == subDomain && record.Type == "TXT" {
records = append(records, record)
}
}
return records, nil
}
// AddTxtRecord adds a TXT record.
func (c *Client) AddTxtRecord(ctx context.Context, zoneName, fqdn, value string, ttl int) error {
subDomain, err := dns01.ExtractSubDomain(fqdn, zoneName)
if err != nil {
return err
}
endpoint := c.BaseURL.JoinPath("add-record.json")
q := endpoint.Query()
q.Set("domain-name", zoneName)
q.Set("host", subDomain)
q.Set("record", value)
q.Set("ttl", strconv.Itoa(ttlRounder(ttl)))
q.Set("record-type", "TXT")
endpoint.RawQuery = q.Encode()
req, err := c.newRequest(ctx, http.MethodPost, endpoint)
if err != nil {
return err
}
rawMessage, err := c.do(req)
if err != nil {
return err
}
resp := apiResponse{}
if err = json.Unmarshal(rawMessage, &resp); err != nil {
return errutils.NewUnmarshalError(req, http.StatusOK, rawMessage, err)
}
if resp.Status != "Success" {
return fmt.Errorf("failed to add TXT record: %s %s", resp.Status, resp.StatusDescription)
}
return nil
}
// RemoveTxtRecord removes a TXT record.
func (c *Client) RemoveTxtRecord(ctx context.Context, recordID int, zoneName string) error {
endpoint := c.BaseURL.JoinPath("delete-record.json")
q := endpoint.Query()
q.Set("domain-name", zoneName)
q.Set("record-id", strconv.Itoa(recordID))
endpoint.RawQuery = q.Encode()
req, err := c.newRequest(ctx, http.MethodPost, endpoint)
if err != nil {
return err
}
rawMessage, err := c.do(req)
if err != nil {
return err
}
resp := apiResponse{}
if err = json.Unmarshal(rawMessage, &resp); err != nil {
return errutils.NewUnmarshalError(req, http.StatusOK, rawMessage, err)
}
if resp.Status != "Success" {
return fmt.Errorf("failed to remove TXT record: %s %s", resp.Status, resp.StatusDescription)
}
return nil
}
// GetUpdateStatus gets sync progress of all CloudDNS NS servers.
func (c *Client) GetUpdateStatus(ctx context.Context, zoneName string) (*SyncProgress, error) {
endpoint := c.BaseURL.JoinPath("update-status.json")
q := endpoint.Query()
q.Set("domain-name", zoneName)
endpoint.RawQuery = q.Encode()
req, err := c.newRequest(ctx, http.MethodGet, endpoint)
if err != nil {
return nil, err
}
rawMessage, err := c.do(req)
if err != nil {
return nil, err
}
// the API returns [] when there is no records.
if string(rawMessage) == "[]" {
return nil, errors.New("no nameservers records returned")
}
var records []UpdateRecord
if err = json.Unmarshal(rawMessage, &records); err != nil {
return nil, errutils.NewUnmarshalError(req, http.StatusOK, rawMessage, err)
}
updatedCount := 0
for _, record := range records {
if record.Updated {
updatedCount++
}
}
return &SyncProgress{Complete: updatedCount == len(records), Updated: updatedCount, Total: len(records)}, nil
}
func (c *Client) newRequest(ctx context.Context, method string, endpoint *url.URL) (*http.Request, error) {
q := endpoint.Query()
if c.subAuthID != "" {
q.Set("sub-auth-id", c.subAuthID)
} else {
q.Set("auth-id", c.authID)
}
q.Set("auth-password", c.authPassword)
endpoint.RawQuery = q.Encode()
req, err := http.NewRequestWithContext(ctx, method, endpoint.String(), nil)
if err != nil {
return nil, fmt.Errorf("unable to create request: %w", err)
}
return req, nil
}
func (c *Client) do(req *http.Request) (json.RawMessage, error) {
resp, err := c.HTTPClient.Do(req)
if err != nil {
return nil, errutils.NewHTTPDoError(req, err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
return nil, errutils.NewUnexpectedResponseStatusCodeError(req, resp)
}
raw, err := io.ReadAll(resp.Body)
if err != nil {
return nil, errutils.NewReadResponseError(req, resp.StatusCode, err)
}
return raw, nil
}
// Rounds the given TTL in seconds to the next accepted value.
// Accepted TTL values are:
// - 60 = 1 minute
// - 300 = 5 minutes
// - 900 = 15 minutes
// - 1800 = 30 minutes
// - 3600 = 1 hour
// - 21600 = 6 hours
// - 43200 = 12 hours
// - 86400 = 1 day
// - 172800 = 2 days
// - 259200 = 3 days
// - 604800 = 1 week
// - 1209600 = 2 weeks
// - 2592000 = 1 month
//
// See https://www.cloudns.net/wiki/article/58/ for details.
func ttlRounder(ttl int) int {
for _, validTTL := range []int{60, 300, 900, 1800, 3600, 21600, 43200, 86400, 172800, 259200, 604800, 1209600} {
if ttl <= validTTL {
return validTTL
}
}
return 2592000
}