-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathprovider.go
More file actions
503 lines (446 loc) · 15.8 KB
/
Copy pathprovider.go
File metadata and controls
503 lines (446 loc) · 15.8 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
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
// Package njalla implements the libdns interfaces for Njalla
// (https://njal.la), allowing DNS records to be managed through the Njalla
// JSON-RPC API.
package njalla
import (
"context"
"fmt"
"strings"
"sync"
"github.com/libdns/libdns"
)
// Provider facilitates DNS record manipulation with Njalla.
//
// # Record types
//
// A, AAAA, CAA, CNAME, MX, NS, SRV, TXT, HTTPS, and SVCB records are returned
// as the corresponding concrete libdns types. Any other type, including
// Njalla's proprietary Redirect and Dynamic pseudo-types, is returned as an
// opaque [libdns.RR]. Records of any type may be supplied as input.
//
// # Provider-specific behaviour
//
// Values are stored exactly as supplied. Njalla preserves trailing dots on
// CNAME, NS, MX, and SRV targets rather than normalising them, and matches on
// them byte-for-byte, so this package does not rewrite them either.
//
// A TTL of 0 leaves the TTL unset, which Njalla defaults to 10800 seconds. Use
// a sub-second duration to request a TTL of 0, as described by [libdns.RR].
//
// Njalla rejects a few otherwise-valid records: TXT values that are empty or
// contain a double quote, and MX records with a preference of 0. These are
// reported as errors before the API is called.
//
// DNSSEC records are not returned by GetRecords and are not supported by
// SetRecords.
//
// # Atomicity
//
// The Njalla API offers no batch operations, so AppendRecords, SetRecords, and
// DeleteRecords are not atomic. If one of them returns an error, some of the
// requested changes may already have been applied; the records that were
// successfully changed are returned alongside the error.
//
// All methods are safe for concurrent use.
type Provider struct {
// APIToken is the Njalla API token used for authentication. Tokens are
// created from the Njalla account settings page.
//
// The token needs the add-record, edit-record, remove-record, and
// list-records methods. A token created with Njalla's "acme" option
// covers the ACME DNS-01 challenge, but restricts listing to the
// _acme-challenge prefix.
APIToken string `json:"api_token,omitempty"`
// HTTPClient is used for API requests. If nil, a client with a 30 second
// timeout is used.
HTTPClient HTTPClient `json:"-"`
client clientInterface
clientOnce sync.Once
// zoneMu serialises the read-modify-write cycle in SetRecords per zone, so
// that concurrent calls cannot lose each other's changes.
zoneMu map[string]*sync.Mutex
zoneMuMu sync.Mutex
}
// getClient returns the API client, creating it on first use.
func (p *Provider) getClient() clientInterface {
p.clientOnce.Do(func() {
p.client = newClient(p.APIToken, p.HTTPClient)
})
return p.client
}
// lockZone serialises per-zone read-modify-write sequences.
func (p *Provider) lockZone(zone string) func() {
p.zoneMuMu.Lock()
if p.zoneMu == nil {
p.zoneMu = make(map[string]*sync.Mutex)
}
mu, ok := p.zoneMu[zone]
if !ok {
mu = new(sync.Mutex)
p.zoneMu[zone] = mu
}
p.zoneMuMu.Unlock()
mu.Lock()
return mu.Unlock
}
// prepare validates configuration and normalises the zone for API use.
func (p *Provider) prepare(zone string) (clientInterface, string, error) {
if p.APIToken == "" {
return nil, "", fmt.Errorf("njalla: APIToken is required")
}
return p.getClient(), strings.TrimSuffix(zone, "."), nil
}
// GetRecords lists all the records in the zone.
//
// DNSSEC-related records are not included. Record types libdns does not model
// are returned as [libdns.RR].
func (p *Provider) GetRecords(ctx context.Context, zone string) ([]libdns.Record, error) {
client, domain, err := p.prepare(zone)
if err != nil {
return nil, err
}
njallaRecords, err := listRecords(ctx, client, domain)
if err != nil {
return nil, err
}
records := make([]libdns.Record, 0, len(njallaRecords))
for _, rec := range njallaRecords {
converted, err := njallaRecordToLibdns(rec)
if err != nil {
return nil, fmt.Errorf("njalla: converting record %+v: %w", rec, err)
}
records = append(records, converted)
}
return records, nil
}
// listRecords fetches the raw record set for a domain.
func listRecords(ctx context.Context, client clientInterface, domain string) ([]njallaRecord, error) {
var resp listRecordsResponse
if err := client.call(ctx, "list-records", listRecordsRequest{Domain: domain}, &resp); err != nil {
return nil, fmt.Errorf("njalla: listing records for %q: %w", domain, err)
}
return resp.Records, nil
}
// AppendRecords adds records to the zone, leaving existing records untouched.
// It returns the records that were created.
func (p *Provider) AppendRecords(ctx context.Context, zone string, records []libdns.Record) ([]libdns.Record, error) {
client, domain, err := p.prepare(zone)
if err != nil {
return nil, err
}
created := make([]libdns.Record, 0, len(records))
for _, record := range records {
converted, err := libdnsRecordToNjalla(record, zone)
if err != nil {
return created, fmt.Errorf("njalla: %w", err)
}
result, err := addRecord(ctx, client, domain, converted)
if err != nil {
return created, err
}
created = append(created, result)
}
return created, nil
}
// addRecord creates one record and returns it in libdns form.
func addRecord(ctx context.Context, client clientInterface, domain string, rec njallaRecord) (libdns.Record, error) {
if err := rec.validateForWrite(); err != nil {
return nil, fmt.Errorf("njalla: %w", err)
}
var resp njallaRecord
if err := client.call(ctx, "add-record", rec.addRequest(domain), &resp); err != nil {
return nil, fmt.Errorf("njalla: adding %s record %q: %w", rec.Type, rec.Name, err)
}
converted, err := njallaRecordToLibdns(resp)
if err != nil {
return nil, fmt.Errorf("njalla: converting created record: %w", err)
}
return converted, nil
}
// SetRecords makes the given records the complete contents of their RRsets.
//
// For every (name, type) pair present in the input, the records supplied
// become the only records in the zone with that name and type: surplus records
// are deleted and missing ones created. Records with other names or types are
// left alone. Existing record IDs are reused where possible, so an RRset is
// never momentarily empty.
//
// DNSSEC records are not supported.
func (p *Provider) SetRecords(ctx context.Context, zone string, records []libdns.Record) ([]libdns.Record, error) {
client, domain, err := p.prepare(zone)
if err != nil {
return nil, err
}
if len(records) == 0 {
return nil, nil
}
unlock := p.lockZone(domain)
defer unlock()
// Group the desired records by the RRset they belong to, preserving the
// order the caller gave so results are deterministic.
type rrsetKey struct{ name, rrtype string }
var order []rrsetKey
desired := make(map[rrsetKey][]njallaRecord)
for _, record := range records {
converted, err := libdnsRecordToNjalla(record, zone)
if err != nil {
return nil, fmt.Errorf("njalla: %w", err)
}
key := rrsetKey{converted.Name, converted.Type}
if _, seen := desired[key]; !seen {
order = append(order, key)
}
desired[key] = append(desired[key], converted)
}
existingRecords, err := listRecords(ctx, client, domain)
if err != nil {
return nil, err
}
existing := make(map[rrsetKey][]njallaRecord)
for _, rec := range existingRecords {
key := rrsetKey{rec.Name, rec.Type}
existing[key] = append(existing[key], rec)
}
results := make([]libdns.Record, 0, len(records))
for _, key := range order {
want := desired[key]
have := existing[key]
// Update in place for as many records as both sides have, then create
// or delete to make up the difference.
for i, rec := range want {
if i < len(have) {
current := have[i]
if sameRecord(current, rec) {
converted, err := njallaRecordToLibdns(current)
if err != nil {
return results, fmt.Errorf("njalla: converting record: %w", err)
}
results = append(results, converted)
continue
}
if err := rec.validateForWrite(); err != nil {
return results, fmt.Errorf("njalla: %w", err)
}
var resp njallaRecord
if err := client.call(ctx, "edit-record", rec.editRequest(domain, current.ID), &resp); err != nil {
return results, fmt.Errorf("njalla: updating %s record %q: %w", rec.Type, rec.Name, err)
}
converted, err := njallaRecordToLibdns(resp)
if err != nil {
return results, fmt.Errorf("njalla: converting updated record: %w", err)
}
results = append(results, converted)
continue
}
result, err := addRecord(ctx, client, domain, rec)
if err != nil {
return results, err
}
results = append(results, result)
}
// Anything left over in the zone is no longer part of the RRset.
for _, surplus := range have[min(len(want), len(have)):] {
req := removeRecordRequest{Domain: domain, ID: surplus.ID}
if err := client.call(ctx, "remove-record", req, nil); err != nil && !IsNotFound(err) {
return results, fmt.Errorf("njalla: removing superseded %s record %q: %w",
surplus.Type, surplus.Name, err)
}
}
}
return results, nil
}
// sameRecord reports whether an existing record already matches what is
// wanted, so an unnecessary edit-record call can be skipped. A nil desired TTL
// means the caller expressed no preference, so the stored TTL is accepted.
func sameRecord(existing, want njallaRecord) bool {
if existing.Type != want.Type ||
existing.Name != want.Name ||
existing.Content != want.Content ||
existing.Target != want.Target ||
existing.Value != want.Value {
return false
}
if want.TTL != nil && derefInt(existing.TTL) != *want.TTL {
return false
}
for _, pair := range [][2]*int{
{existing.Prio, want.Prio},
{existing.Weight, want.Weight},
{existing.Port, want.Port},
} {
if pair[1] != nil && derefInt(pair[0]) != *pair[1] {
return false
}
}
return true
}
// DeleteRecords deletes records from the zone, returning those that were
// deleted. Records that do not exist are silently ignored.
//
// Deletion matches on name, type, and value. Leaving the value empty deletes
// every record with that name and type, and leaving the type empty deletes
// every record with that name; per the libdns contract, TTL is not part of the
// match. Njalla performs the matching itself, so no listing is required and
// this works with tokens that are restricted to the ACME challenge prefix. The
// one exception is deleting by name alone, which needs a listing because the
// API requires a type.
func (p *Provider) DeleteRecords(ctx context.Context, zone string, records []libdns.Record) ([]libdns.Record, error) {
client, domain, err := p.prepare(zone)
if err != nil {
return nil, err
}
deleted := make([]libdns.Record, 0, len(records))
for _, record := range records {
removed, err := p.deleteRecord(ctx, client, domain, zone, record)
if err != nil {
return deleted, err
}
deleted = append(deleted, removed...)
}
return deleted, nil
}
// deleteRecord removes everything matching a single input record.
func (p *Provider) deleteRecord(ctx context.Context, client clientInterface, domain, zone string, record libdns.Record) ([]libdns.Record, error) {
rr := concrete(record).RR()
// A known provider ID identifies the record exactly; no matching needed.
if id := recordID(record); id != "" {
return removeRecords(ctx, client, removeRecordRequest{Domain: domain, ID: id})
}
// Njalla requires a type in order to match on fields, so deleting by name
// alone falls back to listing and removing each match by ID.
if rr.Type == "" {
return p.deleteByName(ctx, client, domain, zone, rr.Name)
}
converted, err := libdnsRecordToNjalla(record, zone)
if err != nil {
return nil, fmt.Errorf("njalla: %w", err)
}
req := removeRecordRequest{
Domain: domain,
Name: converted.Name,
Type: converted.Type,
}
// An empty value means "any value" in the libdns contract, which maps onto
// omitting the identifying fields so Njalla removes the whole RRset.
if rr.Data != "" {
req.Content = converted.Content
req.Prio = converted.Prio
req.Weight = converted.Weight
req.Port = converted.Port
req.Target = converted.Target
req.Value = converted.Value
}
removed, err := removeRecords(ctx, client, req)
if err != nil {
return nil, err
}
if len(removed) > 0 || rr.Data == "" {
return removed, nil
}
// Njalla stores hostnames exactly as they were entered and matches them
// byte-for-byte, so a record created without a trailing dot is not matched
// by a request carrying one, and vice versa. Both spellings denote the
// same name, so try the other one before concluding it is absent.
if alt, ok := toggleTrailingDot(req.Content); ok {
req.Content = alt
return removeRecords(ctx, client, req)
}
if alt, ok := toggleTrailingDot(req.Target); ok {
req.Target = alt
return removeRecords(ctx, client, req)
}
return nil, nil
}
// deleteByName removes every record with the given name, which the libdns
// contract allows when the caller leaves the type empty.
func (p *Provider) deleteByName(ctx context.Context, client clientInterface, domain, zone, name string) ([]libdns.Record, error) {
relative := libdns.RelativeName(name, zone)
if relative == "" {
relative = "@"
}
existing, err := listRecords(ctx, client, domain)
if err != nil {
return nil, err
}
var deleted []libdns.Record
for _, rec := range existing {
if rec.Name != relative {
continue
}
removed, err := removeRecords(ctx, client, removeRecordRequest{Domain: domain, ID: rec.ID})
if err != nil {
return deleted, err
}
deleted = append(deleted, removed...)
}
return deleted, nil
}
// removeRecords issues a remove-record call and converts whatever the API
// reports as removed. A "not found" response means nothing matched, which the
// libdns contract requires be treated as success with no records deleted.
func removeRecords(ctx context.Context, client clientInterface, req removeRecordRequest) ([]libdns.Record, error) {
var resp removeRecordResponse
if err := client.call(ctx, "remove-record", req, &resp); err != nil {
if IsNotFound(err) {
return nil, nil
}
return nil, fmt.Errorf("njalla: removing record %q: %w", req.Name, err)
}
// Deleting by ID returns no record list, so report the request's own
// target rather than nothing at all.
if len(resp.Records) == 0 && req.ID != "" {
return nil, nil
}
deleted := make([]libdns.Record, 0, len(resp.Records))
for _, rec := range resp.Records {
converted, err := njallaRecordToLibdns(rec)
if err != nil {
return deleted, fmt.Errorf("njalla: converting deleted record: %w", err)
}
deleted = append(deleted, converted)
}
return deleted, nil
}
// toggleTrailingDot returns the other spelling of a hostname value, and
// whether one exists. Values that are empty, or that are not hostname-shaped,
// have no alternative spelling.
func toggleTrailingDot(value string) (string, bool) {
if value == "" || value == "." {
return "", false
}
if strings.HasSuffix(value, ".") {
return strings.TrimSuffix(value, "."), true
}
// Only hostname-like values have a meaningful trailing-dot form.
if strings.ContainsAny(value, " \t") || !strings.Contains(value, ".") {
return "", false
}
return value + ".", true
}
// ListZones returns the domains available to the API token.
func (p *Provider) ListZones(ctx context.Context) ([]libdns.Zone, error) {
if p.APIToken == "" {
return nil, fmt.Errorf("njalla: APIToken is required")
}
var resp listDomainsResponse
if err := p.getClient().call(ctx, "list-domains", struct{}{}, &resp); err != nil {
return nil, fmt.Errorf("njalla: listing domains: %w", err)
}
zones := make([]libdns.Zone, 0, len(resp.Domains))
for _, domain := range resp.Domains {
if domain.Name == "" {
continue
}
// libdns zone names are fully qualified.
zones = append(zones, libdns.Zone{Name: domain.Name + "."})
}
return zones, nil
}
// Interface guards
var (
_ libdns.RecordGetter = (*Provider)(nil)
_ libdns.RecordAppender = (*Provider)(nil)
_ libdns.RecordSetter = (*Provider)(nil)
_ libdns.RecordDeleter = (*Provider)(nil)
_ libdns.ZoneLister = (*Provider)(nil)
)