-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathprovider_test.go
More file actions
692 lines (630 loc) · 24.3 KB
/
Copy pathprovider_test.go
File metadata and controls
692 lines (630 loc) · 24.3 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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
package njalla
import (
"context"
"errors"
"fmt"
"net/netip"
"reflect"
"sort"
"strings"
"testing"
"time"
"github.com/libdns/libdns"
)
// All fixtures in this file mirror responses captured from the live Njalla
// API, including its habit of omitting fields that do not apply to a type.
func TestGetRecords(t *testing.T) {
mock := newMockClient().reply("list-records", map[string]any{
"records": []map[string]any{
{"id": "1", "name": "www", "type": "A", "content": "192.0.2.1", "ttl": 3600},
{"id": "2", "name": "@", "type": "MX", "content": "mail.example.com", "ttl": 3600, "prio": 10},
{"id": "3", "name": "_sip._tcp", "type": "SRV", "content": "srv.example.com.", "ttl": 3600, "prio": 10, "weight": 5, "port": 5060},
{"id": "4", "name": "@", "type": "HTTPS", "content": "", "ttl": 10800, "prio": 1, "target": "svc.example.com.", "value": "alpn=h2"},
{"id": "5", "name": "@", "type": "TXT", "content": "hello world", "ttl": 300},
{"id": "6", "name": "@", "type": "CAA", "content": `0 issue "letsencrypt.org"`, "ttl": 3600},
{"id": "7", "name": "ns", "type": "NS", "content": "ns1.example.com.", "ttl": 3600},
// Njalla proprietary pseudo-type, with a null ttl.
{"id": "8", "name": "@", "type": "Redirect", "content": "https://example.org", "ttl": nil, "prio": 302},
},
})
records, err := newTestProvider(mock).GetRecords(context.Background(), "example.com.")
if err != nil {
t.Fatalf("GetRecords: %v", err)
}
if len(records) != 8 {
t.Fatalf("expected 8 records, got %d", len(records))
}
// libdns asks implementations to return the concrete struct for each RR
// type rather than the opaque RR, so callers can type-switch reliably.
wantTypes := []any{
libdns.Address{}, libdns.MX{}, libdns.SRV{}, libdns.ServiceBinding{},
libdns.TXT{}, libdns.CAA{}, libdns.NS{}, libdns.RR{},
}
for i, want := range wantTypes {
if reflect.TypeOf(records[i]) != reflect.TypeOf(want) {
t.Errorf("record %d: got %T, want %T", i, records[i], want)
}
}
// An HTTPS record must report itself as HTTPS, not SVCB.
sb, ok := records[3].(libdns.ServiceBinding)
if !ok {
t.Fatalf("record 3: got %T", records[3])
}
if got := sb.RR().Type; got != "HTTPS" {
t.Errorf("HTTPS record reported as %q", got)
}
if sb.Scheme != "https" {
t.Errorf("HTTPS record Scheme = %q, want %q", sb.Scheme, "https")
}
if sb.Target != "svc.example.com." {
t.Errorf("HTTPS Target = %q", sb.Target)
}
if got := sb.Params.String(); got != "alpn=h2" {
t.Errorf("HTTPS Params = %q", got)
}
// Structured fields must survive the round trip through Njalla's split
// representation.
mx := records[1].(libdns.MX)
if mx.Preference != 10 || mx.Target != "mail.example.com" {
t.Errorf("MX = %+v", mx)
}
srv := records[2].(libdns.SRV)
if srv.Priority != 10 || srv.Weight != 5 || srv.Port != 5060 || srv.Target != "srv.example.com." {
t.Errorf("SRV = %+v", srv)
}
caa := records[5].(libdns.CAA)
if caa.Tag != "issue" || caa.Value != "letsencrypt.org" {
t.Errorf("CAA = %+v", caa)
}
// A null TTL must not become a parse failure.
if got := records[7].RR().TTL; got != 0 {
t.Errorf("Redirect TTL = %v, want 0", got)
}
// Provider IDs must be attached so later calls can skip the lookup.
if got := recordID(records[0]); got != "1" {
t.Errorf("record 0 ID = %q, want %q", got, "1")
}
}
func TestGetRecordsRequiresToken(t *testing.T) {
var p Provider
if _, err := p.GetRecords(context.Background(), "example.com"); err == nil {
t.Fatal("expected an error when APIToken is unset")
}
}
func TestAppendRecords(t *testing.T) {
mock := newMockClient().on("add-record", func(p map[string]any) (any, error) {
return map[string]any{
"id": "99", "name": p["name"], "type": p["type"],
"content": p["content"], "ttl": 300,
}, nil
})
created, err := newTestProvider(mock).AppendRecords(context.Background(), "example.com.", []libdns.Record{
libdns.Address{Name: "www", TTL: 5 * time.Minute, IP: netip.MustParseAddr("192.0.2.1")},
})
if err != nil {
t.Fatalf("AppendRecords: %v", err)
}
if len(created) != 1 {
t.Fatalf("expected 1 record, got %d", len(created))
}
if got := recordID(created[0]); got != "99" {
t.Errorf("created record ID = %q", got)
}
call := mock.callsTo("add-record")[0]
if got := param(t, call, "domain"); got != "example.com" {
t.Errorf("domain = %v, want example.com (no trailing dot)", got)
}
if got := param(t, call, "ttl"); got != float64(300) {
t.Errorf("ttl = %v, want 300", got)
}
}
// libdns requires implementations to accept any Record value, including the
// opaque RR struct. Structured types must be parsed out of its Data field
// rather than shoved into `content` whole.
func TestAppendRecordsAcceptsOpaqueRR(t *testing.T) {
cases := []struct {
name string
input libdns.RR
want map[string]any
}{
{
name: "MX",
input: libdns.RR{Name: "@", Type: "MX", Data: "10 mail.example.com.", TTL: time.Hour},
want: map[string]any{"content": "mail.example.com.", "prio": float64(10)},
},
{
name: "SRV",
input: libdns.RR{Name: "_sip._tcp", Type: "SRV", Data: "10 5 5060 srv.example.com.", TTL: time.Hour},
want: map[string]any{
"content": "srv.example.com.", "prio": float64(10),
"weight": float64(5), "port": float64(5060),
},
},
{
name: "HTTPS",
input: libdns.RR{Name: "@", Type: "HTTPS", Data: "1 svc.example.com. alpn=h2", TTL: time.Hour},
want: map[string]any{"target": "svc.example.com.", "prio": float64(1), "value": "alpn=h2"},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
mock := newMockClient().on("add-record", func(p map[string]any) (any, error) {
return map[string]any{"id": "1", "name": p["name"], "type": p["type"], "ttl": 3600}, nil
})
_, err := newTestProvider(mock).AppendRecords(context.Background(), "example.com",
[]libdns.Record{tc.input})
if err != nil {
t.Fatalf("AppendRecords: %v", err)
}
call := mock.callsTo("add-record")[0]
for key, want := range tc.want {
if got := call.Params[key]; got != want {
t.Errorf("%s = %#v, want %#v", key, got, want)
}
}
})
}
}
// Njalla requires prio for MX/HTTPS/SVCB and accepts 0 for SRV priority,
// weight and port, so a meaningful zero must be transmitted, not dropped.
func TestAppendRecordsTransmitsZeroValues(t *testing.T) {
mock := newMockClient().on("add-record", func(p map[string]any) (any, error) {
return map[string]any{"id": "1", "name": p["name"], "type": p["type"], "ttl": 3600}, nil
})
_, err := newTestProvider(mock).AppendRecords(context.Background(), "example.com", []libdns.Record{
libdns.SRV{
Name: "@", Service: "sip", Transport: "tcp", TTL: time.Hour,
Priority: 0, Weight: 0, Port: 0, Target: "srv.example.com.",
},
})
if err != nil {
t.Fatalf("AppendRecords: %v", err)
}
call := mock.callsTo("add-record")[0]
for _, key := range []string{"prio", "weight", "port"} {
got, present := call.Params[key]
if !present {
t.Errorf("%s was omitted; Njalla would reject the record", key)
continue
}
if got != float64(0) {
t.Errorf("%s = %v, want 0", key, got)
}
}
}
func TestAppendRecordsTTLHandling(t *testing.T) {
cases := []struct {
name string
ttl time.Duration
wantTTL any
present bool
}{
// libdns: a TTL of 0 lets the provider apply its own default.
{"zero omits ttl", 0, nil, false},
// libdns suggests a sub-second duration to mean "do not cache".
{"sub-second sends 0", 500 * time.Millisecond, float64(0), true},
{"normal", 2 * time.Minute, float64(120), true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
mock := newMockClient().on("add-record", func(p map[string]any) (any, error) {
return map[string]any{"id": "1", "name": p["name"], "type": "TXT", "ttl": 300}, nil
})
_, err := newTestProvider(mock).AppendRecords(context.Background(), "example.com",
[]libdns.Record{libdns.TXT{Name: "t", TTL: tc.ttl, Text: "v"}})
if err != nil {
t.Fatalf("AppendRecords: %v", err)
}
got, present := mock.callsTo("add-record")[0].Params["ttl"]
if present != tc.present {
t.Fatalf("ttl present = %v, want %v", present, tc.present)
}
if present && got != tc.wantTTL {
t.Errorf("ttl = %v, want %v", got, tc.wantTTL)
}
})
}
}
// Njalla rejects these outright; the provider should say why rather than
// letting the API return a generic "Invalid DNS record".
func TestAppendRecordsRejectsValuesNjallaWillNotStore(t *testing.T) {
cases := []struct {
name string
record libdns.Record
wantErr string
}{
{"empty TXT", libdns.TXT{Name: "t", Text: ""}, "empty TXT"},
{"TXT with quote", libdns.TXT{Name: "t", Text: `say "hi"`}, "double quote"},
{"MX preference 0", libdns.MX{Name: "@", Preference: 0, Target: "mail.example.com"}, "preference 0"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
mock := newMockClient()
_, err := newTestProvider(mock).AppendRecords(context.Background(), "example.com",
[]libdns.Record{tc.record})
if err == nil {
t.Fatal("expected an error")
}
if !strings.Contains(err.Error(), tc.wantErr) {
t.Errorf("error = %v, want it to mention %q", err, tc.wantErr)
}
if len(mock.callsTo("add-record")) != 0 {
t.Error("the API should not be called for a record it will reject")
}
})
}
}
// SetRecords must make the input the complete contents of each RRset: libdns
// specifies that for any (name, type) in the input, those records become the
// only ones in the zone with that name and type.
func TestSetRecordsReplacesWholeRRset(t *testing.T) {
mock := newMockClient().
reply("list-records", map[string]any{"records": []map[string]any{
{"id": "A1", "name": "www", "type": "A", "content": "192.0.2.1", "ttl": 3600},
{"id": "A2", "name": "www", "type": "A", "content": "192.0.2.2", "ttl": 3600},
{"id": "A3", "name": "www", "type": "A", "content": "192.0.2.3", "ttl": 3600},
{"id": "T1", "name": "www", "type": "TXT", "content": "untouched", "ttl": 3600},
}}).
on("edit-record", func(p map[string]any) (any, error) {
return map[string]any{"id": p["id"], "name": p["name"], "type": p["type"],
"content": p["content"], "ttl": 3600}, nil
}).
on("add-record", func(p map[string]any) (any, error) {
return map[string]any{"id": "NEW", "name": p["name"], "type": p["type"],
"content": p["content"], "ttl": 3600}, nil
}).
reply("remove-record", map[string]any{"status": "removed"})
got, err := newTestProvider(mock).SetRecords(context.Background(), "example.com", []libdns.Record{
libdns.Address{Name: "www", TTL: time.Hour, IP: netip.MustParseAddr("192.0.2.9")},
libdns.Address{Name: "www", TTL: time.Hour, IP: netip.MustParseAddr("192.0.2.8")},
})
if err != nil {
t.Fatalf("SetRecords: %v", err)
}
// Two desired records against three existing: reuse two IDs, delete one.
edits := mock.callsTo("edit-record")
if len(edits) != 2 {
t.Fatalf("expected 2 edits, got %d", len(edits))
}
editedIDs := []string{edits[0].Params["id"].(string), edits[1].Params["id"].(string)}
sort.Strings(editedIDs)
if !reflect.DeepEqual(editedIDs, []string{"A1", "A2"}) {
t.Errorf("edited IDs = %v, want [A1 A2]; each existing record must be used once", editedIDs)
}
removes := mock.callsTo("remove-record")
if len(removes) != 1 {
t.Fatalf("expected 1 removal, got %d", len(removes))
}
if id := removes[0].Params["id"]; id != "A3" {
t.Errorf("removed %v, want the surplus record A3", id)
}
// The TXT record at the same name is a different RRset and must survive.
for _, c := range removes {
if c.Params["id"] == "T1" {
t.Error("removed the TXT record; only the A RRset was in the input")
}
}
var contents []string
for _, r := range got {
contents = append(contents, r.RR().Data)
}
sort.Strings(contents)
if !reflect.DeepEqual(contents, []string{"192.0.2.8", "192.0.2.9"}) {
t.Errorf("returned %v, want the two requested addresses", contents)
}
}
func TestSetRecordsCreatesWhenRRsetIsLarger(t *testing.T) {
mock := newMockClient().
reply("list-records", map[string]any{"records": []map[string]any{
{"id": "A1", "name": "www", "type": "A", "content": "192.0.2.1", "ttl": 3600},
}}).
on("edit-record", func(p map[string]any) (any, error) {
return map[string]any{"id": p["id"], "name": p["name"], "type": p["type"],
"content": p["content"], "ttl": 3600}, nil
}).
on("add-record", func(p map[string]any) (any, error) {
return map[string]any{"id": "NEW", "name": p["name"], "type": p["type"],
"content": p["content"], "ttl": 3600}, nil
})
got, err := newTestProvider(mock).SetRecords(context.Background(), "example.com", []libdns.Record{
libdns.Address{Name: "www", TTL: time.Hour, IP: netip.MustParseAddr("192.0.2.1")},
libdns.Address{Name: "www", TTL: time.Hour, IP: netip.MustParseAddr("192.0.2.2")},
})
if err != nil {
t.Fatalf("SetRecords: %v", err)
}
if len(got) != 2 {
t.Fatalf("expected 2 records, got %d", len(got))
}
// The first is already correct, so it should not be rewritten.
if n := len(mock.callsTo("edit-record")); n != 0 {
t.Errorf("expected no edits for an already-correct record, got %d", n)
}
if n := len(mock.callsTo("add-record")); n != 1 {
t.Errorf("expected 1 add, got %d", n)
}
}
func TestSetRecordsCreatesMissingRRset(t *testing.T) {
mock := newMockClient().
reply("list-records", map[string]any{"records": []map[string]any{}}).
on("add-record", func(p map[string]any) (any, error) {
return map[string]any{"id": "NEW", "name": p["name"], "type": p["type"],
"content": p["content"], "ttl": 300}, nil
})
got, err := newTestProvider(mock).SetRecords(context.Background(), "example.com", []libdns.Record{
libdns.TXT{Name: "_acme-challenge", TTL: 5 * time.Minute, Text: "token"},
})
if err != nil {
t.Fatalf("SetRecords: %v", err)
}
if len(got) != 1 {
t.Fatalf("expected 1 record, got %d", len(got))
}
if n := len(mock.callsTo("remove-record")); n != 0 {
t.Errorf("expected no removals, got %d", n)
}
}
// The bug reported in libdns/njalla#4: with several records sharing a name and
// type, deletion must select the one whose value matches.
func TestDeleteRecordsMatchesOnValue(t *testing.T) {
mock := newMockClient().on("remove-record", func(p map[string]any) (any, error) {
if p["content"] != "target-token" {
return nil, &APIError{Code: 404, Message: "not found"}
}
return map[string]any{"status": "removed", "records": []map[string]any{
{"id": "222", "name": "_acme-challenge", "type": "TXT",
"content": "target-token", "ttl": 120},
}}, nil
})
deleted, err := newTestProvider(mock).DeleteRecords(context.Background(), "example.com", []libdns.Record{
libdns.RR{Name: "_acme-challenge", Type: "TXT", Data: "target-token", TTL: 120 * time.Second},
})
if err != nil {
t.Fatalf("DeleteRecords: %v", err)
}
if len(deleted) != 1 {
t.Fatalf("expected 1 deleted record, got %d", len(deleted))
}
if got := deleted[0].RR().Data; got != "target-token" {
t.Errorf("deleted %q, want target-token", got)
}
// The match is delegated to Njalla, so no listing is needed. This is what
// lets deletion work with tokens restricted to the ACME challenge prefix.
if n := len(mock.callsTo("list-records")); n != 0 {
t.Errorf("expected no list-records call, got %d", n)
}
call := mock.callsTo("remove-record")[0]
if call.Params["name"] != "_acme-challenge" || call.Params["type"] != "TXT" {
t.Errorf("unexpected match fields: %+v", call.Params)
}
// TTL is explicitly not part of the libdns delete match.
if _, present := call.Params["ttl"]; present {
t.Error("ttl must not be sent; it is not part of the match")
}
}
// Deletion by provider ID is the fast path when the caller round-trips a
// record returned by this package.
func TestDeleteRecordsUsesProviderID(t *testing.T) {
mock := newMockClient().reply("remove-record", map[string]any{"status": "removed"})
record := withRecordID(libdns.TXT{Name: "t", Text: "v", TTL: time.Minute}, RecordID("4242"))
_, err := newTestProvider(mock).DeleteRecords(context.Background(), "example.com",
[]libdns.Record{record})
if err != nil {
t.Fatalf("DeleteRecords: %v", err)
}
call := mock.callsTo("remove-record")[0]
if call.Params["id"] != "4242" {
t.Errorf("id = %v, want 4242", call.Params["id"])
}
if _, present := call.Params["name"]; present {
t.Error("name should not be sent when the record ID is known")
}
}
// libdns: leaving the value empty matches any value for that name and type.
func TestDeleteRecordsEmptyValueRemovesWholeRRset(t *testing.T) {
mock := newMockClient().reply("remove-record", map[string]any{
"status": "removed", "records": []map[string]any{
{"id": "T1", "name": "_acme-challenge", "type": "TXT", "content": "tok1", "ttl": 120},
{"id": "T2", "name": "_acme-challenge", "type": "TXT", "content": "tok2", "ttl": 120},
},
})
deleted, err := newTestProvider(mock).DeleteRecords(context.Background(), "example.com",
[]libdns.Record{libdns.RR{Name: "_acme-challenge", Type: "TXT"}})
if err != nil {
t.Fatalf("DeleteRecords: %v", err)
}
if len(deleted) != 2 {
t.Fatalf("expected both records deleted, got %d", len(deleted))
}
call := mock.callsTo("remove-record")[0]
if _, present := call.Params["content"]; present {
t.Error("content must be omitted so Njalla removes the whole RRset")
}
}
// libdns: leaving the type empty matches any type for that name. Njalla needs
// a type to match on fields, so this path lists and removes by ID.
func TestDeleteRecordsEmptyTypeRemovesEveryTypeAtName(t *testing.T) {
mock := newMockClient().
reply("list-records", map[string]any{"records": []map[string]any{
{"id": "1", "name": "multi", "type": "A", "content": "192.0.2.1", "ttl": 300},
{"id": "2", "name": "multi", "type": "TXT", "content": "text", "ttl": 300},
{"id": "3", "name": "other", "type": "A", "content": "192.0.2.2", "ttl": 300},
}}).
on("remove-record", func(p map[string]any) (any, error) {
return map[string]any{"status": "removed", "records": []map[string]any{
{"id": p["id"], "name": "multi", "type": "A", "content": "192.0.2.1", "ttl": 300},
}}, nil
})
deleted, err := newTestProvider(mock).DeleteRecords(context.Background(), "example.com",
[]libdns.Record{libdns.RR{Name: "multi"}})
if err != nil {
t.Fatalf("DeleteRecords: %v", err)
}
if len(deleted) != 2 {
t.Fatalf("expected 2 deleted records, got %d", len(deleted))
}
var ids []string
for _, c := range mock.callsTo("remove-record") {
ids = append(ids, c.Params["id"].(string))
}
sort.Strings(ids)
if !reflect.DeepEqual(ids, []string{"1", "2"}) {
t.Errorf("removed %v, want records 1 and 2 only", ids)
}
}
// libdns: records that do not exist are silently ignored. Njalla reports a 404.
func TestDeleteRecordsIgnoresMissingRecords(t *testing.T) {
mock := newMockClient().fail("remove-record", &APIError{Code: 404, Message: "not found"})
deleted, err := newTestProvider(mock).DeleteRecords(context.Background(), "example.com",
[]libdns.Record{libdns.TXT{Name: "gone", Text: "nothing", TTL: time.Minute}})
if err != nil {
t.Fatalf("a missing record must not be an error, got %v", err)
}
if len(deleted) != 0 {
t.Errorf("expected nothing deleted, got %d", len(deleted))
}
}
func TestDeleteRecordsPropagatesRealErrors(t *testing.T) {
mock := newMockClient().fail("remove-record", &APIError{Code: 403, Message: "forbidden"})
_, err := newTestProvider(mock).DeleteRecords(context.Background(), "example.com",
[]libdns.Record{libdns.TXT{Name: "t", Text: "v", TTL: time.Minute}})
if err == nil {
t.Fatal("expected the error to be reported")
}
var apiErr *APIError
if !errors.As(err, &apiErr) || apiErr.Code != 403 {
t.Errorf("error = %v, want the underlying APIError to be retrievable", err)
}
}
// Njalla stores hostnames verbatim and matches them byte-for-byte, so the two
// spellings of the same name must both find the record.
func TestDeleteRecordsToleratesTrailingDotMismatch(t *testing.T) {
cases := []struct {
name string
storedTarget string
callerTarget string
}{
{"stored without dot, caller with", "target.example.com", "target.example.com."},
{"stored with dot, caller without", "target.example.com.", "target.example.com"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
mock := newMockClient().on("remove-record", func(p map[string]any) (any, error) {
if p["content"] != tc.storedTarget {
return nil, &APIError{Code: 404, Message: "not found"}
}
return map[string]any{"status": "removed", "records": []map[string]any{
{"id": "C1", "name": "www", "type": "CNAME",
"content": tc.storedTarget, "ttl": 3600},
}}, nil
})
deleted, err := newTestProvider(mock).DeleteRecords(context.Background(), "example.com",
[]libdns.Record{libdns.CNAME{Name: "www", TTL: time.Hour, Target: tc.callerTarget}})
if err != nil {
t.Fatalf("DeleteRecords: %v", err)
}
if len(deleted) != 1 {
t.Fatalf("expected the record to be found, got %d deleted", len(deleted))
}
})
}
}
// A record created by AppendRecords and then stripped of provider data by
// RR() must still be deletable. This is the CertMagic DNS-01 cleanup path.
func TestDeleteRecordsAfterAppendRecordsRR(t *testing.T) {
mock := newMockClient().
on("add-record", func(p map[string]any) (any, error) {
return map[string]any{"id": "321", "name": p["name"], "type": p["type"],
"content": p["content"], "ttl": 120}, nil
}).
on("remove-record", func(p map[string]any) (any, error) {
if p["content"] != "target-token" {
return nil, &APIError{Code: 404, Message: "not found"}
}
return map[string]any{"status": "removed", "records": []map[string]any{
{"id": "321", "name": "_acme-challenge", "type": "TXT",
"content": "target-token", "ttl": 120},
}}, nil
})
provider := newTestProvider(mock)
created, err := provider.AppendRecords(context.Background(), "example.com.", []libdns.Record{
libdns.TXT{Name: "_acme-challenge", TTL: 2 * time.Minute, Text: "target-token"},
})
if err != nil {
t.Fatalf("AppendRecords: %v", err)
}
// RR() deliberately drops ProviderData, so this is the portable form.
cleanup := created[0].RR()
deleted, err := provider.DeleteRecords(context.Background(), "example.com.", []libdns.Record{cleanup})
if err != nil {
t.Fatalf("DeleteRecords: %v", err)
}
if len(deleted) != 1 {
t.Fatalf("expected 1 deleted record, got %d", len(deleted))
}
}
func TestListZones(t *testing.T) {
mock := newMockClient().reply("list-domains", map[string]any{
"domains": []map[string]any{
{"name": "example.com", "status": "active"},
{"name": "example.net", "status": "active"},
},
})
zones, err := newTestProvider(mock).ListZones(context.Background())
if err != nil {
t.Fatalf("ListZones: %v", err)
}
want := []libdns.Zone{{Name: "example.com."}, {Name: "example.net."}}
if !reflect.DeepEqual(zones, want) {
t.Errorf("zones = %+v, want %+v (fully qualified)", zones, want)
}
}
// The provider must remain usable when the token is set after construction,
// which a sync.Once that returns early would prevent.
func TestClientIsBuiltAfterTokenIsSet(t *testing.T) {
p := &Provider{}
if _, err := p.GetRecords(context.Background(), "example.com"); err == nil {
t.Fatal("expected an error with no token")
}
p.APIToken = "set-later"
if c := p.getClient(); c == nil {
t.Fatal("client is nil after the token was set")
}
}
func TestZoneNameNormalisation(t *testing.T) {
for _, zone := range []string{"example.com", "example.com."} {
mock := newMockClient().reply("list-records", map[string]any{"records": []map[string]any{}})
if _, err := newTestProvider(mock).GetRecords(context.Background(), zone); err != nil {
t.Fatalf("GetRecords(%q): %v", zone, err)
}
if got := mock.callsTo("list-records")[0].Params["domain"]; got != "example.com" {
t.Errorf("zone %q sent as %v, want example.com", zone, got)
}
}
}
func TestConcurrentSetRecordsAreSerialised(t *testing.T) {
mock := newMockClient().
reply("list-records", map[string]any{"records": []map[string]any{}}).
on("add-record", func(p map[string]any) (any, error) {
return map[string]any{"id": "1", "name": p["name"], "type": p["type"],
"content": p["content"], "ttl": 300}, nil
})
provider := newTestProvider(mock)
done := make(chan error, 4)
for i := range 4 {
go func(i int) {
_, err := provider.SetRecords(context.Background(), "example.com", []libdns.Record{
libdns.TXT{Name: fmt.Sprintf("t%d", i), TTL: time.Minute, Text: "v"},
})
done <- err
}(i)
}
for range 4 {
if err := <-done; err != nil {
t.Fatalf("SetRecords: %v", err)
}
}
if n := len(mock.callsTo("add-record")); n != 4 {
t.Errorf("expected 4 adds, got %d", n)
}
}