-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
Copy pathdns_test.go
3441 lines (3026 loc) · 85.5 KB
/
dns_test.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
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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1
package agent
/* Note: this file got to be 10k lines long and caused multiple IDE issues
* as well as GitHub's UI unable to display diffs with large changes to this file.
* This file has been broken up by moving:
* - Node Lookup tests into dns_node_lookup_test.go
* - Service Lookup tests into dn_service_lookup_test.go
*
* Please be aware of the size of each of these files and add tests / break
* up tests accordingly.
*/
import (
"context"
"errors"
"fmt"
"math"
"math/rand"
"net"
"reflect"
"strings"
"testing"
"time"
"github.com/miekg/dns"
"github.com/stretchr/testify/require"
"golang.org/x/sync/errgroup"
"github.com/hashicorp/serf/coordinate"
"github.com/hashicorp/consul/acl"
"github.com/hashicorp/consul/agent/config"
"github.com/hashicorp/consul/agent/consul"
"github.com/hashicorp/consul/agent/structs"
"github.com/hashicorp/consul/internal/gossip/librtt"
"github.com/hashicorp/consul/sdk/testutil/retry"
"github.com/hashicorp/consul/testrpc"
)
const (
configUDPAnswerLimit = 4
defaultNumUDPResponses = 3
testUDPTruncateLimit = 8
pctNodesWithIPv6 = 0.5
// generateNumNodes is the upper bounds for the number of hosts used
// in testing below. Generate an arbitrarily large number of hosts.
generateNumNodes = testUDPTruncateLimit * defaultNumUDPResponses * configUDPAnswerLimit
)
// makeRecursor creates a generic DNS server which always returns
// the provided reply. This is useful for mocking a DNS recursor with
// an expected result.
func makeRecursor(t *testing.T, answer dns.Msg) *dns.Server {
a := answer
mux := dns.NewServeMux()
mux.HandleFunc(".", func(resp dns.ResponseWriter, msg *dns.Msg) {
// The SetReply function sets the return code of the DNS
// query to SUCCESS
// We need a way to copy the variables not addressed
// in SetReply
answer.SetReply(msg)
answer.Rcode = a.Rcode
if err := resp.WriteMsg(&answer); err != nil {
t.Fatalf("err: %s", err)
}
})
up := make(chan struct{})
server := &dns.Server{
Addr: "127.0.0.1:0",
Net: "udp",
Handler: mux,
NotifyStartedFunc: func() { close(up) },
}
go server.ListenAndServe()
<-up
server.Addr = server.PacketConn.LocalAddr().String()
return server
}
// dnsCNAME returns a DNS CNAME record struct
func dnsCNAME(src, dest string) *dns.CNAME {
return &dns.CNAME{
Hdr: dns.RR_Header{
Name: dns.Fqdn(src),
Rrtype: dns.TypeCNAME,
Class: dns.ClassINET,
},
Target: dns.Fqdn(dest),
}
}
// dnsA returns a DNS A record struct
func dnsA(src, dest string) *dns.A {
return &dns.A{
Hdr: dns.RR_Header{
Name: dns.Fqdn(src),
Rrtype: dns.TypeA,
Class: dns.ClassINET,
},
A: net.ParseIP(dest),
}
}
// dnsTXT returns a DNS TXT record struct
func dnsTXT(src string, txt []string) *dns.TXT {
return &dns.TXT{
Hdr: dns.RR_Header{
Name: dns.Fqdn(src),
Rrtype: dns.TypeTXT,
Class: dns.ClassINET,
},
Txt: txt,
}
}
// Copied to agent/dns/recursor_test.go
func TestDNS_RecursorAddr(t *testing.T) {
addr, err := recursorAddr("8.8.8.8")
if err != nil {
t.Fatalf("err: %v", err)
}
if addr != "8.8.8.8:53" {
t.Fatalf("bad: %v", addr)
}
addr, err = recursorAddr("2001:4860:4860::8888")
if err != nil {
t.Fatalf("err: %v", err)
}
if addr != "[2001:4860:4860::8888]:53" {
t.Fatalf("bad: %v", addr)
}
_, err = recursorAddr("1.2.3.4::53")
if err == nil || !strings.Contains(err.Error(), "too many colons in address") {
t.Fatalf("err: %v", err)
}
_, err = recursorAddr("2001:4860:4860::8888:::53")
if err == nil || !strings.Contains(err.Error(), "too many colons in address") {
t.Fatalf("err: %v", err)
}
}
func TestDNS_EncodeKVasRFC1464(t *testing.T) {
// Test cases are from rfc1464
type rfc1464Test struct {
key, value, internalForm, externalForm string
}
tests := []rfc1464Test{
{"color", "blue", "color=blue", "color=blue"},
{"equation", "a=4", "equation=a=4", "equation=a=4"},
{"a=a", "true", "a`=a=true", "a`=a=true"},
{"a\\=a", "false", "a\\`=a=false", "a\\`=a=false"},
{"=", "\\=", "`==\\=", "`==\\="},
{"string", "\"Cat\"", "string=\"Cat\"", "string=\"Cat\""},
{"string2", "`abc`", "string2=``abc``", "string2=``abc``"},
{"novalue", "", "novalue=", "novalue="},
{"a b", "c d", "a b=c d", "a b=c d"},
{"abc ", "123 ", "abc` =123 ", "abc` =123 "},
// Additional tests
{" abc", " 321", "` abc= 321", "` abc= 321"},
{"`a", "b", "``a=b", "``a=b"},
}
for _, test := range tests {
answer := encodeKVasRFC1464(test.key, test.value)
require.Equal(t, test.internalForm, answer)
}
}
func TestDNS_Over_TCP(t *testing.T) {
if testing.Short() {
t.Skip("too slow for testing.Short")
}
a := NewTestAgent(t, "")
defer a.Shutdown()
testrpc.WaitForLeader(t, a.RPC, "dc1")
// Register node
args := &structs.RegisterRequest{
Datacenter: "dc1",
Node: "Foo",
Address: "127.0.0.1",
}
var out struct{}
if err := a.RPC(context.Background(), "Catalog.Register", args, &out); err != nil {
t.Fatalf("err: %v", err)
}
m := new(dns.Msg)
m.SetQuestion("foo.node.dc1.consul.", dns.TypeANY)
c := new(dns.Client)
c.Net = "tcp"
in, _, err := c.Exchange(m, a.DNSAddr())
if err != nil {
t.Fatalf("err: %v", err)
}
if len(in.Answer) != 1 {
t.Fatalf("empty lookup: %#v", in)
}
}
func TestDNS_EmptyAltDomain(t *testing.T) {
if testing.Short() {
t.Skip("too slow for testing.Short")
}
a := NewTestAgent(t, "")
defer a.Shutdown()
testrpc.WaitForLeader(t, a.RPC, "dc1")
m := new(dns.Msg)
m.SetQuestion("consul.service.", dns.TypeA)
c := new(dns.Client)
in, _, err := c.Exchange(m, a.DNSAddr())
require.NoError(t, err)
require.Empty(t, in.Answer)
}
func TestDNS_CycleRecursorCheck(t *testing.T) {
if testing.Short() {
t.Skip("too slow for testing.Short")
}
// Start a DNS recursor that returns a SERVFAIL
server1 := makeRecursor(t, dns.Msg{
MsgHdr: dns.MsgHdr{Rcode: dns.RcodeServerFailure},
})
// Start a DNS recursor that returns the result
defer server1.Shutdown()
server2 := makeRecursor(t, dns.Msg{
MsgHdr: dns.MsgHdr{Rcode: dns.RcodeSuccess},
Answer: []dns.RR{
dnsA("www.google.com", "172.21.45.67"),
},
})
defer server2.Shutdown()
// Mock the agent startup with the necessary configs
agent := NewTestAgent(t,
`recursors = ["`+server1.Addr+`", "`+server2.Addr+`"]
`)
defer agent.Shutdown()
// DNS Message init
m := new(dns.Msg)
m.SetQuestion("google.com.", dns.TypeA)
// Agent request
client := new(dns.Client)
in, _, _ := client.Exchange(m, agent.DNSAddr())
wantAnswer := []dns.RR{
&dns.A{
Hdr: dns.RR_Header{Name: "www.google.com.", Rrtype: dns.TypeA, Class: dns.ClassINET, Rdlength: 0x4},
A: []byte{0xAC, 0x15, 0x2D, 0x43}, // 172 , 21, 45, 67
},
}
require.NotNil(t, in)
require.Equal(t, wantAnswer, in.Answer)
}
func TestDNS_CycleRecursorCheckAllFail(t *testing.T) {
if testing.Short() {
t.Skip("too slow for testing.Short")
}
// Start 3 DNS recursors that returns a REFUSED status
server1 := makeRecursor(t, dns.Msg{
MsgHdr: dns.MsgHdr{Rcode: dns.RcodeRefused},
})
defer server1.Shutdown()
server2 := makeRecursor(t, dns.Msg{
MsgHdr: dns.MsgHdr{Rcode: dns.RcodeRefused},
})
defer server2.Shutdown()
server3 := makeRecursor(t, dns.Msg{
MsgHdr: dns.MsgHdr{Rcode: dns.RcodeRefused},
})
defer server3.Shutdown()
// Mock the agent startup with the necessary configs
agent := NewTestAgent(t,
`recursors = ["`+server1.Addr+`", "`+server2.Addr+`","`+server3.Addr+`"]
`)
defer agent.Shutdown()
// DNS dummy message initialization
m := new(dns.Msg)
m.SetQuestion("google.com.", dns.TypeA)
// Agent request
client := new(dns.Client)
in, _, err := client.Exchange(m, agent.DNSAddr())
require.NoError(t, err)
// Verify if we hit SERVFAIL from Consul
require.NotNil(t, in)
require.Equal(t, dns.RcodeServerFailure, in.Rcode)
}
func TestDNS_EDNS0(t *testing.T) {
if testing.Short() {
t.Skip("too slow for testing.Short")
}
a := NewTestAgent(t, "")
defer a.Shutdown()
testrpc.WaitForLeader(t, a.RPC, "dc1")
// Register node
args := &structs.RegisterRequest{
Datacenter: "dc1",
Node: "foo",
Address: "127.0.0.2",
}
var out struct{}
if err := a.RPC(context.Background(), "Catalog.Register", args, &out); err != nil {
t.Fatalf("err: %v", err)
}
m := new(dns.Msg)
m.SetEdns0(12345, true)
m.SetQuestion("foo.node.dc1.consul.", dns.TypeANY)
c := new(dns.Client)
in, _, err := c.Exchange(m, a.DNSAddr())
if err != nil {
t.Fatalf("err: %v", err)
}
if len(in.Answer) != 1 {
t.Fatalf("empty lookup: %#v", in)
}
edns := in.IsEdns0()
if edns == nil {
t.Fatalf("empty edns: %#v", in)
}
if edns.UDPSize() != 12345 {
t.Fatalf("bad edns size: %d", edns.UDPSize())
}
}
func TestDNS_EDNS0_ECS(t *testing.T) {
if testing.Short() {
t.Skip("too slow for testing.Short")
}
a := NewTestAgent(t, "")
defer a.Shutdown()
testrpc.WaitForLeader(t, a.RPC, "dc1")
// Register a node with a service.
{
args := &structs.RegisterRequest{
Datacenter: "dc1",
Node: "foo",
Address: "127.0.0.1",
Service: &structs.NodeService{
Service: "db",
Tags: []string{"primary"},
Port: 12345,
},
}
var out struct{}
require.NoError(t, a.RPC(context.Background(), "Catalog.Register", args, &out))
}
// Register an equivalent prepared query.
var id string
{
args := &structs.PreparedQueryRequest{
Datacenter: "dc1",
Op: structs.PreparedQueryCreate,
Query: &structs.PreparedQuery{
Name: "test",
Service: structs.ServiceQuery{
Service: "db",
},
},
}
require.NoError(t, a.RPC(context.Background(), "PreparedQuery.Apply", args, &id))
}
cases := []struct {
Name string
Question string
SubnetAddr string
SourceNetmask uint8
ExpectedScope uint8
}{
{"global", "db.service.consul.", "198.18.0.1", 32, 0},
{"query", "test.query.consul.", "198.18.0.1", 32, 32},
{"query-subnet", "test.query.consul.", "198.18.0.0", 21, 21},
}
for _, tc := range cases {
t.Run(tc.Name, func(t *testing.T) {
c := new(dns.Client)
// Query the service directly - should have a globally valid scope (0)
m := new(dns.Msg)
edns := new(dns.OPT)
edns.Hdr.Name = "."
edns.Hdr.Rrtype = dns.TypeOPT
edns.SetUDPSize(12345)
edns.SetDo(true)
subnetOp := new(dns.EDNS0_SUBNET)
subnetOp.Code = dns.EDNS0SUBNET
subnetOp.Family = 1
subnetOp.SourceNetmask = tc.SourceNetmask
subnetOp.Address = net.ParseIP(tc.SubnetAddr)
edns.Option = append(edns.Option, subnetOp)
m.Extra = append(m.Extra, edns)
m.SetQuestion(tc.Question, dns.TypeA)
in, _, err := c.Exchange(m, a.DNSAddr())
require.NoError(t, err)
require.Len(t, in.Answer, 1)
aRec, ok := in.Answer[0].(*dns.A)
require.True(t, ok)
require.Equal(t, "127.0.0.1", aRec.A.String())
optRR := in.IsEdns0()
require.NotNil(t, optRR)
require.Len(t, optRR.Option, 1)
subnet, ok := optRR.Option[0].(*dns.EDNS0_SUBNET)
require.True(t, ok)
require.Equal(t, uint16(1), subnet.Family)
require.Equal(t, tc.SourceNetmask, subnet.SourceNetmask)
require.Equal(t, tc.ExpectedScope, subnet.SourceScope)
require.Equal(t, net.ParseIP(tc.SubnetAddr), subnet.Address)
})
}
}
func TestDNS_SOA_Settings(t *testing.T) {
if testing.Short() {
t.Skip("too slow for testing.Short")
}
testSoaWithConfig := func(config string, ttl, expire, refresh, retry uint) {
a := NewTestAgent(t, config)
defer a.Shutdown()
testrpc.WaitForLeader(t, a.RPC, "dc1")
// lookup a non-existing node, we should receive a SOA
m := new(dns.Msg)
m.SetQuestion("nofoo.node.dc1.consul.", dns.TypeANY)
c := new(dns.Client)
in, _, err := c.Exchange(m, a.DNSAddr())
require.NoError(t, err)
require.Len(t, in.Ns, 1)
soaRec, ok := in.Ns[0].(*dns.SOA)
require.True(t, ok, "NS RR is not a SOA record")
require.Equal(t, uint32(ttl), soaRec.Minttl)
require.Equal(t, uint32(expire), soaRec.Expire)
require.Equal(t, uint32(refresh), soaRec.Refresh)
require.Equal(t, uint32(retry), soaRec.Retry)
require.Equal(t, uint32(ttl), soaRec.Hdr.Ttl)
}
// Default configuration
testSoaWithConfig("", 0, 86400, 3600, 600)
// Override all settings
testSoaWithConfig("dns_config={soa={min_ttl=60,expire=43200,refresh=1800,retry=300}} ", 60, 43200, 1800, 300)
// Override partial settings
testSoaWithConfig("dns_config={soa={min_ttl=60,expire=43200}} ", 60, 43200, 3600, 600)
// Override partial settings, part II
testSoaWithConfig("dns_config={soa={refresh=1800,retry=300}} ", 0, 86400, 1800, 300)
}
func TestDNS_VirtualIPLookup(t *testing.T) {
if testing.Short() {
t.Skip("too slow for testing.Short")
}
a := StartTestAgent(t, TestAgent{HCL: "", Overrides: `peering = { test_allow_peer_registrations = true } log_level = "debug"`})
defer a.Shutdown()
testrpc.WaitForLeader(t, a.RPC, "dc1")
server, ok := a.delegate.(*consul.Server)
require.True(t, ok)
// The proxy service will not receive a virtual IP if the server is not assigning virtual IPs yet.
retry.Run(t, func(r *retry.R) {
_, entry, err := server.FSM().State().SystemMetadataGet(nil, structs.SystemMetadataVirtualIPsEnabled)
require.NoError(r, err)
require.NotNil(r, entry)
})
type testCase struct {
name string
reg *structs.RegisterRequest
question string
expect string
}
run := func(t *testing.T, tc testCase) {
var out struct{}
require.Nil(t, a.RPC(context.Background(), "Catalog.Register", tc.reg, &out))
m := new(dns.Msg)
m.SetQuestion(tc.question, dns.TypeA)
c := new(dns.Client)
in, _, err := c.Exchange(m, a.DNSAddr())
require.Nil(t, err)
require.Len(t, in.Answer, 1)
aRec, ok := in.Answer[0].(*dns.A)
require.True(t, ok)
require.Equal(t, tc.expect, aRec.A.String())
}
tt := []testCase{
{
name: "local query",
reg: &structs.RegisterRequest{
Datacenter: "dc1",
Node: "foo",
Address: "127.0.0.55",
Service: &structs.NodeService{
Kind: structs.ServiceKindConnectProxy,
Service: "web-proxy",
Port: 12345,
Proxy: structs.ConnectProxyConfig{
DestinationServiceName: "db",
},
},
},
question: "db.virtual.consul.",
expect: "240.0.0.1",
},
{
name: "query for imported service",
reg: &structs.RegisterRequest{
PeerName: "frontend",
Datacenter: "dc1",
Node: "foo",
Address: "127.0.0.55",
Service: &structs.NodeService{
PeerName: "frontend",
Kind: structs.ServiceKindConnectProxy,
Service: "web-proxy",
Port: 12345,
Proxy: structs.ConnectProxyConfig{
DestinationServiceName: "db",
},
},
},
question: "db.virtual.frontend.consul.",
expect: "240.0.0.2",
},
}
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
run(t, tc)
})
}
}
func TestDNS_InifiniteRecursion(t *testing.T) {
if testing.Short() {
t.Skip("too slow for testing.Short")
}
// This test should not create an infinite recursion
a := NewTestAgent(t, `
domain = "CONSUL."
node_name = "test node"
`)
defer a.Shutdown()
testrpc.WaitForLeader(t, a.RPC, "dc1")
// Register the initial node with a service
{
args := &structs.RegisterRequest{
Datacenter: "dc1",
Node: "web",
Address: "web.service.consul.",
Service: &structs.NodeService{
Service: "web",
Port: 12345,
Address: "web.service.consul.",
},
}
var out struct{}
if err := a.RPC(context.Background(), "Catalog.Register", args, &out); err != nil {
t.Fatalf("err: %v", err)
}
}
// Look up the service directly
questions := []string{
"web.service.consul.",
}
for _, question := range questions {
m := new(dns.Msg)
m.SetQuestion(question, dns.TypeA)
c := new(dns.Client)
in, _, err := c.Exchange(m, a.DNSAddr())
if err != nil {
t.Fatalf("err: %v", err)
}
if len(in.Answer) < 1 {
t.Fatalf("Bad: %#v", in)
}
aRec, ok := in.Answer[0].(*dns.CNAME)
if !ok {
t.Fatalf("Bad: %#v", in.Answer[0])
}
if aRec.Target != "web.service.consul." {
t.Fatalf("Bad: %#v, target:=%s", aRec, aRec.Target)
}
}
}
func TestDNS_NSRecords(t *testing.T) {
if testing.Short() {
t.Skip("too slow for testing.Short")
}
a := NewTestAgent(t, `
domain = "CONSUL."
node_name = "server1"
`)
defer a.Shutdown()
testrpc.WaitForTestAgent(t, a.RPC, "dc1")
m := new(dns.Msg)
m.SetQuestion("something.node.consul.", dns.TypeNS)
c := new(dns.Client)
in, _, err := c.Exchange(m, a.DNSAddr())
if err != nil {
t.Fatalf("err: %v", err)
}
wantAnswer := []dns.RR{
&dns.NS{
Hdr: dns.RR_Header{Name: "consul.", Rrtype: dns.TypeNS, Class: dns.ClassINET, Ttl: 0, Rdlength: 0x13},
Ns: "server1.node.dc1.consul.",
},
}
require.Equal(t, wantAnswer, in.Answer, "answer")
wantExtra := []dns.RR{
&dns.A{
Hdr: dns.RR_Header{Name: "server1.node.dc1.consul.", Rrtype: dns.TypeA, Class: dns.ClassINET, Rdlength: 0x4, Ttl: 0},
A: net.ParseIP("127.0.0.1").To4(),
},
}
require.Equal(t, wantExtra, in.Extra, "extra")
}
func TestDNS_AltDomain_NSRecords(t *testing.T) {
if testing.Short() {
t.Skip("too slow for testing.Short")
}
a := NewTestAgent(t, `
domain = "CONSUL."
node_name = "server1"
alt_domain = "test-domain."
`)
defer a.Shutdown()
testrpc.WaitForTestAgent(t, a.RPC, "dc1")
questions := []struct {
ask string
domain string
wantDomain string
}{
{"something.node.consul.", "consul.", "server1.node.dc1.consul."},
{"something.node.test-domain.", "test-domain.", "server1.node.dc1.test-domain."},
}
for _, question := range questions {
m := new(dns.Msg)
m.SetQuestion(question.ask, dns.TypeNS)
c := new(dns.Client)
in, _, err := c.Exchange(m, a.DNSAddr())
if err != nil {
t.Fatalf("err: %v", err)
}
wantAnswer := []dns.RR{
&dns.NS{
Hdr: dns.RR_Header{Name: question.domain, Rrtype: dns.TypeNS, Class: dns.ClassINET, Ttl: 0, Rdlength: 0x13},
Ns: question.wantDomain,
},
}
require.Equal(t, wantAnswer, in.Answer, "answer")
wantExtra := []dns.RR{
&dns.A{
Hdr: dns.RR_Header{Name: question.wantDomain, Rrtype: dns.TypeA, Class: dns.ClassINET, Rdlength: 0x4, Ttl: 0},
A: net.ParseIP("127.0.0.1").To4(),
},
}
require.Equal(t, wantExtra, in.Extra, "extra")
}
}
func TestDNS_NSRecords_IPV6(t *testing.T) {
if testing.Short() {
t.Skip("too slow for testing.Short")
}
a := NewTestAgent(t, `
domain = "CONSUL."
node_name = "server1"
advertise_addr = "::1"
`)
defer a.Shutdown()
testrpc.WaitForTestAgent(t, a.RPC, "dc1")
m := new(dns.Msg)
m.SetQuestion("server1.node.dc1.consul.", dns.TypeNS)
c := new(dns.Client)
in, _, err := c.Exchange(m, a.DNSAddr())
if err != nil {
t.Fatalf("err: %v", err)
}
wantAnswer := []dns.RR{
&dns.NS{
Hdr: dns.RR_Header{Name: "consul.", Rrtype: dns.TypeNS, Class: dns.ClassINET, Ttl: 0, Rdlength: 0x2},
Ns: "server1.node.dc1.consul.",
},
}
require.Equal(t, wantAnswer, in.Answer, "answer")
wantExtra := []dns.RR{
&dns.AAAA{
Hdr: dns.RR_Header{Name: "server1.node.dc1.consul.", Rrtype: dns.TypeAAAA, Class: dns.ClassINET, Rdlength: 0x10, Ttl: 0},
AAAA: net.ParseIP("::1"),
},
}
require.Equal(t, wantExtra, in.Extra, "extra")
}
func TestDNS_AltDomain_NSRecords_IPV6(t *testing.T) {
if testing.Short() {
t.Skip("too slow for testing.Short")
}
a := NewTestAgent(t, `
domain = "CONSUL."
node_name = "server1"
advertise_addr = "::1"
alt_domain = "test-domain."
`)
defer a.Shutdown()
testrpc.WaitForTestAgent(t, a.RPC, "dc1")
questions := []struct {
ask string
domain string
wantDomain string
}{
{"server1.node.dc1.consul.", "consul.", "server1.node.dc1.consul."},
{"server1.node.dc1.test-domain.", "test-domain.", "server1.node.dc1.test-domain."},
}
for _, question := range questions {
m := new(dns.Msg)
m.SetQuestion(question.ask, dns.TypeNS)
c := new(dns.Client)
in, _, err := c.Exchange(m, a.DNSAddr())
if err != nil {
t.Fatalf("err: %v", err)
}
wantAnswer := []dns.RR{
&dns.NS{
Hdr: dns.RR_Header{Name: question.domain, Rrtype: dns.TypeNS, Class: dns.ClassINET, Ttl: 0, Rdlength: 0x2},
Ns: question.wantDomain,
},
}
require.Equal(t, wantAnswer, in.Answer, "answer")
wantExtra := []dns.RR{
&dns.AAAA{
Hdr: dns.RR_Header{Name: question.wantDomain, Rrtype: dns.TypeAAAA, Class: dns.ClassINET, Rdlength: 0x10, Ttl: 0},
AAAA: net.ParseIP("::1"),
},
}
require.Equal(t, wantExtra, in.Extra, "extra")
}
}
func TestDNS_Lookup_TaggedIPAddresses(t *testing.T) {
if testing.Short() {
t.Skip("too slow for testing.Short")
}
a := NewTestAgent(t, "")
defer a.Shutdown()
testrpc.WaitForLeader(t, a.RPC, "dc1")
// Register an equivalent prepared query.
var id string
{
args := &structs.PreparedQueryRequest{
Datacenter: "dc1",
Op: structs.PreparedQueryCreate,
Query: &structs.PreparedQuery{
Name: "test",
Service: structs.ServiceQuery{
Service: "db",
},
},
}
require.NoError(t, a.RPC(context.Background(), "PreparedQuery.Apply", args, &id))
}
type testCase struct {
nodeAddress string
nodeTaggedAddresses map[string]string
serviceAddress string
serviceTaggedAddresses map[string]structs.ServiceAddress
expectedServiceIPv4Address string
expectedServiceIPv6Address string
expectedNodeIPv4Address string
expectedNodeIPv6Address string
}
cases := map[string]testCase{
"simple-ipv4": {
serviceAddress: "127.0.0.2",
nodeAddress: "127.0.0.1",
expectedServiceIPv4Address: "127.0.0.2",
expectedServiceIPv6Address: "",
expectedNodeIPv4Address: "127.0.0.1",
expectedNodeIPv6Address: "",
},
"simple-ipv6": {
serviceAddress: "::2",
nodeAddress: "::1",
expectedServiceIPv6Address: "::2",
expectedServiceIPv4Address: "",
expectedNodeIPv6Address: "::1",
expectedNodeIPv4Address: "",
},
"ipv4-with-tagged-ipv6": {
serviceAddress: "127.0.0.2",
nodeAddress: "127.0.0.1",
serviceTaggedAddresses: map[string]structs.ServiceAddress{
structs.TaggedAddressLANIPv6: {Address: "::2"},
},
nodeTaggedAddresses: map[string]string{
structs.TaggedAddressLANIPv6: "::1",
},
expectedServiceIPv4Address: "127.0.0.2",
expectedServiceIPv6Address: "::2",
expectedNodeIPv4Address: "127.0.0.1",
expectedNodeIPv6Address: "::1",
},
"ipv6-with-tagged-ipv4": {
serviceAddress: "::2",
nodeAddress: "::1",
serviceTaggedAddresses: map[string]structs.ServiceAddress{
structs.TaggedAddressLANIPv4: {Address: "127.0.0.2"},
},
nodeTaggedAddresses: map[string]string{
structs.TaggedAddressLANIPv4: "127.0.0.1",
},
expectedServiceIPv4Address: "127.0.0.2",
expectedServiceIPv6Address: "::2",
expectedNodeIPv4Address: "127.0.0.1",
expectedNodeIPv6Address: "::1",
},
}
for name, tc := range cases {
name := name
tc := tc
t.Run(name, func(t *testing.T) {
args := &structs.RegisterRequest{
Datacenter: "dc1",
Node: "foo",
Address: tc.nodeAddress,
TaggedAddresses: tc.nodeTaggedAddresses,
Service: &structs.NodeService{
Service: "db",
Address: tc.serviceAddress,
Port: 8080,
TaggedAddresses: tc.serviceTaggedAddresses,
},
}
var out struct{}
require.NoError(t, a.RPC(context.Background(), "Catalog.Register", args, &out))
// Look up the SRV record via service and prepared query.
questions := []string{
"db.service.consul.",
id + ".query.consul.",
}
for _, question := range questions {
m := new(dns.Msg)
m.SetQuestion(question, dns.TypeA)
c := new(dns.Client)
addr := a.config.DNSAddrs[0].String()
in, _, err := c.Exchange(m, addr)
require.NoError(t, err)
if tc.expectedServiceIPv4Address != "" {
require.Len(t, in.Answer, 1)
aRec, ok := in.Answer[0].(*dns.A)
require.True(t, ok, "Bad: %#v", in.Answer[0])
require.Equal(t, question, aRec.Hdr.Name)
require.Equal(t, tc.expectedServiceIPv4Address, aRec.A.String())
} else {
require.Len(t, in.Answer, 0)
}
m = new(dns.Msg)
m.SetQuestion(question, dns.TypeAAAA)
c = new(dns.Client)
addr = a.config.DNSAddrs[0].String()
in, _, err = c.Exchange(m, addr)
require.NoError(t, err)
if tc.expectedServiceIPv6Address != "" {
require.Len(t, in.Answer, 1)
aRec, ok := in.Answer[0].(*dns.AAAA)
require.True(t, ok, "Bad: %#v", in.Answer[0])
require.Equal(t, question, aRec.Hdr.Name)
require.Equal(t, tc.expectedServiceIPv6Address, aRec.AAAA.String())
} else {
require.Len(t, in.Answer, 0)
}
}
// Look up node
m := new(dns.Msg)
m.SetQuestion("foo.node.consul.", dns.TypeA)
c := new(dns.Client)
addr := a.config.DNSAddrs[0].String()
in, _, err := c.Exchange(m, addr)
require.NoError(t, err)
if tc.expectedNodeIPv4Address != "" {
require.Len(t, in.Answer, 1)
aRec, ok := in.Answer[0].(*dns.A)
require.True(t, ok, "Bad: %#v", in.Answer[0])
require.Equal(t, "foo.node.consul.", aRec.Hdr.Name)
require.Equal(t, tc.expectedNodeIPv4Address, aRec.A.String())
} else {
require.Len(t, in.Answer, 0)
}
m = new(dns.Msg)
m.SetQuestion("foo.node.consul.", dns.TypeAAAA)
c = new(dns.Client)
addr = a.config.DNSAddrs[0].String()
in, _, err = c.Exchange(m, addr)
require.NoError(t, err)
if tc.expectedNodeIPv6Address != "" {
require.Len(t, in.Answer, 1)
aRec, ok := in.Answer[0].(*dns.AAAA)
require.True(t, ok, "Bad: %#v", in.Answer[0])
require.Equal(t, "foo.node.consul.", aRec.Hdr.Name)
require.Equal(t, tc.expectedNodeIPv6Address, aRec.AAAA.String())
} else {
require.Len(t, in.Answer, 0)
}
})
}
}
func TestDNS_PreparedQueryNearIPEDNS(t *testing.T) {
if testing.Short() {
t.Skip("too slow for testing.Short")
}