-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
353 lines (303 loc) · 8.86 KB
/
client.go
File metadata and controls
353 lines (303 loc) · 8.86 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
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
package httpnet
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
"github.com/libdns/libdns"
)
const (
defaultBaseURL = "https://partner.http.net/api/dns/v1/json"
defaultTimeout = 30 * time.Second
minTTLSeconds = 60
)
type apiRequest struct {
AuthToken string `json:"authToken"`
Filter *apiFilter `json:"filter,omitempty"`
Limit int `json:"limit,omitempty"`
Page int `json:"page,omitempty"`
}
// recordsUpdateReq is the request body for the recordsUpdate endpoint.
// All three lists must be present even if empty.
type recordsUpdateReq struct {
AuthToken string `json:"authToken"`
ZoneName string `json:"zoneName"`
RecordsToAdd []apiRecord `json:"recordsToAdd"`
RecordsToModify []apiRecord `json:"recordsToModify"`
RecordsToDelete []apiRecord `json:"recordsToDelete"`
}
type apiFilter struct {
Field string `json:"field"`
Value string `json:"value"`
}
type apiRecord struct {
ID string `json:"id,omitempty"`
Name string `json:"name"`
Type string `json:"type"`
Content string `json:"content"`
TTL int `json:"ttl,omitempty"`
Priority int `json:"priority,omitempty"`
}
type apiZoneConfig struct {
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
}
type apiEnvelope struct {
Status string `json:"status"`
Errors []apiError `json:"errors,omitempty"`
Response json.RawMessage `json:"response,omitempty"`
}
type apiError struct {
Code int `json:"code"`
Text string `json:"text"`
}
type findRecordsResult struct {
Data []apiRecord `json:"data"`
TotalPages int `json:"totalPages"`
}
type findZoneConfigsResult struct {
Data []apiZoneConfig `json:"data"`
TotalPages int `json:"totalPages"`
}
type recordsUpdateResult struct {
Records []apiRecord `json:"records"`
}
// httpClient returns the HTTP client to use for API requests. A single default
// client is lazily constructed and reused so that the underlying Transport can
// pool TCP/TLS connections across calls.
func (p *Provider) httpClient() *http.Client {
if p.HTTPClient != nil {
return p.HTTPClient
}
p.clientOnce.Do(func() {
p.client = &http.Client{Timeout: defaultTimeout}
})
return p.client
}
func (p *Provider) baseURL() string {
if p.BaseURL != "" {
return strings.TrimRight(p.BaseURL, "/")
}
return defaultBaseURL
}
func (p *Provider) post(ctx context.Context, method string, req any) (json.RawMessage, error) {
body, err := json.Marshal(req)
if err != nil {
return nil, err
}
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, p.baseURL()+"/"+method, bytes.NewReader(body))
if err != nil {
return nil, err
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("Accept", "application/json")
resp, err := p.httpClient().Do(httpReq)
if err != nil {
return nil, err
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var env apiEnvelope
if err := json.Unmarshal(data, &env); err != nil {
return nil, fmt.Errorf("parsing API response (HTTP %d): %w; body: %s", resp.StatusCode, err, data)
}
if env.Status == "error" {
if len(env.Errors) > 0 {
return nil, fmt.Errorf("API error %d: %s", env.Errors[0].Code, env.Errors[0].Text)
}
return nil, fmt.Errorf("API returned error status (HTTP %d)", resp.StatusCode)
}
// Status is "success" or "pending" (async); both are acceptable.
return env.Response, nil
}
func (p *Provider) getZoneID(ctx context.Context, zone string) (string, error) {
p.mu.Lock()
if p.zoneCache == nil {
p.zoneCache = make(map[string]string)
}
if id, ok := p.zoneCache[zone]; ok {
p.mu.Unlock()
return id, nil
}
p.mu.Unlock()
zoneName := strings.TrimSuffix(zone, ".")
resp, err := p.post(ctx, "zoneConfigsFind", apiRequest{
AuthToken: p.AuthToken,
Filter: &apiFilter{Field: "ZoneName", Value: zoneName},
Limit: 1,
})
if err != nil {
return "", err
}
var result findZoneConfigsResult
if err := json.Unmarshal(resp, &result); err != nil {
return "", fmt.Errorf("parsing zone configs: %w", err)
}
if len(result.Data) == 0 {
return "", fmt.Errorf("zone %q not found in http.net account", zone)
}
id := result.Data[0].ID
p.mu.Lock()
p.zoneCache[zone] = id
p.mu.Unlock()
return id, nil
}
func (p *Provider) listRecords(ctx context.Context, zoneID string) ([]apiRecord, error) {
const pageLimit = 100
var all []apiRecord
for page := 1; ; page++ {
resp, err := p.post(ctx, "recordsFind", apiRequest{
AuthToken: p.AuthToken,
Filter: &apiFilter{Field: "ZoneConfigId", Value: zoneID},
Limit: pageLimit,
Page: page,
})
if err != nil {
return nil, err
}
var result findRecordsResult
if err := json.Unmarshal(resp, &result); err != nil {
return nil, fmt.Errorf("parsing records: %w", err)
}
for _, r := range result.Data {
all = append(all, normalizeRecord(r))
}
if page >= result.TotalPages || result.TotalPages == 0 {
break
}
}
return all, nil
}
// listAllZoneConfigs pages through every zoneConfig in the account.
func (p *Provider) listAllZoneConfigs(ctx context.Context) ([]apiZoneConfig, error) {
const pageLimit = 100
var all []apiZoneConfig
for page := 1; ; page++ {
resp, err := p.post(ctx, "zoneConfigsFind", apiRequest{
AuthToken: p.AuthToken,
Limit: pageLimit,
Page: page,
})
if err != nil {
return nil, err
}
var result findZoneConfigsResult
if err := json.Unmarshal(resp, &result); err != nil {
return nil, fmt.Errorf("parsing zone configs: %w", err)
}
all = append(all, result.Data...)
if page >= result.TotalPages || result.TotalPages == 0 {
break
}
}
return all, nil
}
// updateZoneRecords calls recordsUpdate to add, modify, or delete records in one request.
func (p *Provider) updateZoneRecords(ctx context.Context, zone string, toAdd, toModify, toDelete []apiRecord) ([]apiRecord, error) {
// The API requires all three lists to be present, even if empty.
if toAdd == nil {
toAdd = []apiRecord{}
}
if toModify == nil {
toModify = []apiRecord{}
}
if toDelete == nil {
toDelete = []apiRecord{}
}
resp, err := p.post(ctx, "recordsUpdate", recordsUpdateReq{
AuthToken: p.AuthToken,
ZoneName: strings.TrimSuffix(zone, "."),
RecordsToAdd: toAdd,
RecordsToModify: toModify,
RecordsToDelete: toDelete,
})
if err != nil {
return nil, err
}
var result recordsUpdateResult
if err := json.Unmarshal(resp, &result); err != nil {
return nil, fmt.Errorf("parsing recordsUpdate response: %w", err)
}
normalized := make([]apiRecord, len(result.Records))
for i, r := range result.Records {
normalized[i] = normalizeRecord(r)
}
return normalized, nil
}
// unquoteTXT strips the outer double-quotes the http.net API wraps around TXT
// content. Content without surrounding quotes is returned unchanged.
func unquoteTXT(s string) string {
if len(s) >= 2 && s[0] == '"' && s[len(s)-1] == '"' {
return s[1 : len(s)-1]
}
return s
}
// normalizeRecord strips API-specific formatting for consistent internal matching.
func normalizeRecord(r apiRecord) apiRecord {
if r.Type == "TXT" {
r.Content = unquoteTXT(r.Content)
}
return r
}
// toLibdnsRecord converts an API record to a typed libdns value via
// libdns.RR.Parse, which maps every record type libdns knows about. Records
// whose data cannot be parsed are returned as the generic libdns.RR.
//
// The API returns names as FQDNs without trailing dot (e.g. "www.example.com")
// and carries MX/SRV priority as a separate field; libdns expects priority
// folded into Data as "<prio> <target>".
func toLibdnsRecord(r apiRecord, zone string) libdns.Record {
data := r.Content
switch r.Type {
case "MX", "SRV":
data = fmt.Sprintf("%d %s", r.Priority, r.Content)
}
rr := libdns.RR{
Name: libdns.RelativeName(r.Name+".", zone),
TTL: time.Duration(r.TTL) * time.Second,
Type: r.Type,
Data: data,
}
parsed, err := rr.Parse()
if err != nil {
return rr
}
return parsed
}
// fromLibdnsRecord converts a libdns.Record to an http.net API record struct.
// The API expects names as FQDNs without trailing dot (e.g. "www.example.com").
//
// TTL handling: the http.net API enforces a 60-second minimum. Lower values
// are raised to 60 to avoid request rejection; zero is treated the same way.
func fromLibdnsRecord(rec libdns.Record, zone string) apiRecord {
rr := rec.RR()
fqdn := strings.TrimSuffix(libdns.AbsoluteName(rr.Name, zone), ".")
content := rr.Data
priority := 0
switch rr.Type {
case "MX", "SRV":
// libdns encodes priority inline: "10 mail.example.com"
if i := strings.IndexByte(content, ' '); i > 0 {
if p, err := strconv.Atoi(content[:i]); err == nil {
priority = p
content = content[i+1:]
}
}
}
ttl := max(int(rr.TTL.Seconds()), minTTLSeconds)
return apiRecord{
Name: fqdn,
Type: rr.Type,
Content: content,
TTL: ttl,
Priority: priority,
}
}