github.com/kjdelisle/consul@v1.4.5/agent/dns_test.go (about) 1 package agent 2 3 import ( 4 "fmt" 5 "math/rand" 6 "net" 7 "reflect" 8 "strings" 9 "testing" 10 "time" 11 12 "github.com/hashicorp/consul/agent/config" 13 "github.com/hashicorp/consul/agent/structs" 14 "github.com/hashicorp/consul/api" 15 "github.com/hashicorp/consul/lib" 16 "github.com/hashicorp/consul/testrpc" 17 "github.com/hashicorp/consul/testutil/retry" 18 "github.com/hashicorp/serf/coordinate" 19 "github.com/miekg/dns" 20 "github.com/pascaldekloe/goe/verify" 21 "github.com/stretchr/testify/assert" 22 "github.com/stretchr/testify/require" 23 ) 24 25 const ( 26 configUDPAnswerLimit = 4 27 defaultNumUDPResponses = 3 28 testUDPTruncateLimit = 8 29 30 pctNodesWithIPv6 = 0.5 31 32 // generateNumNodes is the upper bounds for the number of hosts used 33 // in testing below. Generate an arbitrarily large number of hosts. 34 generateNumNodes = testUDPTruncateLimit * defaultNumUDPResponses * configUDPAnswerLimit 35 ) 36 37 // makeRecursor creates a generic DNS server which always returns 38 // the provided reply. This is useful for mocking a DNS recursor with 39 // an expected result. 40 func makeRecursor(t *testing.T, answer dns.Msg) *dns.Server { 41 a := answer 42 mux := dns.NewServeMux() 43 mux.HandleFunc(".", func(resp dns.ResponseWriter, msg *dns.Msg) { 44 // The SetReply function sets the return code of the DNS 45 // query to SUCCESS 46 // We need a way to copy the variables not addressed 47 // in SetReply 48 answer.SetReply(msg) 49 answer.Rcode = a.Rcode 50 if err := resp.WriteMsg(&answer); err != nil { 51 t.Fatalf("err: %s", err) 52 } 53 }) 54 up := make(chan struct{}) 55 server := &dns.Server{ 56 Addr: "127.0.0.1:0", 57 Net: "udp", 58 Handler: mux, 59 NotifyStartedFunc: func() { close(up) }, 60 } 61 go server.ListenAndServe() 62 <-up 63 server.Addr = server.PacketConn.LocalAddr().String() 64 return server 65 } 66 67 // dnsCNAME returns a DNS CNAME record struct 68 func dnsCNAME(src, dest string) *dns.CNAME { 69 return &dns.CNAME{ 70 Hdr: dns.RR_Header{ 71 Name: dns.Fqdn(src), 72 Rrtype: dns.TypeCNAME, 73 Class: dns.ClassINET, 74 }, 75 Target: dns.Fqdn(dest), 76 } 77 } 78 79 // dnsA returns a DNS A record struct 80 func dnsA(src, dest string) *dns.A { 81 return &dns.A{ 82 Hdr: dns.RR_Header{ 83 Name: dns.Fqdn(src), 84 Rrtype: dns.TypeA, 85 Class: dns.ClassINET, 86 }, 87 A: net.ParseIP(dest), 88 } 89 } 90 91 // dnsTXT returns a DNS TXT record struct 92 func dnsTXT(src string, txt []string) *dns.TXT { 93 return &dns.TXT{ 94 Hdr: dns.RR_Header{ 95 Name: dns.Fqdn(src), 96 Rrtype: dns.TypeTXT, 97 Class: dns.ClassINET, 98 }, 99 Txt: txt, 100 } 101 } 102 103 func TestRecursorAddr(t *testing.T) { 104 t.Parallel() 105 addr, err := recursorAddr("8.8.8.8") 106 if err != nil { 107 t.Fatalf("err: %v", err) 108 } 109 if addr != "8.8.8.8:53" { 110 t.Fatalf("bad: %v", addr) 111 } 112 } 113 114 func TestEncodeKVasRFC1464(t *testing.T) { 115 // Test cases are from rfc1464 116 type rfc1464Test struct { 117 key, value, internalForm, externalForm string 118 } 119 tests := []rfc1464Test{ 120 {"color", "blue", "color=blue", "color=blue"}, 121 {"equation", "a=4", "equation=a=4", "equation=a=4"}, 122 {"a=a", "true", "a`=a=true", "a`=a=true"}, 123 {"a\\=a", "false", "a\\`=a=false", "a\\`=a=false"}, 124 {"=", "\\=", "`==\\=", "`==\\="}, 125 126 {"string", "\"Cat\"", "string=\"Cat\"", "string=\"Cat\""}, 127 {"string2", "`abc`", "string2=``abc``", "string2=``abc``"}, 128 {"novalue", "", "novalue=", "novalue="}, 129 {"a b", "c d", "a b=c d", "a b=c d"}, 130 {"abc ", "123 ", "abc` =123 ", "abc` =123 "}, 131 132 // Additional tests 133 {" abc", " 321", "` abc= 321", "` abc= 321"}, 134 {"`a", "b", "``a=b", "``a=b"}, 135 } 136 137 for _, test := range tests { 138 answer := encodeKVasRFC1464(test.key, test.value) 139 verify.Values(t, "internalForm", answer, test.internalForm) 140 } 141 } 142 143 func TestDNS_Over_TCP(t *testing.T) { 144 t.Parallel() 145 a := NewTestAgent(t, t.Name(), "") 146 defer a.Shutdown() 147 testrpc.WaitForLeader(t, a.RPC, "dc1") 148 149 // Register node 150 args := &structs.RegisterRequest{ 151 Datacenter: "dc1", 152 Node: "Foo", 153 Address: "127.0.0.1", 154 } 155 156 var out struct{} 157 if err := a.RPC("Catalog.Register", args, &out); err != nil { 158 t.Fatalf("err: %v", err) 159 } 160 161 m := new(dns.Msg) 162 m.SetQuestion("foo.node.dc1.consul.", dns.TypeANY) 163 164 c := new(dns.Client) 165 c.Net = "tcp" 166 in, _, err := c.Exchange(m, a.DNSAddr()) 167 if err != nil { 168 t.Fatalf("err: %v", err) 169 } 170 171 if len(in.Answer) != 1 { 172 t.Fatalf("empty lookup: %#v", in) 173 } 174 } 175 176 func TestDNS_NodeLookup(t *testing.T) { 177 t.Parallel() 178 a := NewTestAgent(t, t.Name(), "") 179 defer a.Shutdown() 180 testrpc.WaitForLeader(t, a.RPC, "dc1") 181 182 // Register node 183 args := &structs.RegisterRequest{ 184 Datacenter: "dc1", 185 Node: "foo", 186 Address: "127.0.0.1", 187 TaggedAddresses: map[string]string{ 188 "wan": "127.0.0.2", 189 }, 190 NodeMeta: map[string]string{ 191 "key": "value", 192 }, 193 } 194 195 var out struct{} 196 if err := a.RPC("Catalog.Register", args, &out); err != nil { 197 t.Fatalf("err: %v", err) 198 } 199 200 m := new(dns.Msg) 201 m.SetQuestion("foo.node.consul.", dns.TypeANY) 202 203 c := new(dns.Client) 204 in, _, err := c.Exchange(m, a.DNSAddr()) 205 require.NoError(t, err) 206 require.Len(t, in.Answer, 2) 207 require.Len(t, in.Extra, 0) 208 209 aRec, ok := in.Answer[0].(*dns.A) 210 require.True(t, ok, "First answer is not an A record") 211 require.Equal(t, "127.0.0.1", aRec.A.String()) 212 require.Equal(t, uint32(0), aRec.Hdr.Ttl) 213 214 txt, ok := in.Answer[1].(*dns.TXT) 215 require.True(t, ok, "Second answer is not a TXT record") 216 require.Len(t, txt.Txt, 1) 217 require.Equal(t, "key=value", txt.Txt[0]) 218 219 // Re-do the query, but only for an A RR 220 221 m = new(dns.Msg) 222 m.SetQuestion("foo.node.consul.", dns.TypeA) 223 224 c = new(dns.Client) 225 in, _, err = c.Exchange(m, a.DNSAddr()) 226 require.NoError(t, err) 227 require.Len(t, in.Answer, 1) 228 require.Len(t, in.Extra, 1) 229 230 aRec, ok = in.Answer[0].(*dns.A) 231 require.True(t, ok, "Answer is not an A record") 232 require.Equal(t, "127.0.0.1", aRec.A.String()) 233 require.Equal(t, uint32(0), aRec.Hdr.Ttl) 234 235 txt, ok = in.Extra[0].(*dns.TXT) 236 require.True(t, ok, "Extra record is not a TXT record") 237 require.Len(t, txt.Txt, 1) 238 require.Equal(t, "key=value", txt.Txt[0]) 239 240 // Re-do the query, but specify the DC 241 m = new(dns.Msg) 242 m.SetQuestion("foo.node.dc1.consul.", dns.TypeANY) 243 244 c = new(dns.Client) 245 in, _, err = c.Exchange(m, a.DNSAddr()) 246 require.NoError(t, err) 247 require.Len(t, in.Answer, 2) 248 require.Len(t, in.Extra, 0) 249 250 aRec, ok = in.Answer[0].(*dns.A) 251 require.True(t, ok, "First answer is not an A record") 252 require.Equal(t, "127.0.0.1", aRec.A.String()) 253 require.Equal(t, uint32(0), aRec.Hdr.Ttl) 254 255 txt, ok = in.Answer[1].(*dns.TXT) 256 require.True(t, ok, "Second answer is not a TXT record") 257 258 // lookup a non-existing node, we should receive a SOA 259 m = new(dns.Msg) 260 m.SetQuestion("nofoo.node.dc1.consul.", dns.TypeANY) 261 262 c = new(dns.Client) 263 in, _, err = c.Exchange(m, a.DNSAddr()) 264 require.NoError(t, err) 265 require.Len(t, in.Ns, 1) 266 soaRec, ok := in.Ns[0].(*dns.SOA) 267 require.True(t, ok, "NS RR is not a SOA record") 268 require.Equal(t, uint32(0), soaRec.Hdr.Ttl) 269 } 270 271 func TestDNS_CaseInsensitiveNodeLookup(t *testing.T) { 272 t.Parallel() 273 a := NewTestAgent(t, t.Name(), "") 274 defer a.Shutdown() 275 testrpc.WaitForLeader(t, a.RPC, "dc1") 276 277 // Register node 278 args := &structs.RegisterRequest{ 279 Datacenter: "dc1", 280 Node: "Foo", 281 Address: "127.0.0.1", 282 } 283 284 var out struct{} 285 if err := a.RPC("Catalog.Register", args, &out); err != nil { 286 t.Fatalf("err: %v", err) 287 } 288 289 m := new(dns.Msg) 290 m.SetQuestion("fOO.node.dc1.consul.", dns.TypeANY) 291 292 c := new(dns.Client) 293 in, _, err := c.Exchange(m, a.DNSAddr()) 294 if err != nil { 295 t.Fatalf("err: %v", err) 296 } 297 298 if len(in.Answer) != 1 { 299 t.Fatalf("empty lookup: %#v", in) 300 } 301 } 302 303 func TestDNS_NodeLookup_PeriodName(t *testing.T) { 304 t.Parallel() 305 a := NewTestAgent(t, t.Name(), "") 306 defer a.Shutdown() 307 testrpc.WaitForLeader(t, a.RPC, "dc1") 308 309 // Register node with period in name 310 args := &structs.RegisterRequest{ 311 Datacenter: "dc1", 312 Node: "foo.bar", 313 Address: "127.0.0.1", 314 } 315 316 var out struct{} 317 if err := a.RPC("Catalog.Register", args, &out); err != nil { 318 t.Fatalf("err: %v", err) 319 } 320 321 m := new(dns.Msg) 322 m.SetQuestion("foo.bar.node.consul.", dns.TypeANY) 323 324 c := new(dns.Client) 325 in, _, err := c.Exchange(m, a.DNSAddr()) 326 if err != nil { 327 t.Fatalf("err: %v", err) 328 } 329 330 if len(in.Answer) != 1 { 331 t.Fatalf("Bad: %#v", in) 332 } 333 334 aRec, ok := in.Answer[0].(*dns.A) 335 if !ok { 336 t.Fatalf("Bad: %#v", in.Answer[0]) 337 } 338 if aRec.A.String() != "127.0.0.1" { 339 t.Fatalf("Bad: %#v", in.Answer[0]) 340 } 341 } 342 343 func TestDNS_NodeLookup_AAAA(t *testing.T) { 344 t.Parallel() 345 a := NewTestAgent(t, t.Name(), "") 346 defer a.Shutdown() 347 testrpc.WaitForLeader(t, a.RPC, "dc1") 348 349 // Register node 350 args := &structs.RegisterRequest{ 351 Datacenter: "dc1", 352 Node: "bar", 353 Address: "::4242:4242", 354 } 355 356 var out struct{} 357 if err := a.RPC("Catalog.Register", args, &out); err != nil { 358 t.Fatalf("err: %v", err) 359 } 360 361 m := new(dns.Msg) 362 m.SetQuestion("bar.node.consul.", dns.TypeAAAA) 363 364 c := new(dns.Client) 365 in, _, err := c.Exchange(m, a.DNSAddr()) 366 if err != nil { 367 t.Fatalf("err: %v", err) 368 } 369 370 if len(in.Answer) != 1 { 371 t.Fatalf("Bad: %#v", in) 372 } 373 374 aRec, ok := in.Answer[0].(*dns.AAAA) 375 if !ok { 376 t.Fatalf("Bad: %#v", in.Answer[0]) 377 } 378 if aRec.AAAA.String() != "::4242:4242" { 379 t.Fatalf("Bad: %#v", in.Answer[0]) 380 } 381 if aRec.Hdr.Ttl != 0 { 382 t.Fatalf("Bad: %#v", in.Answer[0]) 383 } 384 } 385 386 func TestDNSCycleRecursorCheck(t *testing.T) { 387 t.Parallel() 388 // Start a DNS recursor that returns a SERVFAIL 389 server1 := makeRecursor(t, dns.Msg{ 390 MsgHdr: dns.MsgHdr{Rcode: dns.RcodeServerFailure}, 391 }) 392 // Start a DNS recursor that returns the result 393 defer server1.Shutdown() 394 server2 := makeRecursor(t, dns.Msg{ 395 MsgHdr: dns.MsgHdr{Rcode: dns.RcodeSuccess}, 396 Answer: []dns.RR{ 397 dnsA("www.google.com", "172.21.45.67"), 398 }, 399 }) 400 defer server2.Shutdown() 401 //Mock the agent startup with the necessary configs 402 agent := NewTestAgent(t, t.Name(), 403 `recursors = ["`+server1.Addr+`", "`+server2.Addr+`"] 404 `) 405 defer agent.Shutdown() 406 // DNS Message init 407 m := new(dns.Msg) 408 m.SetQuestion("google.com.", dns.TypeA) 409 // Agent request 410 client := new(dns.Client) 411 in, _, _ := client.Exchange(m, agent.DNSAddr()) 412 wantAnswer := []dns.RR{ 413 &dns.A{ 414 Hdr: dns.RR_Header{Name: "www.google.com.", Rrtype: dns.TypeA, Class: dns.ClassINET, Rdlength: 0x4}, 415 A: []byte{0xAC, 0x15, 0x2D, 0x43}, // 172 , 21, 45, 67 416 }, 417 } 418 verify.Values(t, "Answer", in.Answer, wantAnswer) 419 } 420 func TestDNSCycleRecursorCheckAllFail(t *testing.T) { 421 t.Parallel() 422 // Start 3 DNS recursors that returns a REFUSED status 423 server1 := makeRecursor(t, dns.Msg{ 424 MsgHdr: dns.MsgHdr{Rcode: dns.RcodeRefused}, 425 }) 426 defer server1.Shutdown() 427 server2 := makeRecursor(t, dns.Msg{ 428 MsgHdr: dns.MsgHdr{Rcode: dns.RcodeRefused}, 429 }) 430 defer server2.Shutdown() 431 server3 := makeRecursor(t, dns.Msg{ 432 MsgHdr: dns.MsgHdr{Rcode: dns.RcodeRefused}, 433 }) 434 defer server3.Shutdown() 435 //Mock the agent startup with the necessary configs 436 agent := NewTestAgent(t, t.Name(), 437 `recursors = ["`+server1.Addr+`", "`+server2.Addr+`","`+server3.Addr+`"] 438 `) 439 defer agent.Shutdown() 440 // DNS dummy message initialization 441 m := new(dns.Msg) 442 m.SetQuestion("google.com.", dns.TypeA) 443 // Agent request 444 client := new(dns.Client) 445 in, _, _ := client.Exchange(m, agent.DNSAddr()) 446 //Verify if we hit SERVFAIL from Consul 447 verify.Values(t, "Answer", in.Rcode, dns.RcodeServerFailure) 448 } 449 func TestDNS_NodeLookup_CNAME(t *testing.T) { 450 t.Parallel() 451 recursor := makeRecursor(t, dns.Msg{ 452 Answer: []dns.RR{ 453 dnsCNAME("www.google.com", "google.com"), 454 dnsA("google.com", "1.2.3.4"), 455 dnsTXT("google.com", []string{"my_txt_value"}), 456 }, 457 }) 458 defer recursor.Shutdown() 459 460 a := NewTestAgent(t, t.Name(), ` 461 recursors = ["`+recursor.Addr+`"] 462 `) 463 defer a.Shutdown() 464 testrpc.WaitForLeader(t, a.RPC, "dc1") 465 466 // Register node 467 args := &structs.RegisterRequest{ 468 Datacenter: "dc1", 469 Node: "google", 470 Address: "www.google.com", 471 } 472 473 var out struct{} 474 if err := a.RPC("Catalog.Register", args, &out); err != nil { 475 t.Fatalf("err: %v", err) 476 } 477 478 m := new(dns.Msg) 479 m.SetQuestion("google.node.consul.", dns.TypeANY) 480 481 c := new(dns.Client) 482 in, _, err := c.Exchange(m, a.DNSAddr()) 483 if err != nil { 484 t.Fatalf("err: %v", err) 485 } 486 487 wantAnswer := []dns.RR{ 488 &dns.CNAME{ 489 Hdr: dns.RR_Header{Name: "google.node.consul.", Rrtype: dns.TypeCNAME, Class: dns.ClassINET, Ttl: 0, Rdlength: 0x10}, 490 Target: "www.google.com.", 491 }, 492 &dns.CNAME{ 493 Hdr: dns.RR_Header{Name: "www.google.com.", Rrtype: dns.TypeCNAME, Class: dns.ClassINET, Rdlength: 0x2}, 494 Target: "google.com.", 495 }, 496 &dns.A{ 497 Hdr: dns.RR_Header{Name: "google.com.", Rrtype: dns.TypeA, Class: dns.ClassINET, Rdlength: 0x4}, 498 A: []byte{0x1, 0x2, 0x3, 0x4}, // 1.2.3.4 499 }, 500 &dns.TXT{ 501 Hdr: dns.RR_Header{Name: "google.com.", Rrtype: dns.TypeTXT, Class: dns.ClassINET, Rdlength: 0xd}, 502 Txt: []string{"my_txt_value"}, 503 }, 504 } 505 verify.Values(t, "answer", in.Answer, wantAnswer) 506 } 507 508 func TestDNS_NodeLookup_TXT(t *testing.T) { 509 a := NewTestAgent(t, t.Name(), ``) 510 defer a.Shutdown() 511 testrpc.WaitForLeader(t, a.RPC, "dc1") 512 513 args := &structs.RegisterRequest{ 514 Datacenter: "dc1", 515 Node: "google", 516 Address: "127.0.0.1", 517 NodeMeta: map[string]string{ 518 "rfc1035-00": "value0", 519 "key0": "value1", 520 }, 521 } 522 523 var out struct{} 524 if err := a.RPC("Catalog.Register", args, &out); err != nil { 525 t.Fatalf("err: %v", err) 526 } 527 528 m := new(dns.Msg) 529 m.SetQuestion("google.node.consul.", dns.TypeTXT) 530 531 c := new(dns.Client) 532 in, _, err := c.Exchange(m, a.DNSAddr()) 533 if err != nil { 534 t.Fatalf("err: %v", err) 535 } 536 537 // Should have the 1 TXT record reply 538 if len(in.Answer) != 2 { 539 t.Fatalf("Bad: %#v", in) 540 } 541 542 txtRec, ok := in.Answer[0].(*dns.TXT) 543 if !ok { 544 t.Fatalf("Bad: %#v", in.Answer[0]) 545 } 546 if len(txtRec.Txt) != 1 { 547 t.Fatalf("Bad: %#v", in.Answer[0]) 548 } 549 if txtRec.Txt[0] != "value0" && txtRec.Txt[0] != "key0=value1" { 550 t.Fatalf("Bad: %#v", in.Answer[0]) 551 } 552 } 553 554 func TestDNS_NodeLookup_TXT_DontSuppress(t *testing.T) { 555 a := NewTestAgent(t, t.Name(), `dns_config = { enable_additional_node_meta_txt = false }`) 556 defer a.Shutdown() 557 testrpc.WaitForLeader(t, a.RPC, "dc1") 558 559 args := &structs.RegisterRequest{ 560 Datacenter: "dc1", 561 Node: "google", 562 Address: "127.0.0.1", 563 NodeMeta: map[string]string{ 564 "rfc1035-00": "value0", 565 "key0": "value1", 566 }, 567 } 568 569 var out struct{} 570 if err := a.RPC("Catalog.Register", args, &out); err != nil { 571 t.Fatalf("err: %v", err) 572 } 573 574 m := new(dns.Msg) 575 m.SetQuestion("google.node.consul.", dns.TypeTXT) 576 577 c := new(dns.Client) 578 in, _, err := c.Exchange(m, a.DNSAddr()) 579 if err != nil { 580 t.Fatalf("err: %v", err) 581 } 582 583 // Should have the 1 TXT record reply 584 if len(in.Answer) != 2 { 585 t.Fatalf("Bad: %#v", in) 586 } 587 588 txtRec, ok := in.Answer[0].(*dns.TXT) 589 if !ok { 590 t.Fatalf("Bad: %#v", in.Answer[0]) 591 } 592 if len(txtRec.Txt) != 1 { 593 t.Fatalf("Bad: %#v", in.Answer[0]) 594 } 595 if txtRec.Txt[0] != "value0" && txtRec.Txt[0] != "key0=value1" { 596 t.Fatalf("Bad: %#v", in.Answer[0]) 597 } 598 } 599 600 func TestDNS_NodeLookup_ANY(t *testing.T) { 601 a := NewTestAgent(t, t.Name(), ``) 602 defer a.Shutdown() 603 testrpc.WaitForLeader(t, a.RPC, "dc1") 604 605 args := &structs.RegisterRequest{ 606 Datacenter: "dc1", 607 Node: "bar", 608 Address: "127.0.0.1", 609 NodeMeta: map[string]string{ 610 "key": "value", 611 }, 612 } 613 614 var out struct{} 615 if err := a.RPC("Catalog.Register", args, &out); err != nil { 616 t.Fatalf("err: %v", err) 617 } 618 619 m := new(dns.Msg) 620 m.SetQuestion("bar.node.consul.", dns.TypeANY) 621 622 c := new(dns.Client) 623 in, _, err := c.Exchange(m, a.DNSAddr()) 624 if err != nil { 625 t.Fatalf("err: %v", err) 626 } 627 628 wantAnswer := []dns.RR{ 629 &dns.A{ 630 Hdr: dns.RR_Header{Name: "bar.node.consul.", Rrtype: dns.TypeA, Class: dns.ClassINET, Rdlength: 0x4}, 631 A: []byte{0x7f, 0x0, 0x0, 0x1}, // 127.0.0.1 632 }, 633 &dns.TXT{ 634 Hdr: dns.RR_Header{Name: "bar.node.consul.", Rrtype: dns.TypeTXT, Class: dns.ClassINET, Rdlength: 0xa}, 635 Txt: []string{"key=value"}, 636 }, 637 } 638 verify.Values(t, "answer", in.Answer, wantAnswer) 639 } 640 641 func TestDNS_NodeLookup_ANY_DontSuppressTXT(t *testing.T) { 642 a := NewTestAgent(t, t.Name(), `dns_config = { enable_additional_node_meta_txt = false }`) 643 defer a.Shutdown() 644 testrpc.WaitForLeader(t, a.RPC, "dc1") 645 646 args := &structs.RegisterRequest{ 647 Datacenter: "dc1", 648 Node: "bar", 649 Address: "127.0.0.1", 650 NodeMeta: map[string]string{ 651 "key": "value", 652 }, 653 } 654 655 var out struct{} 656 if err := a.RPC("Catalog.Register", args, &out); err != nil { 657 t.Fatalf("err: %v", err) 658 } 659 660 m := new(dns.Msg) 661 m.SetQuestion("bar.node.consul.", dns.TypeANY) 662 663 c := new(dns.Client) 664 in, _, err := c.Exchange(m, a.DNSAddr()) 665 if err != nil { 666 t.Fatalf("err: %v", err) 667 } 668 669 wantAnswer := []dns.RR{ 670 &dns.A{ 671 Hdr: dns.RR_Header{Name: "bar.node.consul.", Rrtype: dns.TypeA, Class: dns.ClassINET, Rdlength: 0x4}, 672 A: []byte{0x7f, 0x0, 0x0, 0x1}, // 127.0.0.1 673 }, 674 &dns.TXT{ 675 Hdr: dns.RR_Header{Name: "bar.node.consul.", Rrtype: dns.TypeTXT, Class: dns.ClassINET, Rdlength: 0xa}, 676 Txt: []string{"key=value"}, 677 }, 678 } 679 verify.Values(t, "answer", in.Answer, wantAnswer) 680 } 681 682 func TestDNS_NodeLookup_A_SuppressTXT(t *testing.T) { 683 a := NewTestAgent(t, t.Name(), `dns_config = { enable_additional_node_meta_txt = false }`) 684 defer a.Shutdown() 685 testrpc.WaitForLeader(t, a.RPC, "dc1") 686 687 args := &structs.RegisterRequest{ 688 Datacenter: "dc1", 689 Node: "bar", 690 Address: "127.0.0.1", 691 NodeMeta: map[string]string{ 692 "key": "value", 693 }, 694 } 695 696 var out struct{} 697 require.NoError(t, a.RPC("Catalog.Register", args, &out)) 698 699 m := new(dns.Msg) 700 m.SetQuestion("bar.node.consul.", dns.TypeA) 701 702 c := new(dns.Client) 703 in, _, err := c.Exchange(m, a.DNSAddr()) 704 require.NoError(t, err) 705 706 wantAnswer := []dns.RR{ 707 &dns.A{ 708 Hdr: dns.RR_Header{Name: "bar.node.consul.", Rrtype: dns.TypeA, Class: dns.ClassINET, Rdlength: 0x4}, 709 A: []byte{0x7f, 0x0, 0x0, 0x1}, // 127.0.0.1 710 }, 711 } 712 verify.Values(t, "answer", in.Answer, wantAnswer) 713 714 // ensure TXT RR suppression 715 require.Len(t, in.Extra, 0) 716 } 717 718 func TestDNS_EDNS0(t *testing.T) { 719 t.Parallel() 720 a := NewTestAgent(t, t.Name(), "") 721 defer a.Shutdown() 722 testrpc.WaitForLeader(t, a.RPC, "dc1") 723 724 // Register node 725 args := &structs.RegisterRequest{ 726 Datacenter: "dc1", 727 Node: "foo", 728 Address: "127.0.0.2", 729 } 730 731 var out struct{} 732 if err := a.RPC("Catalog.Register", args, &out); err != nil { 733 t.Fatalf("err: %v", err) 734 } 735 736 m := new(dns.Msg) 737 m.SetEdns0(12345, true) 738 m.SetQuestion("foo.node.dc1.consul.", dns.TypeANY) 739 740 c := new(dns.Client) 741 in, _, err := c.Exchange(m, a.DNSAddr()) 742 if err != nil { 743 t.Fatalf("err: %v", err) 744 } 745 746 if len(in.Answer) != 1 { 747 t.Fatalf("empty lookup: %#v", in) 748 } 749 edns := in.IsEdns0() 750 if edns == nil { 751 t.Fatalf("empty edns: %#v", in) 752 } 753 if edns.UDPSize() != 12345 { 754 t.Fatalf("bad edns size: %d", edns.UDPSize()) 755 } 756 } 757 758 func TestDNS_EDNS0_ECS(t *testing.T) { 759 t.Parallel() 760 a := NewTestAgent(t, t.Name(), "") 761 defer a.Shutdown() 762 testrpc.WaitForLeader(t, a.RPC, "dc1") 763 764 // Register a node with a service. 765 { 766 args := &structs.RegisterRequest{ 767 Datacenter: "dc1", 768 Node: "foo", 769 Address: "127.0.0.1", 770 Service: &structs.NodeService{ 771 Service: "db", 772 Tags: []string{"master"}, 773 Port: 12345, 774 }, 775 } 776 777 var out struct{} 778 require.NoError(t, a.RPC("Catalog.Register", args, &out)) 779 } 780 781 // Register an equivalent prepared query. 782 var id string 783 { 784 args := &structs.PreparedQueryRequest{ 785 Datacenter: "dc1", 786 Op: structs.PreparedQueryCreate, 787 Query: &structs.PreparedQuery{ 788 Name: "test", 789 Service: structs.ServiceQuery{ 790 Service: "db", 791 }, 792 }, 793 } 794 require.NoError(t, a.RPC("PreparedQuery.Apply", args, &id)) 795 } 796 797 cases := []struct { 798 Name string 799 Question string 800 SubnetAddr string 801 SourceNetmask uint8 802 ExpectedScope uint8 803 }{ 804 {"global", "db.service.consul.", "198.18.0.1", 32, 0}, 805 {"query", "test.query.consul.", "198.18.0.1", 32, 32}, 806 {"query-subnet", "test.query.consul.", "198.18.0.0", 21, 21}, 807 } 808 809 for _, tc := range cases { 810 t.Run(tc.Name, func(t *testing.T) { 811 c := new(dns.Client) 812 // Query the service directly - should have a globally valid scope (0) 813 m := new(dns.Msg) 814 edns := new(dns.OPT) 815 edns.Hdr.Name = "." 816 edns.Hdr.Rrtype = dns.TypeOPT 817 edns.SetUDPSize(12345) 818 edns.SetDo(true) 819 subnetOp := new(dns.EDNS0_SUBNET) 820 subnetOp.Code = dns.EDNS0SUBNET 821 subnetOp.Family = 1 822 subnetOp.SourceNetmask = tc.SourceNetmask 823 subnetOp.Address = net.ParseIP(tc.SubnetAddr) 824 edns.Option = append(edns.Option, subnetOp) 825 m.Extra = append(m.Extra, edns) 826 m.SetQuestion(tc.Question, dns.TypeA) 827 828 in, _, err := c.Exchange(m, a.DNSAddr()) 829 require.NoError(t, err) 830 require.Len(t, in.Answer, 1) 831 aRec, ok := in.Answer[0].(*dns.A) 832 require.True(t, ok) 833 require.Equal(t, "127.0.0.1", aRec.A.String()) 834 835 optRR := in.IsEdns0() 836 require.NotNil(t, optRR) 837 require.Len(t, optRR.Option, 1) 838 839 subnet, ok := optRR.Option[0].(*dns.EDNS0_SUBNET) 840 require.True(t, ok) 841 require.Equal(t, uint16(1), subnet.Family) 842 require.Equal(t, tc.SourceNetmask, subnet.SourceNetmask) 843 // scope set to 0 for a globally valid reply 844 require.Equal(t, tc.ExpectedScope, subnet.SourceScope) 845 require.Equal(t, net.ParseIP(tc.SubnetAddr), subnet.Address) 846 }) 847 } 848 } 849 850 func TestDNS_ReverseLookup(t *testing.T) { 851 t.Parallel() 852 a := NewTestAgent(t, t.Name(), "") 853 defer a.Shutdown() 854 testrpc.WaitForLeader(t, a.RPC, "dc1") 855 856 // Register node 857 args := &structs.RegisterRequest{ 858 Datacenter: "dc1", 859 Node: "foo2", 860 Address: "127.0.0.2", 861 } 862 863 var out struct{} 864 if err := a.RPC("Catalog.Register", args, &out); err != nil { 865 t.Fatalf("err: %v", err) 866 } 867 868 m := new(dns.Msg) 869 m.SetQuestion("2.0.0.127.in-addr.arpa.", dns.TypeANY) 870 871 c := new(dns.Client) 872 in, _, err := c.Exchange(m, a.DNSAddr()) 873 if err != nil { 874 t.Fatalf("err: %v", err) 875 } 876 877 if len(in.Answer) != 1 { 878 t.Fatalf("Bad: %#v", in) 879 } 880 881 ptrRec, ok := in.Answer[0].(*dns.PTR) 882 if !ok { 883 t.Fatalf("Bad: %#v", in.Answer[0]) 884 } 885 if ptrRec.Ptr != "foo2.node.dc1.consul." { 886 t.Fatalf("Bad: %#v", ptrRec) 887 } 888 } 889 890 func TestDNS_ReverseLookup_CustomDomain(t *testing.T) { 891 t.Parallel() 892 a := NewTestAgent(t, t.Name(), ` 893 domain = "custom" 894 `) 895 defer a.Shutdown() 896 testrpc.WaitForLeader(t, a.RPC, "dc1") 897 898 // Register node 899 args := &structs.RegisterRequest{ 900 Datacenter: "dc1", 901 Node: "foo2", 902 Address: "127.0.0.2", 903 } 904 905 var out struct{} 906 if err := a.RPC("Catalog.Register", args, &out); err != nil { 907 t.Fatalf("err: %v", err) 908 } 909 910 m := new(dns.Msg) 911 m.SetQuestion("2.0.0.127.in-addr.arpa.", dns.TypeANY) 912 913 c := new(dns.Client) 914 in, _, err := c.Exchange(m, a.DNSAddr()) 915 if err != nil { 916 t.Fatalf("err: %v", err) 917 } 918 919 if len(in.Answer) != 1 { 920 t.Fatalf("Bad: %#v", in) 921 } 922 923 ptrRec, ok := in.Answer[0].(*dns.PTR) 924 if !ok { 925 t.Fatalf("Bad: %#v", in.Answer[0]) 926 } 927 if ptrRec.Ptr != "foo2.node.dc1.custom." { 928 t.Fatalf("Bad: %#v", ptrRec) 929 } 930 } 931 932 func TestDNS_ReverseLookup_IPV6(t *testing.T) { 933 t.Parallel() 934 a := NewTestAgent(t, t.Name(), "") 935 defer a.Shutdown() 936 testrpc.WaitForLeader(t, a.RPC, "dc1") 937 938 // Register node 939 args := &structs.RegisterRequest{ 940 Datacenter: "dc1", 941 Node: "bar", 942 Address: "::4242:4242", 943 } 944 945 var out struct{} 946 if err := a.RPC("Catalog.Register", args, &out); err != nil { 947 t.Fatalf("err: %v", err) 948 } 949 950 m := new(dns.Msg) 951 m.SetQuestion("2.4.2.4.2.4.2.4.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa.", dns.TypeANY) 952 953 c := new(dns.Client) 954 in, _, err := c.Exchange(m, a.DNSAddr()) 955 if err != nil { 956 t.Fatalf("err: %v", err) 957 } 958 959 if len(in.Answer) != 1 { 960 t.Fatalf("Bad: %#v", in) 961 } 962 963 ptrRec, ok := in.Answer[0].(*dns.PTR) 964 if !ok { 965 t.Fatalf("Bad: %#v", in.Answer[0]) 966 } 967 if ptrRec.Ptr != "bar.node.dc1.consul." { 968 t.Fatalf("Bad: %#v", ptrRec) 969 } 970 } 971 972 func TestDNS_ServiceReverseLookup(t *testing.T) { 973 t.Parallel() 974 a := NewTestAgent(t, t.Name(), "") 975 defer a.Shutdown() 976 testrpc.WaitForLeader(t, a.RPC, "dc1") 977 978 // Register a node with a service. 979 { 980 args := &structs.RegisterRequest{ 981 Datacenter: "dc1", 982 Node: "foo", 983 Address: "127.0.0.1", 984 Service: &structs.NodeService{ 985 Service: "db", 986 Tags: []string{"master"}, 987 Port: 12345, 988 Address: "127.0.0.2", 989 }, 990 } 991 992 var out struct{} 993 if err := a.RPC("Catalog.Register", args, &out); err != nil { 994 t.Fatalf("err: %v", err) 995 } 996 } 997 998 m := new(dns.Msg) 999 m.SetQuestion("2.0.0.127.in-addr.arpa.", dns.TypeANY) 1000 1001 c := new(dns.Client) 1002 in, _, err := c.Exchange(m, a.DNSAddr()) 1003 if err != nil { 1004 t.Fatalf("err: %v", err) 1005 } 1006 1007 if len(in.Answer) != 1 { 1008 t.Fatalf("Bad: %#v", in) 1009 } 1010 1011 ptrRec, ok := in.Answer[0].(*dns.PTR) 1012 if !ok { 1013 t.Fatalf("Bad: %#v", in.Answer[0]) 1014 } 1015 if ptrRec.Ptr != "db.service.consul." { 1016 t.Fatalf("Bad: %#v", ptrRec) 1017 } 1018 } 1019 1020 func TestDNS_ServiceReverseLookup_IPV6(t *testing.T) { 1021 t.Parallel() 1022 a := NewTestAgent(t, t.Name(), "") 1023 defer a.Shutdown() 1024 testrpc.WaitForLeader(t, a.RPC, "dc1") 1025 1026 // Register a node with a service. 1027 { 1028 args := &structs.RegisterRequest{ 1029 Datacenter: "dc1", 1030 Node: "foo", 1031 Address: "2001:db8::1", 1032 Service: &structs.NodeService{ 1033 Service: "db", 1034 Tags: []string{"master"}, 1035 Port: 12345, 1036 Address: "2001:db8::ff00:42:8329", 1037 }, 1038 } 1039 1040 var out struct{} 1041 if err := a.RPC("Catalog.Register", args, &out); err != nil { 1042 t.Fatalf("err: %v", err) 1043 } 1044 } 1045 1046 m := new(dns.Msg) 1047 m.SetQuestion("9.2.3.8.2.4.0.0.0.0.f.f.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa.", dns.TypeANY) 1048 1049 c := new(dns.Client) 1050 in, _, err := c.Exchange(m, a.DNSAddr()) 1051 if err != nil { 1052 t.Fatalf("err: %v", err) 1053 } 1054 1055 if len(in.Answer) != 1 { 1056 t.Fatalf("Bad: %#v", in) 1057 } 1058 1059 ptrRec, ok := in.Answer[0].(*dns.PTR) 1060 if !ok { 1061 t.Fatalf("Bad: %#v", in.Answer[0]) 1062 } 1063 if ptrRec.Ptr != "db.service.consul." { 1064 t.Fatalf("Bad: %#v", ptrRec) 1065 } 1066 } 1067 1068 func TestDNS_ServiceReverseLookup_CustomDomain(t *testing.T) { 1069 t.Parallel() 1070 a := NewTestAgent(t, t.Name(), ` 1071 domain = "custom" 1072 `) 1073 defer a.Shutdown() 1074 testrpc.WaitForLeader(t, a.RPC, "dc1") 1075 1076 // Register a node with a service. 1077 { 1078 args := &structs.RegisterRequest{ 1079 Datacenter: "dc1", 1080 Node: "foo", 1081 Address: "127.0.0.1", 1082 Service: &structs.NodeService{ 1083 Service: "db", 1084 Tags: []string{"master"}, 1085 Port: 12345, 1086 Address: "127.0.0.2", 1087 }, 1088 } 1089 1090 var out struct{} 1091 if err := a.RPC("Catalog.Register", args, &out); err != nil { 1092 t.Fatalf("err: %v", err) 1093 } 1094 } 1095 1096 m := new(dns.Msg) 1097 m.SetQuestion("2.0.0.127.in-addr.arpa.", dns.TypeANY) 1098 1099 c := new(dns.Client) 1100 in, _, err := c.Exchange(m, a.DNSAddr()) 1101 if err != nil { 1102 t.Fatalf("err: %v", err) 1103 } 1104 1105 if len(in.Answer) != 1 { 1106 t.Fatalf("Bad: %#v", in) 1107 } 1108 1109 ptrRec, ok := in.Answer[0].(*dns.PTR) 1110 if !ok { 1111 t.Fatalf("Bad: %#v", in.Answer[0]) 1112 } 1113 if ptrRec.Ptr != "db.service.custom." { 1114 t.Fatalf("Bad: %#v", ptrRec) 1115 } 1116 } 1117 1118 func TestDNS_SOA_Settings(t *testing.T) { 1119 t.Parallel() 1120 testSoaWithConfig := func(config string, ttl, expire, refresh, retry uint) { 1121 a := NewTestAgent(t, t.Name(), config) 1122 defer a.Shutdown() 1123 testrpc.WaitForLeader(t, a.RPC, "dc1") 1124 1125 // lookup a non-existing node, we should receive a SOA 1126 m := new(dns.Msg) 1127 m.SetQuestion("nofoo.node.dc1.consul.", dns.TypeANY) 1128 1129 c := new(dns.Client) 1130 in, _, err := c.Exchange(m, a.DNSAddr()) 1131 require.NoError(t, err) 1132 require.Len(t, in.Ns, 1) 1133 soaRec, ok := in.Ns[0].(*dns.SOA) 1134 require.True(t, ok, "NS RR is not a SOA record") 1135 require.Equal(t, uint32(ttl), soaRec.Minttl) 1136 require.Equal(t, uint32(expire), soaRec.Expire) 1137 require.Equal(t, uint32(refresh), soaRec.Refresh) 1138 require.Equal(t, uint32(retry), soaRec.Retry) 1139 require.Equal(t, uint32(ttl), soaRec.Hdr.Ttl) 1140 } 1141 // Default configuration 1142 testSoaWithConfig("", 0, 86400, 3600, 600) 1143 // Override all settings 1144 testSoaWithConfig("dns_config={soa={min_ttl=60,expire=43200,refresh=1800,retry=300}}", 60, 43200, 1800, 300) 1145 // Override partial settings 1146 testSoaWithConfig("dns_config={soa={min_ttl=60,expire=43200}}", 60, 43200, 3600, 600) 1147 // Override partial settings, part II 1148 testSoaWithConfig("dns_config={soa={refresh=1800,retry=300}}", 0, 86400, 1800, 300) 1149 } 1150 1151 func TestDNS_ServiceReverseLookupNodeAddress(t *testing.T) { 1152 t.Parallel() 1153 a := NewTestAgent(t, t.Name(), "") 1154 defer a.Shutdown() 1155 testrpc.WaitForLeader(t, a.RPC, "dc1") 1156 1157 // Register a node with a service. 1158 { 1159 args := &structs.RegisterRequest{ 1160 Datacenter: "dc1", 1161 Node: "foo", 1162 Address: "127.0.0.1", 1163 Service: &structs.NodeService{ 1164 Service: "db", 1165 Tags: []string{"master"}, 1166 Port: 12345, 1167 Address: "127.0.0.1", 1168 }, 1169 } 1170 1171 var out struct{} 1172 if err := a.RPC("Catalog.Register", args, &out); err != nil { 1173 t.Fatalf("err: %v", err) 1174 } 1175 } 1176 1177 m := new(dns.Msg) 1178 m.SetQuestion("1.0.0.127.in-addr.arpa.", dns.TypeANY) 1179 1180 c := new(dns.Client) 1181 in, _, err := c.Exchange(m, a.DNSAddr()) 1182 if err != nil { 1183 t.Fatalf("err: %v", err) 1184 } 1185 1186 if len(in.Answer) != 1 { 1187 t.Fatalf("Bad: %#v", in) 1188 } 1189 1190 ptrRec, ok := in.Answer[0].(*dns.PTR) 1191 if !ok { 1192 t.Fatalf("Bad: %#v", in.Answer[0]) 1193 } 1194 if ptrRec.Ptr != "foo.node.dc1.consul." { 1195 t.Fatalf("Bad: %#v", ptrRec) 1196 } 1197 } 1198 1199 func TestDNS_ServiceLookupNoMultiCNAME(t *testing.T) { 1200 t.Parallel() 1201 a := NewTestAgent(t, t.Name(), "") 1202 defer a.Shutdown() 1203 testrpc.WaitForLeader(t, a.RPC, "dc1") 1204 1205 // Register a node with a service. 1206 { 1207 args := &structs.RegisterRequest{ 1208 Datacenter: "dc1", 1209 Node: "foo", 1210 Address: "198.18.0.1", 1211 Service: &structs.NodeService{ 1212 Service: "db", 1213 Port: 12345, 1214 Address: "foo.node.consul", 1215 }, 1216 } 1217 1218 var out struct{} 1219 require.NoError(t, a.RPC("Catalog.Register", args, &out)) 1220 } 1221 1222 // Register a second node node with the same service. 1223 { 1224 args := &structs.RegisterRequest{ 1225 Datacenter: "dc1", 1226 Node: "bar", 1227 Address: "198.18.0.2", 1228 Service: &structs.NodeService{ 1229 Service: "db", 1230 Port: 12345, 1231 Address: "bar.node.consul", 1232 }, 1233 } 1234 1235 var out struct{} 1236 if err := a.RPC("Catalog.Register", args, &out); err != nil { 1237 t.Fatalf("err: %v", err) 1238 } 1239 } 1240 1241 m := new(dns.Msg) 1242 m.SetQuestion("db.service.consul.", dns.TypeANY) 1243 1244 c := new(dns.Client) 1245 in, _, err := c.Exchange(m, a.DNSAddr()) 1246 require.NoError(t, err) 1247 1248 // expect a CNAME and an A RR 1249 require.Len(t, in.Answer, 2) 1250 require.IsType(t, &dns.CNAME{}, in.Answer[0]) 1251 require.IsType(t, &dns.A{}, in.Answer[1]) 1252 } 1253 1254 func TestDNS_ServiceLookupPreferNoCNAME(t *testing.T) { 1255 t.Parallel() 1256 a := NewTestAgent(t, t.Name(), "") 1257 defer a.Shutdown() 1258 testrpc.WaitForLeader(t, a.RPC, "dc1") 1259 1260 // Register a node with a service. 1261 { 1262 args := &structs.RegisterRequest{ 1263 Datacenter: "dc1", 1264 Node: "foo", 1265 Address: "198.18.0.1", 1266 Service: &structs.NodeService{ 1267 Service: "db", 1268 Port: 12345, 1269 Address: "198.18.0.1", 1270 }, 1271 } 1272 1273 var out struct{} 1274 require.NoError(t, a.RPC("Catalog.Register", args, &out)) 1275 } 1276 1277 // Register a second node node with the same service. 1278 { 1279 args := &structs.RegisterRequest{ 1280 Datacenter: "dc1", 1281 Node: "bar", 1282 Address: "198.18.0.2", 1283 Service: &structs.NodeService{ 1284 Service: "db", 1285 Port: 12345, 1286 Address: "bar.node.consul", 1287 }, 1288 } 1289 1290 var out struct{} 1291 if err := a.RPC("Catalog.Register", args, &out); err != nil { 1292 t.Fatalf("err: %v", err) 1293 } 1294 } 1295 1296 m := new(dns.Msg) 1297 m.SetQuestion("db.service.consul.", dns.TypeANY) 1298 1299 c := new(dns.Client) 1300 in, _, err := c.Exchange(m, a.DNSAddr()) 1301 require.NoError(t, err) 1302 1303 // expect a CNAME and an A RR 1304 require.Len(t, in.Answer, 1) 1305 aRec, ok := in.Answer[0].(*dns.A) 1306 require.Truef(t, ok, "Not an A RR") 1307 1308 require.Equal(t, "db.service.consul.", aRec.Hdr.Name) 1309 require.Equal(t, "198.18.0.1", aRec.A.String()) 1310 } 1311 1312 func TestDNS_ServiceLookupMultiAddrNoCNAME(t *testing.T) { 1313 t.Parallel() 1314 a := NewTestAgent(t, t.Name(), "") 1315 defer a.Shutdown() 1316 testrpc.WaitForLeader(t, a.RPC, "dc1") 1317 1318 // Register a node with a service. 1319 { 1320 args := &structs.RegisterRequest{ 1321 Datacenter: "dc1", 1322 Node: "foo", 1323 Address: "198.18.0.1", 1324 Service: &structs.NodeService{ 1325 Service: "db", 1326 Port: 12345, 1327 Address: "198.18.0.1", 1328 }, 1329 } 1330 1331 var out struct{} 1332 require.NoError(t, a.RPC("Catalog.Register", args, &out)) 1333 } 1334 1335 // Register a second node node with the same service. 1336 { 1337 args := &structs.RegisterRequest{ 1338 Datacenter: "dc1", 1339 Node: "bar", 1340 Address: "198.18.0.2", 1341 Service: &structs.NodeService{ 1342 Service: "db", 1343 Port: 12345, 1344 Address: "bar.node.consul", 1345 }, 1346 } 1347 1348 var out struct{} 1349 if err := a.RPC("Catalog.Register", args, &out); err != nil { 1350 t.Fatalf("err: %v", err) 1351 } 1352 } 1353 1354 // Register a second node node with the same service. 1355 { 1356 args := &structs.RegisterRequest{ 1357 Datacenter: "dc1", 1358 Node: "baz", 1359 Address: "198.18.0.3", 1360 Service: &structs.NodeService{ 1361 Service: "db", 1362 Port: 12345, 1363 Address: "198.18.0.3", 1364 }, 1365 } 1366 1367 var out struct{} 1368 if err := a.RPC("Catalog.Register", args, &out); err != nil { 1369 t.Fatalf("err: %v", err) 1370 } 1371 } 1372 1373 m := new(dns.Msg) 1374 m.SetQuestion("db.service.consul.", dns.TypeANY) 1375 1376 c := new(dns.Client) 1377 in, _, err := c.Exchange(m, a.DNSAddr()) 1378 require.NoError(t, err) 1379 1380 // expect a CNAME and an A RR 1381 require.Len(t, in.Answer, 2) 1382 require.IsType(t, &dns.A{}, in.Answer[0]) 1383 require.IsType(t, &dns.A{}, in.Answer[1]) 1384 } 1385 1386 func TestDNS_ServiceLookup(t *testing.T) { 1387 t.Parallel() 1388 a := NewTestAgent(t, t.Name(), "") 1389 defer a.Shutdown() 1390 testrpc.WaitForLeader(t, a.RPC, "dc1") 1391 1392 // Register a node with a service. 1393 { 1394 args := &structs.RegisterRequest{ 1395 Datacenter: "dc1", 1396 Node: "foo", 1397 Address: "127.0.0.1", 1398 Service: &structs.NodeService{ 1399 Service: "db", 1400 Tags: []string{"master"}, 1401 Port: 12345, 1402 }, 1403 } 1404 1405 var out struct{} 1406 if err := a.RPC("Catalog.Register", args, &out); err != nil { 1407 t.Fatalf("err: %v", err) 1408 } 1409 } 1410 1411 // Register an equivalent prepared query. 1412 var id string 1413 { 1414 args := &structs.PreparedQueryRequest{ 1415 Datacenter: "dc1", 1416 Op: structs.PreparedQueryCreate, 1417 Query: &structs.PreparedQuery{ 1418 Name: "test", 1419 Service: structs.ServiceQuery{ 1420 Service: "db", 1421 }, 1422 }, 1423 } 1424 if err := a.RPC("PreparedQuery.Apply", args, &id); err != nil { 1425 t.Fatalf("err: %v", err) 1426 } 1427 } 1428 1429 // Look up the service directly and via prepared query. 1430 questions := []string{ 1431 "db.service.consul.", 1432 id + ".query.consul.", 1433 } 1434 for _, question := range questions { 1435 m := new(dns.Msg) 1436 m.SetQuestion(question, dns.TypeSRV) 1437 1438 c := new(dns.Client) 1439 in, _, err := c.Exchange(m, a.DNSAddr()) 1440 if err != nil { 1441 t.Fatalf("err: %v", err) 1442 } 1443 1444 if len(in.Answer) != 1 { 1445 t.Fatalf("Bad: %#v", in) 1446 } 1447 1448 srvRec, ok := in.Answer[0].(*dns.SRV) 1449 if !ok { 1450 t.Fatalf("Bad: %#v", in.Answer[0]) 1451 } 1452 if srvRec.Port != 12345 { 1453 t.Fatalf("Bad: %#v", srvRec) 1454 } 1455 if srvRec.Target != "foo.node.dc1.consul." { 1456 t.Fatalf("Bad: %#v", srvRec) 1457 } 1458 if srvRec.Hdr.Ttl != 0 { 1459 t.Fatalf("Bad: %#v", in.Answer[0]) 1460 } 1461 1462 aRec, ok := in.Extra[0].(*dns.A) 1463 if !ok { 1464 t.Fatalf("Bad: %#v", in.Extra[0]) 1465 } 1466 if aRec.Hdr.Name != "foo.node.dc1.consul." { 1467 t.Fatalf("Bad: %#v", in.Extra[0]) 1468 } 1469 if aRec.A.String() != "127.0.0.1" { 1470 t.Fatalf("Bad: %#v", in.Extra[0]) 1471 } 1472 if aRec.Hdr.Ttl != 0 { 1473 t.Fatalf("Bad: %#v", in.Extra[0]) 1474 } 1475 } 1476 1477 // Lookup a non-existing service/query, we should receive an SOA. 1478 questions = []string{ 1479 "nodb.service.consul.", 1480 "nope.query.consul.", 1481 } 1482 for _, question := range questions { 1483 m := new(dns.Msg) 1484 m.SetQuestion(question, dns.TypeSRV) 1485 1486 c := new(dns.Client) 1487 in, _, err := c.Exchange(m, a.DNSAddr()) 1488 if err != nil { 1489 t.Fatalf("err: %v", err) 1490 } 1491 1492 if len(in.Ns) != 1 { 1493 t.Fatalf("Bad: %#v", in) 1494 } 1495 1496 soaRec, ok := in.Ns[0].(*dns.SOA) 1497 if !ok { 1498 t.Fatalf("Bad: %#v", in.Ns[0]) 1499 } 1500 if soaRec.Hdr.Ttl != 0 { 1501 t.Fatalf("Bad: %#v", in.Ns[0]) 1502 } 1503 1504 } 1505 } 1506 1507 func TestDNS_ServiceLookupWithInternalServiceAddress(t *testing.T) { 1508 t.Parallel() 1509 a := NewTestAgent(t, t.Name(), ` 1510 node_name = "my.test-node" 1511 `) 1512 defer a.Shutdown() 1513 testrpc.WaitForLeader(t, a.RPC, "dc1") 1514 1515 // Register a node with a service. 1516 // The service is using the consul DNS name as service address 1517 // which triggers a lookup loop and a subsequent stack overflow 1518 // crash. 1519 args := &structs.RegisterRequest{ 1520 Datacenter: "dc1", 1521 Node: "foo", 1522 Address: "127.0.0.1", 1523 Service: &structs.NodeService{ 1524 Service: "db", 1525 Address: "db.service.consul", 1526 Port: 12345, 1527 }, 1528 } 1529 1530 var out struct{} 1531 if err := a.RPC("Catalog.Register", args, &out); err != nil { 1532 t.Fatalf("err: %v", err) 1533 } 1534 1535 // Looking up the service should not trigger a loop 1536 m := new(dns.Msg) 1537 m.SetQuestion("db.service.consul.", dns.TypeSRV) 1538 1539 c := new(dns.Client) 1540 in, _, err := c.Exchange(m, a.DNSAddr()) 1541 if err != nil { 1542 t.Fatalf("err: %v", err) 1543 } 1544 1545 wantAnswer := []dns.RR{ 1546 &dns.SRV{ 1547 Hdr: dns.RR_Header{Name: "db.service.consul.", Rrtype: 0x21, Class: 0x1, Rdlength: 0x1b}, 1548 Priority: 0x1, 1549 Weight: 0x1, 1550 Port: 12345, 1551 Target: "foo.node.dc1.consul.", 1552 }, 1553 } 1554 verify.Values(t, "answer", in.Answer, wantAnswer) 1555 wantExtra := []dns.RR{ 1556 &dns.CNAME{ 1557 Hdr: dns.RR_Header{Name: "foo.node.dc1.consul.", Rrtype: 0x5, Class: 0x1, Rdlength: 0x2}, 1558 Target: "db.service.consul.", 1559 }, 1560 &dns.A{ 1561 Hdr: dns.RR_Header{Name: "db.service.consul.", Rrtype: 0x1, Class: 0x1, Rdlength: 0x4}, 1562 A: []byte{0x7f, 0x0, 0x0, 0x1}, // 127.0.0.1 1563 }, 1564 } 1565 verify.Values(t, "extra", in.Extra, wantExtra) 1566 } 1567 1568 func TestDNS_ConnectServiceLookup(t *testing.T) { 1569 t.Parallel() 1570 1571 assert := assert.New(t) 1572 a := NewTestAgent(t, t.Name(), "") 1573 defer a.Shutdown() 1574 testrpc.WaitForLeader(t, a.RPC, "dc1") 1575 1576 // Register 1577 { 1578 args := structs.TestRegisterRequestProxy(t) 1579 args.Address = "127.0.0.55" 1580 args.Service.Proxy.DestinationServiceName = "db" 1581 args.Service.Address = "" 1582 args.Service.Port = 12345 1583 var out struct{} 1584 assert.Nil(a.RPC("Catalog.Register", args, &out)) 1585 } 1586 1587 // Look up the service 1588 questions := []string{ 1589 "db.connect.consul.", 1590 } 1591 for _, question := range questions { 1592 m := new(dns.Msg) 1593 m.SetQuestion(question, dns.TypeSRV) 1594 1595 c := new(dns.Client) 1596 in, _, err := c.Exchange(m, a.DNSAddr()) 1597 assert.Nil(err) 1598 assert.Len(in.Answer, 1) 1599 1600 srvRec, ok := in.Answer[0].(*dns.SRV) 1601 assert.True(ok) 1602 assert.Equal(uint16(12345), srvRec.Port) 1603 assert.Equal("foo.node.dc1.consul.", srvRec.Target) 1604 assert.Equal(uint32(0), srvRec.Hdr.Ttl) 1605 1606 cnameRec, ok := in.Extra[0].(*dns.A) 1607 assert.True(ok) 1608 assert.Equal("foo.node.dc1.consul.", cnameRec.Hdr.Name) 1609 assert.Equal(uint32(0), srvRec.Hdr.Ttl) 1610 assert.Equal("127.0.0.55", cnameRec.A.String()) 1611 } 1612 } 1613 1614 func TestDNS_ExternalServiceLookup(t *testing.T) { 1615 t.Parallel() 1616 a := NewTestAgent(t, t.Name(), "") 1617 defer a.Shutdown() 1618 testrpc.WaitForLeader(t, a.RPC, "dc1") 1619 1620 // Register a node with an external service. 1621 { 1622 args := &structs.RegisterRequest{ 1623 Datacenter: "dc1", 1624 Node: "foo", 1625 Address: "www.google.com", 1626 Service: &structs.NodeService{ 1627 Service: "db", 1628 Port: 12345, 1629 }, 1630 } 1631 1632 var out struct{} 1633 if err := a.RPC("Catalog.Register", args, &out); err != nil { 1634 t.Fatalf("err: %v", err) 1635 } 1636 } 1637 1638 // Look up the service 1639 questions := []string{ 1640 "db.service.consul.", 1641 } 1642 for _, question := range questions { 1643 m := new(dns.Msg) 1644 m.SetQuestion(question, dns.TypeSRV) 1645 1646 c := new(dns.Client) 1647 in, _, err := c.Exchange(m, a.DNSAddr()) 1648 if err != nil { 1649 t.Fatalf("err: %v", err) 1650 } 1651 1652 if len(in.Answer) != 1 { 1653 t.Fatalf("Bad: %#v", in) 1654 } 1655 1656 srvRec, ok := in.Answer[0].(*dns.SRV) 1657 if !ok { 1658 t.Fatalf("Bad: %#v", in.Answer[0]) 1659 } 1660 if srvRec.Port != 12345 { 1661 t.Fatalf("Bad: %#v", srvRec) 1662 } 1663 if srvRec.Target != "foo.node.dc1.consul." { 1664 t.Fatalf("Bad: %#v", srvRec) 1665 } 1666 if srvRec.Hdr.Ttl != 0 { 1667 t.Fatalf("Bad: %#v", in.Answer[0]) 1668 } 1669 1670 cnameRec, ok := in.Extra[0].(*dns.CNAME) 1671 if !ok { 1672 t.Fatalf("Bad: %#v", in.Extra[0]) 1673 } 1674 if cnameRec.Hdr.Name != "foo.node.dc1.consul." { 1675 t.Fatalf("Bad: %#v", in.Extra[0]) 1676 } 1677 if cnameRec.Target != "www.google.com." { 1678 t.Fatalf("Bad: %#v", in.Extra[0]) 1679 } 1680 if cnameRec.Hdr.Ttl != 0 { 1681 t.Fatalf("Bad: %#v", in.Extra[0]) 1682 } 1683 } 1684 } 1685 1686 func TestDNS_InifiniteRecursion(t *testing.T) { 1687 // This test should not create an infinite recursion 1688 t.Parallel() 1689 a := NewTestAgent(t, t.Name(), ` 1690 domain = "CONSUL." 1691 node_name = "test node" 1692 `) 1693 defer a.Shutdown() 1694 testrpc.WaitForLeader(t, a.RPC, "dc1") 1695 1696 // Register the initial node with a service 1697 { 1698 args := &structs.RegisterRequest{ 1699 Datacenter: "dc1", 1700 Node: "web", 1701 Address: "web.service.consul.", 1702 Service: &structs.NodeService{ 1703 Service: "web", 1704 Port: 12345, 1705 Address: "web.service.consul.", 1706 }, 1707 } 1708 1709 var out struct{} 1710 if err := a.RPC("Catalog.Register", args, &out); err != nil { 1711 t.Fatalf("err: %v", err) 1712 } 1713 } 1714 1715 // Look up the service directly 1716 questions := []string{ 1717 "web.service.consul.", 1718 } 1719 for _, question := range questions { 1720 m := new(dns.Msg) 1721 m.SetQuestion(question, dns.TypeA) 1722 c := new(dns.Client) 1723 in, _, err := c.Exchange(m, a.DNSAddr()) 1724 if err != nil { 1725 t.Fatalf("err: %v", err) 1726 } 1727 1728 if len(in.Answer) < 1 { 1729 t.Fatalf("Bad: %#v", in) 1730 } 1731 aRec, ok := in.Answer[0].(*dns.CNAME) 1732 if !ok { 1733 t.Fatalf("Bad: %#v", in.Answer[0]) 1734 } 1735 if aRec.Target != "web.service.consul." { 1736 t.Fatalf("Bad: %#v, target:=%s", aRec, aRec.Target) 1737 } 1738 } 1739 } 1740 1741 func TestDNS_ExternalServiceToConsulCNAMELookup(t *testing.T) { 1742 t.Parallel() 1743 a := NewTestAgent(t, t.Name(), ` 1744 domain = "CONSUL." 1745 node_name = "test node" 1746 `) 1747 defer a.Shutdown() 1748 testrpc.WaitForLeader(t, a.RPC, "dc1") 1749 1750 // Register the initial node with a service 1751 { 1752 args := &structs.RegisterRequest{ 1753 Datacenter: "dc1", 1754 Node: "web", 1755 Address: "127.0.0.1", 1756 Service: &structs.NodeService{ 1757 Service: "web", 1758 Port: 12345, 1759 }, 1760 } 1761 1762 var out struct{} 1763 if err := a.RPC("Catalog.Register", args, &out); err != nil { 1764 t.Fatalf("err: %v", err) 1765 } 1766 } 1767 1768 // Register an external service pointing to the 'web' service 1769 { 1770 args := &structs.RegisterRequest{ 1771 Datacenter: "dc1", 1772 Node: "alias", 1773 Address: "web.service.consul", 1774 Service: &structs.NodeService{ 1775 Service: "alias", 1776 Port: 12345, 1777 }, 1778 } 1779 1780 var out struct{} 1781 if err := a.RPC("Catalog.Register", args, &out); err != nil { 1782 t.Fatalf("err: %v", err) 1783 } 1784 } 1785 1786 // Look up the service directly 1787 questions := []string{ 1788 "alias.service.consul.", 1789 "alias.service.CoNsUl.", 1790 } 1791 for _, question := range questions { 1792 m := new(dns.Msg) 1793 m.SetQuestion(question, dns.TypeSRV) 1794 1795 c := new(dns.Client) 1796 in, _, err := c.Exchange(m, a.DNSAddr()) 1797 if err != nil { 1798 t.Fatalf("err: %v", err) 1799 } 1800 1801 if len(in.Answer) != 1 { 1802 t.Fatalf("Bad: %#v", in) 1803 } 1804 1805 srvRec, ok := in.Answer[0].(*dns.SRV) 1806 if !ok { 1807 t.Fatalf("Bad: %#v", in.Answer[0]) 1808 } 1809 if srvRec.Port != 12345 { 1810 t.Fatalf("Bad: %#v", srvRec) 1811 } 1812 if srvRec.Target != "alias.node.dc1.consul." { 1813 t.Fatalf("Bad: %#v", srvRec) 1814 } 1815 if srvRec.Hdr.Ttl != 0 { 1816 t.Fatalf("Bad: %#v", in.Answer[0]) 1817 } 1818 1819 if len(in.Extra) != 2 { 1820 t.Fatalf("Bad: %#v", in) 1821 } 1822 1823 cnameRec, ok := in.Extra[0].(*dns.CNAME) 1824 if !ok { 1825 t.Fatalf("Bad: %#v", in.Extra[0]) 1826 } 1827 if cnameRec.Hdr.Name != "alias.node.dc1.consul." { 1828 t.Fatalf("Bad: %#v", in.Extra[0]) 1829 } 1830 if cnameRec.Target != "web.service.consul." { 1831 t.Fatalf("Bad: %#v", in.Extra[0]) 1832 } 1833 if cnameRec.Hdr.Ttl != 0 { 1834 t.Fatalf("Bad: %#v", in.Extra[0]) 1835 } 1836 1837 aRec, ok := in.Extra[1].(*dns.A) 1838 if !ok { 1839 t.Fatalf("Bad: %#v", in.Extra[1]) 1840 } 1841 if aRec.Hdr.Name != "web.service.consul." { 1842 t.Fatalf("Bad: %#v", in.Extra[1]) 1843 } 1844 if aRec.A.String() != "127.0.0.1" { 1845 t.Fatalf("Bad: %#v", in.Extra[1]) 1846 } 1847 if aRec.Hdr.Ttl != 0 { 1848 t.Fatalf("Bad: %#v", in.Extra[1]) 1849 } 1850 1851 } 1852 } 1853 1854 func TestDNS_NSRecords(t *testing.T) { 1855 t.Parallel() 1856 a := NewTestAgent(t, t.Name(), ` 1857 domain = "CONSUL." 1858 node_name = "server1" 1859 `) 1860 defer a.Shutdown() 1861 testrpc.WaitForTestAgent(t, a.RPC, "dc1") 1862 1863 m := new(dns.Msg) 1864 m.SetQuestion("something.node.consul.", dns.TypeNS) 1865 1866 c := new(dns.Client) 1867 in, _, err := c.Exchange(m, a.DNSAddr()) 1868 if err != nil { 1869 t.Fatalf("err: %v", err) 1870 } 1871 1872 wantAnswer := []dns.RR{ 1873 &dns.NS{ 1874 Hdr: dns.RR_Header{Name: "consul.", Rrtype: dns.TypeNS, Class: dns.ClassINET, Ttl: 0, Rdlength: 0x13}, 1875 Ns: "server1.node.dc1.consul.", 1876 }, 1877 } 1878 verify.Values(t, "answer", in.Answer, wantAnswer) 1879 wantExtra := []dns.RR{ 1880 &dns.A{ 1881 Hdr: dns.RR_Header{Name: "server1.node.dc1.consul.", Rrtype: dns.TypeA, Class: dns.ClassINET, Rdlength: 0x4, Ttl: 0}, 1882 A: net.ParseIP("127.0.0.1").To4(), 1883 }, 1884 } 1885 1886 verify.Values(t, "extra", in.Extra, wantExtra) 1887 } 1888 1889 func TestDNS_NSRecords_IPV6(t *testing.T) { 1890 t.Parallel() 1891 a := NewTestAgent(t, t.Name(), ` 1892 domain = "CONSUL." 1893 node_name = "server1" 1894 advertise_addr = "::1" 1895 `) 1896 defer a.Shutdown() 1897 testrpc.WaitForTestAgent(t, a.RPC, "dc1") 1898 1899 m := new(dns.Msg) 1900 m.SetQuestion("server1.node.dc1.consul.", dns.TypeNS) 1901 1902 c := new(dns.Client) 1903 in, _, err := c.Exchange(m, a.DNSAddr()) 1904 if err != nil { 1905 t.Fatalf("err: %v", err) 1906 } 1907 1908 wantAnswer := []dns.RR{ 1909 &dns.NS{ 1910 Hdr: dns.RR_Header{Name: "consul.", Rrtype: dns.TypeNS, Class: dns.ClassINET, Ttl: 0, Rdlength: 0x2}, 1911 Ns: "server1.node.dc1.consul.", 1912 }, 1913 } 1914 verify.Values(t, "answer", in.Answer, wantAnswer) 1915 wantExtra := []dns.RR{ 1916 &dns.AAAA{ 1917 Hdr: dns.RR_Header{Name: "server1.node.dc1.consul.", Rrtype: dns.TypeAAAA, Class: dns.ClassINET, Rdlength: 0x10, Ttl: 0}, 1918 AAAA: net.ParseIP("::1"), 1919 }, 1920 } 1921 1922 verify.Values(t, "extra", in.Extra, wantExtra) 1923 1924 } 1925 1926 func TestDNS_ExternalServiceToConsulCNAMENestedLookup(t *testing.T) { 1927 t.Parallel() 1928 a := NewTestAgent(t, t.Name(), ` 1929 node_name = "test-node" 1930 `) 1931 defer a.Shutdown() 1932 testrpc.WaitForLeader(t, a.RPC, "dc1") 1933 1934 // Register the initial node with a service 1935 { 1936 args := &structs.RegisterRequest{ 1937 Datacenter: "dc1", 1938 Node: "web", 1939 Address: "127.0.0.1", 1940 Service: &structs.NodeService{ 1941 Service: "web", 1942 Port: 12345, 1943 }, 1944 } 1945 1946 var out struct{} 1947 if err := a.RPC("Catalog.Register", args, &out); err != nil { 1948 t.Fatalf("err: %v", err) 1949 } 1950 } 1951 1952 // Register an external service pointing to the 'web' service 1953 { 1954 args := &structs.RegisterRequest{ 1955 Datacenter: "dc1", 1956 Node: "alias", 1957 Address: "web.service.consul", 1958 Service: &structs.NodeService{ 1959 Service: "alias", 1960 Port: 12345, 1961 }, 1962 } 1963 1964 var out struct{} 1965 if err := a.RPC("Catalog.Register", args, &out); err != nil { 1966 t.Fatalf("err: %v", err) 1967 } 1968 } 1969 1970 // Register an external service pointing to the 'alias' service 1971 { 1972 args := &structs.RegisterRequest{ 1973 Datacenter: "dc1", 1974 Node: "alias2", 1975 Address: "alias.service.consul", 1976 Service: &structs.NodeService{ 1977 Service: "alias2", 1978 Port: 12345, 1979 }, 1980 } 1981 1982 var out struct{} 1983 if err := a.RPC("Catalog.Register", args, &out); err != nil { 1984 t.Fatalf("err: %v", err) 1985 } 1986 } 1987 1988 // Look up the service directly 1989 questions := []string{ 1990 "alias2.service.consul.", 1991 } 1992 for _, question := range questions { 1993 m := new(dns.Msg) 1994 m.SetQuestion(question, dns.TypeSRV) 1995 1996 c := new(dns.Client) 1997 in, _, err := c.Exchange(m, a.DNSAddr()) 1998 if err != nil { 1999 t.Fatalf("err: %v", err) 2000 } 2001 2002 if len(in.Answer) != 1 { 2003 t.Fatalf("Bad: %#v", in) 2004 } 2005 2006 srvRec, ok := in.Answer[0].(*dns.SRV) 2007 if !ok { 2008 t.Fatalf("Bad: %#v", in.Answer[0]) 2009 } 2010 if srvRec.Port != 12345 { 2011 t.Fatalf("Bad: %#v", srvRec) 2012 } 2013 if srvRec.Target != "alias2.node.dc1.consul." { 2014 t.Fatalf("Bad: %#v", srvRec) 2015 } 2016 if srvRec.Hdr.Ttl != 0 { 2017 t.Fatalf("Bad: %#v", in.Answer[0]) 2018 } 2019 2020 if len(in.Extra) != 3 { 2021 t.Fatalf("Bad: %#v", in) 2022 } 2023 2024 cnameRec, ok := in.Extra[0].(*dns.CNAME) 2025 if !ok { 2026 t.Fatalf("Bad: %#v", in.Extra[0]) 2027 } 2028 if cnameRec.Hdr.Name != "alias2.node.dc1.consul." { 2029 t.Fatalf("Bad: %#v", in.Extra[0]) 2030 } 2031 if cnameRec.Target != "alias.service.consul." { 2032 t.Fatalf("Bad: %#v", in.Extra[0]) 2033 } 2034 if cnameRec.Hdr.Ttl != 0 { 2035 t.Fatalf("Bad: %#v", in.Extra[0]) 2036 } 2037 2038 cnameRec, ok = in.Extra[1].(*dns.CNAME) 2039 if !ok { 2040 t.Fatalf("Bad: %#v", in.Extra[1]) 2041 } 2042 if cnameRec.Hdr.Name != "alias.service.consul." { 2043 t.Fatalf("Bad: %#v", in.Extra[1]) 2044 } 2045 if cnameRec.Target != "web.service.consul." { 2046 t.Fatalf("Bad: %#v", in.Extra[1]) 2047 } 2048 if cnameRec.Hdr.Ttl != 0 { 2049 t.Fatalf("Bad: %#v", in.Extra[1]) 2050 } 2051 2052 aRec, ok := in.Extra[2].(*dns.A) 2053 if !ok { 2054 t.Fatalf("Bad: %#v", in.Extra[2]) 2055 } 2056 if aRec.Hdr.Name != "web.service.consul." { 2057 t.Fatalf("Bad: %#v", in.Extra[1]) 2058 } 2059 if aRec.A.String() != "127.0.0.1" { 2060 t.Fatalf("Bad: %#v", in.Extra[2]) 2061 } 2062 if aRec.Hdr.Ttl != 0 { 2063 t.Fatalf("Bad: %#v", in.Extra[2]) 2064 } 2065 } 2066 } 2067 2068 func TestDNS_ServiceLookup_ServiceAddress_A(t *testing.T) { 2069 t.Parallel() 2070 a := NewTestAgent(t, t.Name(), "") 2071 defer a.Shutdown() 2072 testrpc.WaitForLeader(t, a.RPC, "dc1") 2073 2074 // Register a node with a service. 2075 { 2076 args := &structs.RegisterRequest{ 2077 Datacenter: "dc1", 2078 Node: "foo", 2079 Address: "127.0.0.1", 2080 Service: &structs.NodeService{ 2081 Service: "db", 2082 Tags: []string{"master"}, 2083 Address: "127.0.0.2", 2084 Port: 12345, 2085 }, 2086 } 2087 2088 var out struct{} 2089 if err := a.RPC("Catalog.Register", args, &out); err != nil { 2090 t.Fatalf("err: %v", err) 2091 } 2092 } 2093 2094 // Register an equivalent prepared query. 2095 var id string 2096 { 2097 args := &structs.PreparedQueryRequest{ 2098 Datacenter: "dc1", 2099 Op: structs.PreparedQueryCreate, 2100 Query: &structs.PreparedQuery{ 2101 Name: "test", 2102 Service: structs.ServiceQuery{ 2103 Service: "db", 2104 }, 2105 }, 2106 } 2107 if err := a.RPC("PreparedQuery.Apply", args, &id); err != nil { 2108 t.Fatalf("err: %v", err) 2109 } 2110 } 2111 2112 // Look up the service directly and via prepared query. 2113 questions := []string{ 2114 "db.service.consul.", 2115 id + ".query.consul.", 2116 } 2117 for _, question := range questions { 2118 m := new(dns.Msg) 2119 m.SetQuestion(question, dns.TypeSRV) 2120 2121 c := new(dns.Client) 2122 in, _, err := c.Exchange(m, a.DNSAddr()) 2123 if err != nil { 2124 t.Fatalf("err: %v", err) 2125 } 2126 2127 if len(in.Answer) != 1 { 2128 t.Fatalf("Bad: %#v", in) 2129 } 2130 2131 srvRec, ok := in.Answer[0].(*dns.SRV) 2132 if !ok { 2133 t.Fatalf("Bad: %#v", in.Answer[0]) 2134 } 2135 if srvRec.Port != 12345 { 2136 t.Fatalf("Bad: %#v", srvRec) 2137 } 2138 if srvRec.Target != "7f000002.addr.dc1.consul." { 2139 t.Fatalf("Bad: %#v", srvRec) 2140 } 2141 if srvRec.Hdr.Ttl != 0 { 2142 t.Fatalf("Bad: %#v", in.Answer[0]) 2143 } 2144 2145 aRec, ok := in.Extra[0].(*dns.A) 2146 if !ok { 2147 t.Fatalf("Bad: %#v", in.Extra[0]) 2148 } 2149 if aRec.Hdr.Name != "7f000002.addr.dc1.consul." { 2150 t.Fatalf("Bad: %#v", in.Extra[0]) 2151 } 2152 if aRec.A.String() != "127.0.0.2" { 2153 t.Fatalf("Bad: %#v", in.Extra[0]) 2154 } 2155 if aRec.Hdr.Ttl != 0 { 2156 t.Fatalf("Bad: %#v", in.Extra[0]) 2157 } 2158 } 2159 } 2160 2161 func TestDNS_ServiceLookup_ServiceAddress_CNAME(t *testing.T) { 2162 t.Parallel() 2163 a := NewTestAgent(t, t.Name(), "") 2164 defer a.Shutdown() 2165 testrpc.WaitForLeader(t, a.RPC, "dc1") 2166 2167 // Register a node with a service whose address isn't an IP. 2168 { 2169 args := &structs.RegisterRequest{ 2170 Datacenter: "dc1", 2171 Node: "foo", 2172 Address: "127.0.0.1", 2173 Service: &structs.NodeService{ 2174 Service: "db", 2175 Tags: []string{"master"}, 2176 Address: "www.google.com", 2177 Port: 12345, 2178 }, 2179 } 2180 2181 var out struct{} 2182 if err := a.RPC("Catalog.Register", args, &out); err != nil { 2183 t.Fatalf("err: %v", err) 2184 } 2185 } 2186 2187 // Register an equivalent prepared query. 2188 var id string 2189 { 2190 args := &structs.PreparedQueryRequest{ 2191 Datacenter: "dc1", 2192 Op: structs.PreparedQueryCreate, 2193 Query: &structs.PreparedQuery{ 2194 Name: "test", 2195 Service: structs.ServiceQuery{ 2196 Service: "db", 2197 }, 2198 }, 2199 } 2200 if err := a.RPC("PreparedQuery.Apply", args, &id); err != nil { 2201 t.Fatalf("err: %v", err) 2202 } 2203 } 2204 2205 // Look up the service directly and via prepared query. 2206 questions := []string{ 2207 "db.service.consul.", 2208 id + ".query.consul.", 2209 } 2210 for _, question := range questions { 2211 m := new(dns.Msg) 2212 m.SetQuestion(question, dns.TypeSRV) 2213 2214 c := new(dns.Client) 2215 in, _, err := c.Exchange(m, a.DNSAddr()) 2216 if err != nil { 2217 t.Fatalf("err: %v", err) 2218 } 2219 2220 if len(in.Answer) != 1 { 2221 t.Fatalf("Bad: %#v", in) 2222 } 2223 2224 srvRec, ok := in.Answer[0].(*dns.SRV) 2225 if !ok { 2226 t.Fatalf("Bad: %#v", in.Answer[0]) 2227 } 2228 if srvRec.Port != 12345 { 2229 t.Fatalf("Bad: %#v", srvRec) 2230 } 2231 if srvRec.Target != "foo.node.dc1.consul." { 2232 t.Fatalf("Bad: %#v", srvRec) 2233 } 2234 if srvRec.Hdr.Ttl != 0 { 2235 t.Fatalf("Bad: %#v", in.Answer[0]) 2236 } 2237 2238 cnameRec, ok := in.Extra[0].(*dns.CNAME) 2239 if !ok { 2240 t.Fatalf("Bad: %#v", in.Extra[0]) 2241 } 2242 if cnameRec.Hdr.Name != "foo.node.dc1.consul." { 2243 t.Fatalf("Bad: %#v", in.Extra[0]) 2244 } 2245 if cnameRec.Target != "www.google.com." { 2246 t.Fatalf("Bad: %#v", in.Extra[0]) 2247 } 2248 if cnameRec.Hdr.Ttl != 0 { 2249 t.Fatalf("Bad: %#v", in.Extra[0]) 2250 } 2251 } 2252 } 2253 2254 func TestDNS_ServiceLookup_ServiceAddressIPV6(t *testing.T) { 2255 t.Parallel() 2256 a := NewTestAgent(t, t.Name(), "") 2257 defer a.Shutdown() 2258 testrpc.WaitForLeader(t, a.RPC, "dc1") 2259 2260 // Register a node with a service. 2261 { 2262 args := &structs.RegisterRequest{ 2263 Datacenter: "dc1", 2264 Node: "foo", 2265 Address: "127.0.0.1", 2266 Service: &structs.NodeService{ 2267 Service: "db", 2268 Tags: []string{"master"}, 2269 Address: "2607:20:4005:808::200e", 2270 Port: 12345, 2271 }, 2272 } 2273 2274 var out struct{} 2275 if err := a.RPC("Catalog.Register", args, &out); err != nil { 2276 t.Fatalf("err: %v", err) 2277 } 2278 } 2279 2280 // Register an equivalent prepared query. 2281 var id string 2282 { 2283 args := &structs.PreparedQueryRequest{ 2284 Datacenter: "dc1", 2285 Op: structs.PreparedQueryCreate, 2286 Query: &structs.PreparedQuery{ 2287 Name: "test", 2288 Service: structs.ServiceQuery{ 2289 Service: "db", 2290 }, 2291 }, 2292 } 2293 if err := a.RPC("PreparedQuery.Apply", args, &id); err != nil { 2294 t.Fatalf("err: %v", err) 2295 } 2296 } 2297 2298 // Look up the service directly and via prepared query. 2299 questions := []string{ 2300 "db.service.consul.", 2301 id + ".query.consul.", 2302 } 2303 for _, question := range questions { 2304 m := new(dns.Msg) 2305 m.SetQuestion(question, dns.TypeSRV) 2306 2307 c := new(dns.Client) 2308 in, _, err := c.Exchange(m, a.DNSAddr()) 2309 if err != nil { 2310 t.Fatalf("err: %v", err) 2311 } 2312 2313 if len(in.Answer) != 1 { 2314 t.Fatalf("Bad: %#v", in) 2315 } 2316 2317 srvRec, ok := in.Answer[0].(*dns.SRV) 2318 if !ok { 2319 t.Fatalf("Bad: %#v", in.Answer[0]) 2320 } 2321 if srvRec.Port != 12345 { 2322 t.Fatalf("Bad: %#v", srvRec) 2323 } 2324 if srvRec.Target != "2607002040050808000000000000200e.addr.dc1.consul." { 2325 t.Fatalf("Bad: %#v", srvRec) 2326 } 2327 if srvRec.Hdr.Ttl != 0 { 2328 t.Fatalf("Bad: %#v", in.Answer[0]) 2329 } 2330 2331 aRec, ok := in.Extra[0].(*dns.AAAA) 2332 if !ok { 2333 t.Fatalf("Bad: %#v", in.Extra[0]) 2334 } 2335 if aRec.Hdr.Name != "2607002040050808000000000000200e.addr.dc1.consul." { 2336 t.Fatalf("Bad: %#v", in.Extra[0]) 2337 } 2338 if aRec.AAAA.String() != "2607:20:4005:808::200e" { 2339 t.Fatalf("Bad: %#v", in.Extra[0]) 2340 } 2341 if aRec.Hdr.Ttl != 0 { 2342 t.Fatalf("Bad: %#v", in.Extra[0]) 2343 } 2344 } 2345 } 2346 2347 func TestDNS_ServiceLookup_WanAddress(t *testing.T) { 2348 t.Parallel() 2349 a1 := NewTestAgent(t, t.Name(), ` 2350 datacenter = "dc1" 2351 translate_wan_addrs = true 2352 acl_datacenter = "" 2353 `) 2354 defer a1.Shutdown() 2355 2356 a2 := NewTestAgent(t, t.Name(), ` 2357 datacenter = "dc2" 2358 translate_wan_addrs = true 2359 acl_datacenter = "" 2360 `) 2361 defer a2.Shutdown() 2362 2363 // Join WAN cluster 2364 addr := fmt.Sprintf("127.0.0.1:%d", a1.Config.SerfPortWAN) 2365 if _, err := a2.JoinWAN([]string{addr}); err != nil { 2366 t.Fatalf("err: %v", err) 2367 } 2368 retry.Run(t, func(r *retry.R) { 2369 if got, want := len(a1.WANMembers()), 2; got < want { 2370 r.Fatalf("got %d WAN members want at least %d", got, want) 2371 } 2372 if got, want := len(a2.WANMembers()), 2; got < want { 2373 r.Fatalf("got %d WAN members want at least %d", got, want) 2374 } 2375 }) 2376 2377 // Register a remote node with a service. This is in a retry since we 2378 // need the datacenter to have a route which takes a little more time 2379 // beyond the join, and we don't have direct access to the router here. 2380 retry.Run(t, func(r *retry.R) { 2381 args := &structs.RegisterRequest{ 2382 Datacenter: "dc2", 2383 Node: "foo", 2384 Address: "127.0.0.1", 2385 TaggedAddresses: map[string]string{ 2386 "wan": "127.0.0.2", 2387 }, 2388 Service: &structs.NodeService{ 2389 Service: "db", 2390 }, 2391 } 2392 2393 var out struct{} 2394 if err := a2.RPC("Catalog.Register", args, &out); err != nil { 2395 r.Fatalf("err: %v", err) 2396 } 2397 }) 2398 2399 // Register an equivalent prepared query. 2400 var id string 2401 { 2402 args := &structs.PreparedQueryRequest{ 2403 Datacenter: "dc2", 2404 Op: structs.PreparedQueryCreate, 2405 Query: &structs.PreparedQuery{ 2406 Name: "test", 2407 Service: structs.ServiceQuery{ 2408 Service: "db", 2409 }, 2410 }, 2411 } 2412 if err := a2.RPC("PreparedQuery.Apply", args, &id); err != nil { 2413 t.Fatalf("err: %v", err) 2414 } 2415 } 2416 2417 // Look up the SRV record via service and prepared query. 2418 questions := []string{ 2419 "db.service.dc2.consul.", 2420 id + ".query.dc2.consul.", 2421 } 2422 for _, question := range questions { 2423 m := new(dns.Msg) 2424 m.SetQuestion(question, dns.TypeSRV) 2425 2426 c := new(dns.Client) 2427 2428 addr := a1.config.DNSAddrs[0] 2429 in, _, err := c.Exchange(m, addr.String()) 2430 if err != nil { 2431 t.Fatalf("err: %v", err) 2432 } 2433 2434 if len(in.Answer) != 1 { 2435 t.Fatalf("Bad: %#v", in) 2436 } 2437 2438 aRec, ok := in.Extra[0].(*dns.A) 2439 if !ok { 2440 t.Fatalf("Bad: %#v", in.Extra[0]) 2441 } 2442 if aRec.Hdr.Name != "7f000002.addr.dc2.consul." { 2443 t.Fatalf("Bad: %#v", in.Extra[0]) 2444 } 2445 if aRec.A.String() != "127.0.0.2" { 2446 t.Fatalf("Bad: %#v", in.Extra[0]) 2447 } 2448 } 2449 2450 // Also check the A record directly 2451 for _, question := range questions { 2452 m := new(dns.Msg) 2453 m.SetQuestion(question, dns.TypeA) 2454 2455 c := new(dns.Client) 2456 addr := a1.config.DNSAddrs[0] 2457 in, _, err := c.Exchange(m, addr.String()) 2458 if err != nil { 2459 t.Fatalf("err: %v", err) 2460 } 2461 2462 if len(in.Answer) != 1 { 2463 t.Fatalf("Bad: %#v", in) 2464 } 2465 2466 aRec, ok := in.Answer[0].(*dns.A) 2467 if !ok { 2468 t.Fatalf("Bad: %#v", in.Answer[0]) 2469 } 2470 if aRec.Hdr.Name != question { 2471 t.Fatalf("Bad: %#v", in.Answer[0]) 2472 } 2473 if aRec.A.String() != "127.0.0.2" { 2474 t.Fatalf("Bad: %#v", in.Answer[0]) 2475 } 2476 } 2477 2478 // Now query from the same DC and make sure we get the local address 2479 for _, question := range questions { 2480 m := new(dns.Msg) 2481 m.SetQuestion(question, dns.TypeSRV) 2482 2483 c := new(dns.Client) 2484 addr := a2.Config.DNSAddrs[0] 2485 in, _, err := c.Exchange(m, addr.String()) 2486 if err != nil { 2487 t.Fatalf("err: %v", err) 2488 } 2489 2490 if len(in.Answer) != 1 { 2491 t.Fatalf("Bad: %#v", in) 2492 } 2493 2494 aRec, ok := in.Extra[0].(*dns.A) 2495 if !ok { 2496 t.Fatalf("Bad: %#v", in.Extra[0]) 2497 } 2498 if aRec.Hdr.Name != "foo.node.dc2.consul." { 2499 t.Fatalf("Bad: %#v", in.Extra[0]) 2500 } 2501 if aRec.A.String() != "127.0.0.1" { 2502 t.Fatalf("Bad: %#v", in.Extra[0]) 2503 } 2504 } 2505 2506 // Also check the A record directly from DC2 2507 for _, question := range questions { 2508 m := new(dns.Msg) 2509 m.SetQuestion(question, dns.TypeA) 2510 2511 c := new(dns.Client) 2512 addr := a2.Config.DNSAddrs[0] 2513 in, _, err := c.Exchange(m, addr.String()) 2514 if err != nil { 2515 t.Fatalf("err: %v", err) 2516 } 2517 2518 if len(in.Answer) != 1 { 2519 t.Fatalf("Bad: %#v", in) 2520 } 2521 2522 aRec, ok := in.Answer[0].(*dns.A) 2523 if !ok { 2524 t.Fatalf("Bad: %#v", in.Answer[0]) 2525 } 2526 if aRec.Hdr.Name != question { 2527 t.Fatalf("Bad: %#v", in.Answer[0]) 2528 } 2529 if aRec.A.String() != "127.0.0.1" { 2530 t.Fatalf("Bad: %#v", in.Answer[0]) 2531 } 2532 } 2533 } 2534 2535 func TestDNS_CaseInsensitiveServiceLookup(t *testing.T) { 2536 t.Parallel() 2537 a := NewTestAgent(t, t.Name(), "") 2538 defer a.Shutdown() 2539 testrpc.WaitForLeader(t, a.RPC, "dc1") 2540 2541 // Register a node with a service. 2542 { 2543 args := &structs.RegisterRequest{ 2544 Datacenter: "dc1", 2545 Node: "foo", 2546 Address: "127.0.0.1", 2547 Service: &structs.NodeService{ 2548 Service: "Db", 2549 Tags: []string{"Master"}, 2550 Port: 12345, 2551 }, 2552 } 2553 2554 var out struct{} 2555 if err := a.RPC("Catalog.Register", args, &out); err != nil { 2556 t.Fatalf("err: %v", err) 2557 } 2558 } 2559 2560 // Register an equivalent prepared query, as well as a name. 2561 var id string 2562 { 2563 args := &structs.PreparedQueryRequest{ 2564 Datacenter: "dc1", 2565 Op: structs.PreparedQueryCreate, 2566 Query: &structs.PreparedQuery{ 2567 Name: "somequery", 2568 Service: structs.ServiceQuery{ 2569 Service: "db", 2570 }, 2571 }, 2572 } 2573 if err := a.RPC("PreparedQuery.Apply", args, &id); err != nil { 2574 t.Fatalf("err: %v", err) 2575 } 2576 } 2577 2578 // Try some variations to make sure case doesn't matter. 2579 questions := []string{ 2580 "master.db.service.consul.", 2581 "mASTER.dB.service.consul.", 2582 "MASTER.dB.service.consul.", 2583 "db.service.consul.", 2584 "DB.service.consul.", 2585 "Db.service.consul.", 2586 "somequery.query.consul.", 2587 "SomeQuery.query.consul.", 2588 "SOMEQUERY.query.consul.", 2589 } 2590 for _, question := range questions { 2591 m := new(dns.Msg) 2592 m.SetQuestion(question, dns.TypeSRV) 2593 2594 c := new(dns.Client) 2595 in, _, err := c.Exchange(m, a.DNSAddr()) 2596 if err != nil { 2597 t.Fatalf("err: %v", err) 2598 } 2599 2600 if len(in.Answer) != 1 { 2601 t.Fatalf("empty lookup: %#v", in) 2602 } 2603 } 2604 } 2605 2606 func TestDNS_ServiceLookup_TagPeriod(t *testing.T) { 2607 t.Parallel() 2608 a := NewTestAgent(t, t.Name(), "") 2609 defer a.Shutdown() 2610 testrpc.WaitForLeader(t, a.RPC, "dc1") 2611 2612 // Register node 2613 args := &structs.RegisterRequest{ 2614 Datacenter: "dc1", 2615 Node: "foo", 2616 Address: "127.0.0.1", 2617 Service: &structs.NodeService{ 2618 Service: "db", 2619 Tags: []string{"v1.master"}, 2620 Port: 12345, 2621 }, 2622 } 2623 2624 var out struct{} 2625 if err := a.RPC("Catalog.Register", args, &out); err != nil { 2626 t.Fatalf("err: %v", err) 2627 } 2628 2629 m1 := new(dns.Msg) 2630 m1.SetQuestion("v1.master2.db.service.consul.", dns.TypeSRV) 2631 2632 c1 := new(dns.Client) 2633 in, _, err := c1.Exchange(m1, a.DNSAddr()) 2634 if err != nil { 2635 t.Fatalf("err: %v", err) 2636 } 2637 2638 if len(in.Answer) != 0 { 2639 t.Fatalf("Bad: %#v", in) 2640 } 2641 2642 m := new(dns.Msg) 2643 m.SetQuestion("v1.master.db.service.consul.", dns.TypeSRV) 2644 2645 c := new(dns.Client) 2646 in, _, err = c.Exchange(m, a.DNSAddr()) 2647 if err != nil { 2648 t.Fatalf("err: %v", err) 2649 } 2650 2651 if len(in.Answer) != 1 { 2652 t.Fatalf("Bad: %#v", in) 2653 } 2654 2655 srvRec, ok := in.Answer[0].(*dns.SRV) 2656 if !ok { 2657 t.Fatalf("Bad: %#v", in.Answer[0]) 2658 } 2659 if srvRec.Port != 12345 { 2660 t.Fatalf("Bad: %#v", srvRec) 2661 } 2662 if srvRec.Target != "foo.node.dc1.consul." { 2663 t.Fatalf("Bad: %#v", srvRec) 2664 } 2665 2666 aRec, ok := in.Extra[0].(*dns.A) 2667 if !ok { 2668 t.Fatalf("Bad: %#v", in.Extra[0]) 2669 } 2670 if aRec.Hdr.Name != "foo.node.dc1.consul." { 2671 t.Fatalf("Bad: %#v", in.Extra[0]) 2672 } 2673 if aRec.A.String() != "127.0.0.1" { 2674 t.Fatalf("Bad: %#v", in.Extra[0]) 2675 } 2676 } 2677 2678 func TestDNS_PreparedQueryNearIPEDNS(t *testing.T) { 2679 ipCoord := lib.GenerateCoordinate(1 * time.Millisecond) 2680 serviceNodes := []struct { 2681 name string 2682 address string 2683 coord *coordinate.Coordinate 2684 }{ 2685 {"foo1", "198.18.0.1", lib.GenerateCoordinate(1 * time.Millisecond)}, 2686 {"foo2", "198.18.0.2", lib.GenerateCoordinate(10 * time.Millisecond)}, 2687 {"foo3", "198.18.0.3", lib.GenerateCoordinate(30 * time.Millisecond)}, 2688 } 2689 2690 t.Parallel() 2691 a := NewTestAgent(t, t.Name(), "") 2692 defer a.Shutdown() 2693 testrpc.WaitForLeader(t, a.RPC, "dc1") 2694 2695 added := 0 2696 2697 // Register nodes with a service 2698 for _, cfg := range serviceNodes { 2699 args := &structs.RegisterRequest{ 2700 Datacenter: "dc1", 2701 Node: cfg.name, 2702 Address: cfg.address, 2703 Service: &structs.NodeService{ 2704 Service: "db", 2705 Port: 12345, 2706 }, 2707 } 2708 2709 var out struct{} 2710 err := a.RPC("Catalog.Register", args, &out) 2711 require.NoError(t, err) 2712 2713 // Send coordinate updates 2714 coordArgs := structs.CoordinateUpdateRequest{ 2715 Datacenter: "dc1", 2716 Node: cfg.name, 2717 Coord: cfg.coord, 2718 } 2719 err = a.RPC("Coordinate.Update", &coordArgs, &out) 2720 require.NoError(t, err) 2721 2722 added += 1 2723 } 2724 2725 fmt.Printf("Added %d service nodes\n", added) 2726 2727 // Register a node without a service 2728 { 2729 args := &structs.RegisterRequest{ 2730 Datacenter: "dc1", 2731 Node: "bar", 2732 Address: "198.18.0.9", 2733 } 2734 2735 var out struct{} 2736 err := a.RPC("Catalog.Register", args, &out) 2737 require.NoError(t, err) 2738 2739 // Send coordinate updates for a few nodes. 2740 coordArgs := structs.CoordinateUpdateRequest{ 2741 Datacenter: "dc1", 2742 Node: "bar", 2743 Coord: ipCoord, 2744 } 2745 err = a.RPC("Coordinate.Update", &coordArgs, &out) 2746 require.NoError(t, err) 2747 } 2748 2749 // Register a prepared query Near = _ip 2750 { 2751 args := &structs.PreparedQueryRequest{ 2752 Datacenter: "dc1", 2753 Op: structs.PreparedQueryCreate, 2754 Query: &structs.PreparedQuery{ 2755 Name: "some.query.we.like", 2756 Service: structs.ServiceQuery{ 2757 Service: "db", 2758 Near: "_ip", 2759 }, 2760 }, 2761 } 2762 2763 var id string 2764 err := a.RPC("PreparedQuery.Apply", args, &id) 2765 require.NoError(t, err) 2766 } 2767 retry.Run(t, func(r *retry.R) { 2768 m := new(dns.Msg) 2769 m.SetQuestion("some.query.we.like.query.consul.", dns.TypeA) 2770 m.SetEdns0(4096, false) 2771 o := new(dns.OPT) 2772 o.Hdr.Name = "." 2773 o.Hdr.Rrtype = dns.TypeOPT 2774 e := new(dns.EDNS0_SUBNET) 2775 e.Code = dns.EDNS0SUBNET 2776 e.Family = 1 2777 e.SourceNetmask = 32 2778 e.SourceScope = 0 2779 e.Address = net.ParseIP("198.18.0.9").To4() 2780 o.Option = append(o.Option, e) 2781 m.Extra = append(m.Extra, o) 2782 2783 c := new(dns.Client) 2784 in, _, err := c.Exchange(m, a.DNSAddr()) 2785 if err != nil { 2786 r.Fatalf("Error with call to dns.Client.Exchange: %s", err) 2787 } 2788 2789 if len(serviceNodes) != len(in.Answer) { 2790 r.Fatalf("Expecting %d A RRs in response, Actual found was %d", len(serviceNodes), len(in.Answer)) 2791 } 2792 2793 for i, rr := range in.Answer { 2794 if aRec, ok := rr.(*dns.A); ok { 2795 if actual := aRec.A.String(); serviceNodes[i].address != actual { 2796 r.Fatalf("Expecting A RR #%d = %s, Actual RR was %s", i, serviceNodes[i].address, actual) 2797 } 2798 } else { 2799 r.Fatalf("DNS Answer contained a non-A RR") 2800 } 2801 } 2802 }) 2803 } 2804 2805 func TestDNS_PreparedQueryNearIP(t *testing.T) { 2806 ipCoord := lib.GenerateCoordinate(1 * time.Millisecond) 2807 serviceNodes := []struct { 2808 name string 2809 address string 2810 coord *coordinate.Coordinate 2811 }{ 2812 {"foo1", "198.18.0.1", lib.GenerateCoordinate(1 * time.Millisecond)}, 2813 {"foo2", "198.18.0.2", lib.GenerateCoordinate(10 * time.Millisecond)}, 2814 {"foo3", "198.18.0.3", lib.GenerateCoordinate(30 * time.Millisecond)}, 2815 } 2816 2817 t.Parallel() 2818 a := NewTestAgent(t, t.Name(), "") 2819 defer a.Shutdown() 2820 testrpc.WaitForLeader(t, a.RPC, "dc1") 2821 2822 added := 0 2823 2824 // Register nodes with a service 2825 for _, cfg := range serviceNodes { 2826 args := &structs.RegisterRequest{ 2827 Datacenter: "dc1", 2828 Node: cfg.name, 2829 Address: cfg.address, 2830 Service: &structs.NodeService{ 2831 Service: "db", 2832 Port: 12345, 2833 }, 2834 } 2835 2836 var out struct{} 2837 err := a.RPC("Catalog.Register", args, &out) 2838 require.NoError(t, err) 2839 2840 // Send coordinate updates 2841 coordArgs := structs.CoordinateUpdateRequest{ 2842 Datacenter: "dc1", 2843 Node: cfg.name, 2844 Coord: cfg.coord, 2845 } 2846 err = a.RPC("Coordinate.Update", &coordArgs, &out) 2847 require.NoError(t, err) 2848 2849 added += 1 2850 } 2851 2852 fmt.Printf("Added %d service nodes\n", added) 2853 2854 // Register a node without a service 2855 { 2856 args := &structs.RegisterRequest{ 2857 Datacenter: "dc1", 2858 Node: "bar", 2859 Address: "198.18.0.9", 2860 } 2861 2862 var out struct{} 2863 err := a.RPC("Catalog.Register", args, &out) 2864 require.NoError(t, err) 2865 2866 // Send coordinate updates for a few nodes. 2867 coordArgs := structs.CoordinateUpdateRequest{ 2868 Datacenter: "dc1", 2869 Node: "bar", 2870 Coord: ipCoord, 2871 } 2872 err = a.RPC("Coordinate.Update", &coordArgs, &out) 2873 require.NoError(t, err) 2874 } 2875 2876 // Register a prepared query Near = _ip 2877 { 2878 args := &structs.PreparedQueryRequest{ 2879 Datacenter: "dc1", 2880 Op: structs.PreparedQueryCreate, 2881 Query: &structs.PreparedQuery{ 2882 Name: "some.query.we.like", 2883 Service: structs.ServiceQuery{ 2884 Service: "db", 2885 Near: "_ip", 2886 }, 2887 }, 2888 } 2889 2890 var id string 2891 err := a.RPC("PreparedQuery.Apply", args, &id) 2892 require.NoError(t, err) 2893 } 2894 2895 retry.Run(t, func(r *retry.R) { 2896 m := new(dns.Msg) 2897 m.SetQuestion("some.query.we.like.query.consul.", dns.TypeA) 2898 2899 c := new(dns.Client) 2900 in, _, err := c.Exchange(m, a.DNSAddr()) 2901 if err != nil { 2902 r.Fatalf("Error with call to dns.Client.Exchange: %s", err) 2903 } 2904 2905 if len(serviceNodes) != len(in.Answer) { 2906 r.Fatalf("Expecting %d A RRs in response, Actual found was %d", len(serviceNodes), len(in.Answer)) 2907 } 2908 2909 for i, rr := range in.Answer { 2910 if aRec, ok := rr.(*dns.A); ok { 2911 if actual := aRec.A.String(); serviceNodes[i].address != actual { 2912 r.Fatalf("Expecting A RR #%d = %s, Actual RR was %s", i, serviceNodes[i].address, actual) 2913 } 2914 } else { 2915 r.Fatalf("DNS Answer contained a non-A RR") 2916 } 2917 } 2918 }) 2919 } 2920 2921 func TestDNS_ServiceLookup_PreparedQueryNamePeriod(t *testing.T) { 2922 t.Parallel() 2923 a := NewTestAgent(t, t.Name(), "") 2924 defer a.Shutdown() 2925 testrpc.WaitForLeader(t, a.RPC, "dc1") 2926 2927 // Register a node with a service. 2928 { 2929 args := &structs.RegisterRequest{ 2930 Datacenter: "dc1", 2931 Node: "foo", 2932 Address: "127.0.0.1", 2933 Service: &structs.NodeService{ 2934 Service: "db", 2935 Port: 12345, 2936 }, 2937 } 2938 2939 var out struct{} 2940 if err := a.RPC("Catalog.Register", args, &out); err != nil { 2941 t.Fatalf("err: %v", err) 2942 } 2943 } 2944 2945 // Register a prepared query with a period in the name. 2946 { 2947 args := &structs.PreparedQueryRequest{ 2948 Datacenter: "dc1", 2949 Op: structs.PreparedQueryCreate, 2950 Query: &structs.PreparedQuery{ 2951 Name: "some.query.we.like", 2952 Service: structs.ServiceQuery{ 2953 Service: "db", 2954 }, 2955 }, 2956 } 2957 2958 var id string 2959 if err := a.RPC("PreparedQuery.Apply", args, &id); err != nil { 2960 t.Fatalf("err: %v", err) 2961 } 2962 } 2963 2964 m := new(dns.Msg) 2965 m.SetQuestion("some.query.we.like.query.consul.", dns.TypeSRV) 2966 2967 c := new(dns.Client) 2968 in, _, err := c.Exchange(m, a.DNSAddr()) 2969 if err != nil { 2970 t.Fatalf("err: %v", err) 2971 } 2972 2973 if len(in.Answer) != 1 { 2974 t.Fatalf("Bad: %#v", in) 2975 } 2976 2977 srvRec, ok := in.Answer[0].(*dns.SRV) 2978 if !ok { 2979 t.Fatalf("Bad: %#v", in.Answer[0]) 2980 } 2981 if srvRec.Port != 12345 { 2982 t.Fatalf("Bad: %#v", srvRec) 2983 } 2984 if srvRec.Target != "foo.node.dc1.consul." { 2985 t.Fatalf("Bad: %#v", srvRec) 2986 } 2987 2988 aRec, ok := in.Extra[0].(*dns.A) 2989 if !ok { 2990 t.Fatalf("Bad: %#v", in.Extra[0]) 2991 } 2992 if aRec.Hdr.Name != "foo.node.dc1.consul." { 2993 t.Fatalf("Bad: %#v", in.Extra[0]) 2994 } 2995 if aRec.A.String() != "127.0.0.1" { 2996 t.Fatalf("Bad: %#v", in.Extra[0]) 2997 } 2998 } 2999 3000 func TestDNS_ServiceLookup_Dedup(t *testing.T) { 3001 t.Parallel() 3002 a := NewTestAgent(t, t.Name(), "") 3003 defer a.Shutdown() 3004 testrpc.WaitForLeader(t, a.RPC, "dc1") 3005 3006 // Register a single node with multiple instances of a service. 3007 { 3008 args := &structs.RegisterRequest{ 3009 Datacenter: "dc1", 3010 Node: "foo", 3011 Address: "127.0.0.1", 3012 Service: &structs.NodeService{ 3013 Service: "db", 3014 Tags: []string{"master"}, 3015 Port: 12345, 3016 }, 3017 } 3018 3019 var out struct{} 3020 if err := a.RPC("Catalog.Register", args, &out); err != nil { 3021 t.Fatalf("err: %v", err) 3022 } 3023 3024 args = &structs.RegisterRequest{ 3025 Datacenter: "dc1", 3026 Node: "foo", 3027 Address: "127.0.0.1", 3028 Service: &structs.NodeService{ 3029 ID: "db2", 3030 Service: "db", 3031 Tags: []string{"slave"}, 3032 Port: 12345, 3033 }, 3034 } 3035 if err := a.RPC("Catalog.Register", args, &out); err != nil { 3036 t.Fatalf("err: %v", err) 3037 } 3038 3039 args = &structs.RegisterRequest{ 3040 Datacenter: "dc1", 3041 Node: "foo", 3042 Address: "127.0.0.1", 3043 Service: &structs.NodeService{ 3044 ID: "db3", 3045 Service: "db", 3046 Tags: []string{"slave"}, 3047 Port: 12346, 3048 }, 3049 } 3050 if err := a.RPC("Catalog.Register", args, &out); err != nil { 3051 t.Fatalf("err: %v", err) 3052 } 3053 } 3054 3055 // Register an equivalent prepared query. 3056 var id string 3057 { 3058 args := &structs.PreparedQueryRequest{ 3059 Datacenter: "dc1", 3060 Op: structs.PreparedQueryCreate, 3061 Query: &structs.PreparedQuery{ 3062 Name: "test", 3063 Service: structs.ServiceQuery{ 3064 Service: "db", 3065 }, 3066 }, 3067 } 3068 if err := a.RPC("PreparedQuery.Apply", args, &id); err != nil { 3069 t.Fatalf("err: %v", err) 3070 } 3071 } 3072 3073 // Look up the service directly and via prepared query, make sure only 3074 // one IP is returned. 3075 questions := []string{ 3076 "db.service.consul.", 3077 id + ".query.consul.", 3078 } 3079 for _, question := range questions { 3080 m := new(dns.Msg) 3081 m.SetQuestion(question, dns.TypeANY) 3082 3083 c := new(dns.Client) 3084 in, _, err := c.Exchange(m, a.DNSAddr()) 3085 if err != nil { 3086 t.Fatalf("err: %v", err) 3087 } 3088 3089 if len(in.Answer) != 1 { 3090 t.Fatalf("Bad: %#v", in) 3091 } 3092 3093 aRec, ok := in.Answer[0].(*dns.A) 3094 if !ok { 3095 t.Fatalf("Bad: %#v", in.Answer[0]) 3096 } 3097 if aRec.A.String() != "127.0.0.1" { 3098 t.Fatalf("Bad: %#v", in.Answer[0]) 3099 } 3100 } 3101 } 3102 3103 func TestDNS_ServiceLookup_Dedup_SRV(t *testing.T) { 3104 t.Parallel() 3105 a := NewTestAgent(t, t.Name(), "") 3106 defer a.Shutdown() 3107 testrpc.WaitForLeader(t, a.RPC, "dc1") 3108 3109 // Register a single node with multiple instances of a service. 3110 { 3111 args := &structs.RegisterRequest{ 3112 Datacenter: "dc1", 3113 Node: "foo", 3114 Address: "127.0.0.1", 3115 Service: &structs.NodeService{ 3116 Service: "db", 3117 Tags: []string{"master"}, 3118 Port: 12345, 3119 }, 3120 } 3121 3122 var out struct{} 3123 if err := a.RPC("Catalog.Register", args, &out); err != nil { 3124 t.Fatalf("err: %v", err) 3125 } 3126 3127 args = &structs.RegisterRequest{ 3128 Datacenter: "dc1", 3129 Node: "foo", 3130 Address: "127.0.0.1", 3131 Service: &structs.NodeService{ 3132 ID: "db2", 3133 Service: "db", 3134 Tags: []string{"slave"}, 3135 Port: 12345, 3136 }, 3137 } 3138 if err := a.RPC("Catalog.Register", args, &out); err != nil { 3139 t.Fatalf("err: %v", err) 3140 } 3141 3142 args = &structs.RegisterRequest{ 3143 Datacenter: "dc1", 3144 Node: "foo", 3145 Address: "127.0.0.1", 3146 Service: &structs.NodeService{ 3147 ID: "db3", 3148 Service: "db", 3149 Tags: []string{"slave"}, 3150 Port: 12346, 3151 }, 3152 } 3153 if err := a.RPC("Catalog.Register", args, &out); err != nil { 3154 t.Fatalf("err: %v", err) 3155 } 3156 } 3157 3158 // Register an equivalent prepared query. 3159 var id string 3160 { 3161 args := &structs.PreparedQueryRequest{ 3162 Datacenter: "dc1", 3163 Op: structs.PreparedQueryCreate, 3164 Query: &structs.PreparedQuery{ 3165 Name: "test", 3166 Service: structs.ServiceQuery{ 3167 Service: "db", 3168 }, 3169 }, 3170 } 3171 if err := a.RPC("PreparedQuery.Apply", args, &id); err != nil { 3172 t.Fatalf("err: %v", err) 3173 } 3174 } 3175 3176 // Look up the service directly and via prepared query, make sure only 3177 // one IP is returned and two unique ports are returned. 3178 questions := []string{ 3179 "db.service.consul.", 3180 id + ".query.consul.", 3181 } 3182 for _, question := range questions { 3183 m := new(dns.Msg) 3184 m.SetQuestion(question, dns.TypeSRV) 3185 3186 c := new(dns.Client) 3187 in, _, err := c.Exchange(m, a.DNSAddr()) 3188 if err != nil { 3189 t.Fatalf("err: %v", err) 3190 } 3191 3192 if len(in.Answer) != 2 { 3193 t.Fatalf("Bad: %#v", in) 3194 } 3195 3196 srvRec, ok := in.Answer[0].(*dns.SRV) 3197 if !ok { 3198 t.Fatalf("Bad: %#v", in.Answer[0]) 3199 } 3200 if srvRec.Port != 12345 && srvRec.Port != 12346 { 3201 t.Fatalf("Bad: %#v", srvRec) 3202 } 3203 if srvRec.Target != "foo.node.dc1.consul." { 3204 t.Fatalf("Bad: %#v", srvRec) 3205 } 3206 3207 srvRec, ok = in.Answer[1].(*dns.SRV) 3208 if !ok { 3209 t.Fatalf("Bad: %#v", in.Answer[1]) 3210 } 3211 if srvRec.Port != 12346 && srvRec.Port != 12345 { 3212 t.Fatalf("Bad: %#v", srvRec) 3213 } 3214 if srvRec.Port == in.Answer[0].(*dns.SRV).Port { 3215 t.Fatalf("should be a different port") 3216 } 3217 if srvRec.Target != "foo.node.dc1.consul." { 3218 t.Fatalf("Bad: %#v", srvRec) 3219 } 3220 3221 aRec, ok := in.Extra[0].(*dns.A) 3222 if !ok { 3223 t.Fatalf("Bad: %#v", in.Extra[0]) 3224 } 3225 if aRec.Hdr.Name != "foo.node.dc1.consul." { 3226 t.Fatalf("Bad: %#v", in.Extra[0]) 3227 } 3228 if aRec.A.String() != "127.0.0.1" { 3229 t.Fatalf("Bad: %#v", in.Extra[0]) 3230 } 3231 } 3232 } 3233 3234 func TestDNS_Recurse(t *testing.T) { 3235 t.Parallel() 3236 recursor := makeRecursor(t, dns.Msg{ 3237 Answer: []dns.RR{dnsA("apple.com", "1.2.3.4")}, 3238 }) 3239 defer recursor.Shutdown() 3240 3241 a := NewTestAgent(t, t.Name(), ` 3242 recursors = ["`+recursor.Addr+`"] 3243 `) 3244 defer a.Shutdown() 3245 testrpc.WaitForLeader(t, a.RPC, "dc1") 3246 3247 m := new(dns.Msg) 3248 m.SetQuestion("apple.com.", dns.TypeANY) 3249 3250 c := new(dns.Client) 3251 in, _, err := c.Exchange(m, a.DNSAddr()) 3252 if err != nil { 3253 t.Fatalf("err: %v", err) 3254 } 3255 3256 if len(in.Answer) == 0 { 3257 t.Fatalf("Bad: %#v", in) 3258 } 3259 if in.Rcode != dns.RcodeSuccess { 3260 t.Fatalf("Bad: %#v", in) 3261 } 3262 } 3263 3264 func TestDNS_Recurse_Truncation(t *testing.T) { 3265 t.Parallel() 3266 3267 recursor := makeRecursor(t, dns.Msg{ 3268 MsgHdr: dns.MsgHdr{Truncated: true}, 3269 Answer: []dns.RR{dnsA("apple.com", "1.2.3.4")}, 3270 }) 3271 defer recursor.Shutdown() 3272 3273 a := NewTestAgent(t, t.Name(), ` 3274 recursors = ["`+recursor.Addr+`"] 3275 `) 3276 defer a.Shutdown() 3277 testrpc.WaitForLeader(t, a.RPC, "dc1") 3278 3279 m := new(dns.Msg) 3280 m.SetQuestion("apple.com.", dns.TypeANY) 3281 3282 c := new(dns.Client) 3283 in, _, err := c.Exchange(m, a.DNSAddr()) 3284 if err != dns.ErrTruncated { 3285 t.Fatalf("err: %v", err) 3286 } 3287 if in.Truncated != true { 3288 t.Fatalf("err: message should have been truncated %v", in) 3289 } 3290 if len(in.Answer) == 0 { 3291 t.Fatalf("Bad: Truncated message ignored, expected some reply %#v", in) 3292 } 3293 if in.Rcode != dns.RcodeSuccess { 3294 t.Fatalf("Bad: %#v", in) 3295 } 3296 } 3297 3298 func TestDNS_RecursorTimeout(t *testing.T) { 3299 t.Parallel() 3300 serverClientTimeout := 3 * time.Second 3301 testClientTimeout := serverClientTimeout + 5*time.Second 3302 3303 resolverAddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:0") 3304 if err != nil { 3305 t.Error(err) 3306 } 3307 3308 resolver, err := net.ListenUDP("udp", resolverAddr) 3309 if err != nil { 3310 t.Error(err) 3311 } 3312 defer resolver.Close() 3313 3314 a := NewTestAgent(t, t.Name(), ` 3315 recursors = ["`+resolver.LocalAddr().String()+`"] // host must cause a connection|read|write timeout 3316 dns_config { 3317 recursor_timeout = "`+serverClientTimeout.String()+`" 3318 } 3319 `) 3320 defer a.Shutdown() 3321 testrpc.WaitForLeader(t, a.RPC, "dc1") 3322 3323 m := new(dns.Msg) 3324 m.SetQuestion("apple.com.", dns.TypeANY) 3325 3326 // This client calling the server under test must have a longer timeout than the one we set internally 3327 c := &dns.Client{Timeout: testClientTimeout} 3328 3329 start := time.Now() 3330 in, _, err := c.Exchange(m, a.DNSAddr()) 3331 3332 duration := time.Since(start) 3333 3334 if err != nil { 3335 t.Fatalf("err: %v", err) 3336 } 3337 3338 if len(in.Answer) != 0 { 3339 t.Fatalf("Bad: %#v", in) 3340 } 3341 if in.Rcode != dns.RcodeServerFailure { 3342 t.Fatalf("Bad: %#v", in) 3343 } 3344 3345 if duration < serverClientTimeout { 3346 t.Fatalf("Expected the call to return after at least %f seconds but lasted only %f", serverClientTimeout.Seconds(), duration.Seconds()) 3347 } 3348 3349 } 3350 3351 func TestDNS_ServiceLookup_FilterCritical(t *testing.T) { 3352 t.Parallel() 3353 a := NewTestAgent(t, t.Name(), "") 3354 defer a.Shutdown() 3355 testrpc.WaitForLeader(t, a.RPC, "dc1") 3356 3357 // Register nodes with health checks in various states. 3358 { 3359 args := &structs.RegisterRequest{ 3360 Datacenter: "dc1", 3361 Node: "foo", 3362 Address: "127.0.0.1", 3363 Service: &structs.NodeService{ 3364 Service: "db", 3365 Tags: []string{"master"}, 3366 Port: 12345, 3367 }, 3368 Check: &structs.HealthCheck{ 3369 CheckID: "serf", 3370 Name: "serf", 3371 Status: api.HealthCritical, 3372 }, 3373 } 3374 3375 var out struct{} 3376 if err := a.RPC("Catalog.Register", args, &out); err != nil { 3377 t.Fatalf("err: %v", err) 3378 } 3379 3380 args2 := &structs.RegisterRequest{ 3381 Datacenter: "dc1", 3382 Node: "bar", 3383 Address: "127.0.0.2", 3384 Service: &structs.NodeService{ 3385 Service: "db", 3386 Tags: []string{"master"}, 3387 Port: 12345, 3388 }, 3389 Check: &structs.HealthCheck{ 3390 CheckID: "serf", 3391 Name: "serf", 3392 Status: api.HealthCritical, 3393 }, 3394 } 3395 if err := a.RPC("Catalog.Register", args2, &out); err != nil { 3396 t.Fatalf("err: %v", err) 3397 } 3398 3399 args3 := &structs.RegisterRequest{ 3400 Datacenter: "dc1", 3401 Node: "bar", 3402 Address: "127.0.0.2", 3403 Service: &structs.NodeService{ 3404 Service: "db", 3405 Tags: []string{"master"}, 3406 Port: 12345, 3407 }, 3408 Check: &structs.HealthCheck{ 3409 CheckID: "db", 3410 Name: "db", 3411 ServiceID: "db", 3412 Status: api.HealthCritical, 3413 }, 3414 } 3415 if err := a.RPC("Catalog.Register", args3, &out); err != nil { 3416 t.Fatalf("err: %v", err) 3417 } 3418 3419 args4 := &structs.RegisterRequest{ 3420 Datacenter: "dc1", 3421 Node: "baz", 3422 Address: "127.0.0.3", 3423 Service: &structs.NodeService{ 3424 Service: "db", 3425 Tags: []string{"master"}, 3426 Port: 12345, 3427 }, 3428 } 3429 if err := a.RPC("Catalog.Register", args4, &out); err != nil { 3430 t.Fatalf("err: %v", err) 3431 } 3432 3433 args5 := &structs.RegisterRequest{ 3434 Datacenter: "dc1", 3435 Node: "quux", 3436 Address: "127.0.0.4", 3437 Service: &structs.NodeService{ 3438 Service: "db", 3439 Tags: []string{"master"}, 3440 Port: 12345, 3441 }, 3442 Check: &structs.HealthCheck{ 3443 CheckID: "db", 3444 Name: "db", 3445 ServiceID: "db", 3446 Status: api.HealthWarning, 3447 }, 3448 } 3449 if err := a.RPC("Catalog.Register", args5, &out); err != nil { 3450 t.Fatalf("err: %v", err) 3451 } 3452 } 3453 3454 // Register an equivalent prepared query. 3455 var id string 3456 { 3457 args := &structs.PreparedQueryRequest{ 3458 Datacenter: "dc1", 3459 Op: structs.PreparedQueryCreate, 3460 Query: &structs.PreparedQuery{ 3461 Name: "test", 3462 Service: structs.ServiceQuery{ 3463 Service: "db", 3464 }, 3465 }, 3466 } 3467 if err := a.RPC("PreparedQuery.Apply", args, &id); err != nil { 3468 t.Fatalf("err: %v", err) 3469 } 3470 } 3471 3472 // Look up the service directly and via prepared query. 3473 questions := []string{ 3474 "db.service.consul.", 3475 id + ".query.consul.", 3476 } 3477 for _, question := range questions { 3478 m := new(dns.Msg) 3479 m.SetQuestion(question, dns.TypeANY) 3480 3481 c := new(dns.Client) 3482 in, _, err := c.Exchange(m, a.DNSAddr()) 3483 if err != nil { 3484 t.Fatalf("err: %v", err) 3485 } 3486 3487 // Only 4 and 5 are not failing, so we should get 2 answers 3488 if len(in.Answer) != 2 { 3489 t.Fatalf("Bad: %#v", in) 3490 } 3491 3492 ips := make(map[string]bool) 3493 for _, resp := range in.Answer { 3494 aRec := resp.(*dns.A) 3495 ips[aRec.A.String()] = true 3496 } 3497 3498 if !ips["127.0.0.3"] { 3499 t.Fatalf("Bad: %#v should contain 127.0.0.3 (state healthy)", in) 3500 } 3501 if !ips["127.0.0.4"] { 3502 t.Fatalf("Bad: %#v should contain 127.0.0.4 (state warning)", in) 3503 } 3504 } 3505 } 3506 3507 func TestDNS_ServiceLookup_OnlyFailing(t *testing.T) { 3508 t.Parallel() 3509 a := NewTestAgent(t, t.Name(), "") 3510 defer a.Shutdown() 3511 testrpc.WaitForLeader(t, a.RPC, "dc1") 3512 3513 // Register nodes with all health checks in a critical state. 3514 { 3515 args := &structs.RegisterRequest{ 3516 Datacenter: "dc1", 3517 Node: "foo", 3518 Address: "127.0.0.1", 3519 Service: &structs.NodeService{ 3520 Service: "db", 3521 Tags: []string{"master"}, 3522 Port: 12345, 3523 }, 3524 Check: &structs.HealthCheck{ 3525 CheckID: "serf", 3526 Name: "serf", 3527 Status: api.HealthCritical, 3528 }, 3529 } 3530 3531 var out struct{} 3532 if err := a.RPC("Catalog.Register", args, &out); err != nil { 3533 t.Fatalf("err: %v", err) 3534 } 3535 3536 args2 := &structs.RegisterRequest{ 3537 Datacenter: "dc1", 3538 Node: "bar", 3539 Address: "127.0.0.2", 3540 Service: &structs.NodeService{ 3541 Service: "db", 3542 Tags: []string{"master"}, 3543 Port: 12345, 3544 }, 3545 Check: &structs.HealthCheck{ 3546 CheckID: "serf", 3547 Name: "serf", 3548 Status: api.HealthCritical, 3549 }, 3550 } 3551 if err := a.RPC("Catalog.Register", args2, &out); err != nil { 3552 t.Fatalf("err: %v", err) 3553 } 3554 3555 args3 := &structs.RegisterRequest{ 3556 Datacenter: "dc1", 3557 Node: "bar", 3558 Address: "127.0.0.2", 3559 Service: &structs.NodeService{ 3560 Service: "db", 3561 Tags: []string{"master"}, 3562 Port: 12345, 3563 }, 3564 Check: &structs.HealthCheck{ 3565 CheckID: "db", 3566 Name: "db", 3567 ServiceID: "db", 3568 Status: api.HealthCritical, 3569 }, 3570 } 3571 if err := a.RPC("Catalog.Register", args3, &out); err != nil { 3572 t.Fatalf("err: %v", err) 3573 } 3574 } 3575 3576 // Register an equivalent prepared query. 3577 var id string 3578 { 3579 args := &structs.PreparedQueryRequest{ 3580 Datacenter: "dc1", 3581 Op: structs.PreparedQueryCreate, 3582 Query: &structs.PreparedQuery{ 3583 Name: "test", 3584 Service: structs.ServiceQuery{ 3585 Service: "db", 3586 }, 3587 }, 3588 } 3589 if err := a.RPC("PreparedQuery.Apply", args, &id); err != nil { 3590 t.Fatalf("err: %v", err) 3591 } 3592 } 3593 3594 // Look up the service directly and via prepared query. 3595 questions := []string{ 3596 "db.service.consul.", 3597 id + ".query.consul.", 3598 } 3599 for _, question := range questions { 3600 m := new(dns.Msg) 3601 m.SetQuestion(question, dns.TypeANY) 3602 3603 c := new(dns.Client) 3604 in, _, err := c.Exchange(m, a.DNSAddr()) 3605 if err != nil { 3606 t.Fatalf("err: %v", err) 3607 } 3608 3609 // All 3 are failing, so we should get 0 answers and an NXDOMAIN response 3610 if len(in.Answer) != 0 { 3611 t.Fatalf("Bad: %#v", in) 3612 } 3613 3614 if in.Rcode != dns.RcodeNameError { 3615 t.Fatalf("Bad: %#v", in) 3616 } 3617 } 3618 } 3619 3620 func TestDNS_ServiceLookup_OnlyPassing(t *testing.T) { 3621 t.Parallel() 3622 a := NewTestAgent(t, t.Name(), ` 3623 dns_config { 3624 only_passing = true 3625 } 3626 `) 3627 defer a.Shutdown() 3628 testrpc.WaitForLeader(t, a.RPC, "dc1") 3629 3630 // Register nodes with health checks in various states. 3631 { 3632 args := &structs.RegisterRequest{ 3633 Datacenter: "dc1", 3634 Node: "foo", 3635 Address: "127.0.0.1", 3636 Service: &structs.NodeService{ 3637 Service: "db", 3638 Tags: []string{"master"}, 3639 Port: 12345, 3640 }, 3641 Check: &structs.HealthCheck{ 3642 CheckID: "db", 3643 Name: "db", 3644 ServiceID: "db", 3645 Status: api.HealthPassing, 3646 }, 3647 } 3648 3649 var out struct{} 3650 if err := a.RPC("Catalog.Register", args, &out); err != nil { 3651 t.Fatalf("err: %v", err) 3652 } 3653 3654 args2 := &structs.RegisterRequest{ 3655 Datacenter: "dc1", 3656 Node: "bar", 3657 Address: "127.0.0.2", 3658 Service: &structs.NodeService{ 3659 Service: "db", 3660 Tags: []string{"master"}, 3661 Port: 12345, 3662 }, 3663 Check: &structs.HealthCheck{ 3664 CheckID: "db", 3665 Name: "db", 3666 ServiceID: "db", 3667 Status: api.HealthWarning, 3668 }, 3669 } 3670 3671 if err := a.RPC("Catalog.Register", args2, &out); err != nil { 3672 t.Fatalf("err: %v", err) 3673 } 3674 3675 args3 := &structs.RegisterRequest{ 3676 Datacenter: "dc1", 3677 Node: "baz", 3678 Address: "127.0.0.3", 3679 Service: &structs.NodeService{ 3680 Service: "db", 3681 Tags: []string{"master"}, 3682 Port: 12345, 3683 }, 3684 Check: &structs.HealthCheck{ 3685 CheckID: "db", 3686 Name: "db", 3687 ServiceID: "db", 3688 Status: api.HealthCritical, 3689 }, 3690 } 3691 3692 if err := a.RPC("Catalog.Register", args3, &out); err != nil { 3693 t.Fatalf("err: %v", err) 3694 } 3695 } 3696 3697 // Register an equivalent prepared query. 3698 var id string 3699 { 3700 args := &structs.PreparedQueryRequest{ 3701 Datacenter: "dc1", 3702 Op: structs.PreparedQueryCreate, 3703 Query: &structs.PreparedQuery{ 3704 Name: "test", 3705 Service: structs.ServiceQuery{ 3706 Service: "db", 3707 OnlyPassing: true, 3708 }, 3709 }, 3710 } 3711 if err := a.RPC("PreparedQuery.Apply", args, &id); err != nil { 3712 t.Fatalf("err: %v", err) 3713 } 3714 } 3715 3716 // Look up the service directly and via prepared query. 3717 questions := []string{ 3718 "db.service.consul.", 3719 id + ".query.consul.", 3720 } 3721 for _, question := range questions { 3722 m := new(dns.Msg) 3723 m.SetQuestion(question, dns.TypeANY) 3724 3725 c := new(dns.Client) 3726 in, _, err := c.Exchange(m, a.DNSAddr()) 3727 if err != nil { 3728 t.Fatalf("err: %v", err) 3729 } 3730 3731 // Only 1 is passing, so we should only get 1 answer 3732 if len(in.Answer) != 1 { 3733 t.Fatalf("Bad: %#v", in) 3734 } 3735 3736 resp := in.Answer[0] 3737 aRec := resp.(*dns.A) 3738 3739 if aRec.A.String() != "127.0.0.1" { 3740 t.Fatalf("Bad: %#v", in.Answer[0]) 3741 } 3742 } 3743 } 3744 3745 func TestDNS_ServiceLookup_Randomize(t *testing.T) { 3746 t.Parallel() 3747 a := NewTestAgent(t, t.Name(), "") 3748 defer a.Shutdown() 3749 testrpc.WaitForLeader(t, a.RPC, "dc1") 3750 3751 // Register a large number of nodes. 3752 for i := 0; i < generateNumNodes; i++ { 3753 args := &structs.RegisterRequest{ 3754 Datacenter: "dc1", 3755 Node: fmt.Sprintf("foo%d", i), 3756 Address: fmt.Sprintf("127.0.0.%d", i+1), 3757 Service: &structs.NodeService{ 3758 Service: "web", 3759 Port: 8000, 3760 }, 3761 } 3762 3763 var out struct{} 3764 if err := a.RPC("Catalog.Register", args, &out); err != nil { 3765 t.Fatalf("err: %v", err) 3766 } 3767 } 3768 3769 // Register an equivalent prepared query. 3770 var id string 3771 { 3772 args := &structs.PreparedQueryRequest{ 3773 Datacenter: "dc1", 3774 Op: structs.PreparedQueryCreate, 3775 Query: &structs.PreparedQuery{ 3776 Name: "test", 3777 Service: structs.ServiceQuery{ 3778 Service: "web", 3779 }, 3780 }, 3781 } 3782 if err := a.RPC("PreparedQuery.Apply", args, &id); err != nil { 3783 t.Fatalf("err: %v", err) 3784 } 3785 } 3786 3787 // Look up the service directly and via prepared query. Ensure the 3788 // response is randomized each time. 3789 questions := []string{ 3790 "web.service.consul.", 3791 id + ".query.consul.", 3792 } 3793 for _, question := range questions { 3794 uniques := map[string]struct{}{} 3795 for i := 0; i < 10; i++ { 3796 m := new(dns.Msg) 3797 m.SetQuestion(question, dns.TypeANY) 3798 3799 c := &dns.Client{Net: "udp"} 3800 in, _, err := c.Exchange(m, a.DNSAddr()) 3801 if err != nil { 3802 t.Fatalf("err: %v", err) 3803 } 3804 3805 // Response length should be truncated and we should get 3806 // an A record for each response. 3807 if len(in.Answer) != defaultNumUDPResponses { 3808 t.Fatalf("Bad: %#v", len(in.Answer)) 3809 } 3810 3811 // Collect all the names. 3812 var names []string 3813 for _, rec := range in.Answer { 3814 switch v := rec.(type) { 3815 case *dns.SRV: 3816 names = append(names, v.Target) 3817 case *dns.A: 3818 names = append(names, v.A.String()) 3819 } 3820 } 3821 nameS := strings.Join(names, "|") 3822 3823 // Tally the results. 3824 uniques[nameS] = struct{}{} 3825 } 3826 3827 // Give some wiggle room. Since the responses are randomized and 3828 // there is a finite number of combinations, requiring 0 3829 // duplicates every test run eventually gives us failures. 3830 if len(uniques) < 2 { 3831 t.Fatalf("unique response ratio too low: %d/10\n%v", len(uniques), uniques) 3832 } 3833 } 3834 } 3835 3836 func TestBinarySearch(t *testing.T) { 3837 t.Parallel() 3838 msgSrc := new(dns.Msg) 3839 msgSrc.Compress = true 3840 msgSrc.SetQuestion("redis.service.consul.", dns.TypeSRV) 3841 3842 for i := 0; i < 5000; i++ { 3843 target := fmt.Sprintf("host-redis-%d-%d.test.acme.com.node.dc1.consul.", i/256, i%256) 3844 msgSrc.Answer = append(msgSrc.Answer, &dns.SRV{Hdr: dns.RR_Header{Name: "redis.service.consul.", Class: 1, Rrtype: dns.TypeSRV, Ttl: 0x3c}, Port: 0x4c57, Target: target}) 3845 msgSrc.Extra = append(msgSrc.Extra, &dns.CNAME{Hdr: dns.RR_Header{Name: target, Class: 1, Rrtype: dns.TypeCNAME, Ttl: 0x3c}, Target: fmt.Sprintf("fx.168.%d.%d.", i/256, i%256)}) 3846 } 3847 for _, compress := range []bool{true, false} { 3848 for idx, maxSize := range []int{12, 256, 512, 8192, 65535} { 3849 t.Run(fmt.Sprintf("binarySearch %d", maxSize), func(t *testing.T) { 3850 msg := new(dns.Msg) 3851 msgSrc.Compress = compress 3852 msgSrc.SetQuestion("redis.service.consul.", dns.TypeSRV) 3853 msg.Answer = msgSrc.Answer 3854 msg.Extra = msgSrc.Extra 3855 index := make(map[string]dns.RR, len(msg.Extra)) 3856 indexRRs(msg.Extra, index) 3857 blen := dnsBinaryTruncate(msg, maxSize, index, true) 3858 msg.Answer = msg.Answer[:blen] 3859 syncExtra(index, msg) 3860 predicted := msg.Len() 3861 buf, err := msg.Pack() 3862 if err != nil { 3863 t.Error(err) 3864 } 3865 if predicted < len(buf) { 3866 t.Fatalf("Bug in DNS library: %d != %d", predicted, len(buf)) 3867 } 3868 if len(buf) > maxSize || (idx != 0 && len(buf) < 16) { 3869 t.Fatalf("bad[%d]: %d > %d", idx, len(buf), maxSize) 3870 } 3871 }) 3872 } 3873 } 3874 } 3875 3876 func TestDNS_TCP_and_UDP_Truncate(t *testing.T) { 3877 t.Parallel() 3878 a := NewTestAgent(t, t.Name(), ` 3879 dns_config { 3880 enable_truncate = true 3881 } 3882 `) 3883 defer a.Shutdown() 3884 testrpc.WaitForLeader(t, a.RPC, "dc1") 3885 3886 services := []string{"normal", "truncated"} 3887 for index, service := range services { 3888 numServices := (index * 5000) + 2 3889 for i := 1; i < numServices; i++ { 3890 args := &structs.RegisterRequest{ 3891 Datacenter: "dc1", 3892 Node: fmt.Sprintf("%s-%d.acme.com", service, i), 3893 Address: fmt.Sprintf("127.%d.%d.%d", 0, (i / 255), i%255), 3894 Service: &structs.NodeService{ 3895 Service: service, 3896 Port: 8000, 3897 }, 3898 } 3899 3900 var out struct{} 3901 if err := a.RPC("Catalog.Register", args, &out); err != nil { 3902 t.Fatalf("err: %v", err) 3903 } 3904 } 3905 3906 // Register an equivalent prepared query. 3907 var id string 3908 { 3909 args := &structs.PreparedQueryRequest{ 3910 Datacenter: "dc1", 3911 Op: structs.PreparedQueryCreate, 3912 Query: &structs.PreparedQuery{ 3913 Name: service, 3914 Service: structs.ServiceQuery{ 3915 Service: service, 3916 }, 3917 }, 3918 } 3919 if err := a.RPC("PreparedQuery.Apply", args, &id); err != nil { 3920 t.Fatalf("err: %v", err) 3921 } 3922 } 3923 3924 // Look up the service directly and via prepared query. Ensure the 3925 // response is truncated each time. 3926 questions := []string{ 3927 fmt.Sprintf("%s.service.consul.", service), 3928 id + ".query.consul.", 3929 } 3930 protocols := []string{ 3931 "tcp", 3932 "udp", 3933 } 3934 for _, maxSize := range []uint16{8192, 65535} { 3935 for _, qType := range []uint16{dns.TypeANY, dns.TypeA, dns.TypeSRV} { 3936 for _, question := range questions { 3937 for _, protocol := range protocols { 3938 for _, compress := range []bool{true, false} { 3939 t.Run(fmt.Sprintf("lookup %s %s (qType:=%d) compressed=%v", question, protocol, qType, compress), func(t *testing.T) { 3940 m := new(dns.Msg) 3941 m.SetQuestion(question, dns.TypeANY) 3942 maxSz := maxSize 3943 if protocol == "udp" { 3944 maxSz = 8192 3945 } 3946 m.SetEdns0(uint16(maxSz), true) 3947 c := new(dns.Client) 3948 c.Net = protocol 3949 m.Compress = compress 3950 in, _, err := c.Exchange(m, a.DNSAddr()) 3951 if err != nil && err != dns.ErrTruncated { 3952 t.Fatalf("err: %v", err) 3953 } 3954 3955 // Check for the truncate bit 3956 buf, err := m.Pack() 3957 info := fmt.Sprintf("service %s question:=%s (%s) (%d total records) sz:= %d in %v", 3958 service, question, protocol, numServices, len(in.Answer), in) 3959 if err != nil { 3960 t.Fatalf("Error while packing: %v ; info:=%s", err, info) 3961 } 3962 if len(buf) > int(maxSz) { 3963 t.Fatalf("len(buf) := %d > maxSz=%d for %v", len(buf), maxSz, info) 3964 } 3965 }) 3966 } 3967 } 3968 } 3969 } 3970 } 3971 } 3972 } 3973 3974 func TestDNS_ServiceLookup_Truncate(t *testing.T) { 3975 t.Parallel() 3976 a := NewTestAgent(t, t.Name(), ` 3977 dns_config { 3978 enable_truncate = true 3979 } 3980 `) 3981 defer a.Shutdown() 3982 testrpc.WaitForLeader(t, a.RPC, "dc1") 3983 3984 // Register a large number of nodes. 3985 for i := 0; i < generateNumNodes; i++ { 3986 args := &structs.RegisterRequest{ 3987 Datacenter: "dc1", 3988 Node: fmt.Sprintf("foo%d", i), 3989 Address: fmt.Sprintf("127.0.0.%d", i+1), 3990 Service: &structs.NodeService{ 3991 Service: "web", 3992 Port: 8000, 3993 }, 3994 } 3995 3996 var out struct{} 3997 if err := a.RPC("Catalog.Register", args, &out); err != nil { 3998 t.Fatalf("err: %v", err) 3999 } 4000 } 4001 4002 // Register an equivalent prepared query. 4003 var id string 4004 { 4005 args := &structs.PreparedQueryRequest{ 4006 Datacenter: "dc1", 4007 Op: structs.PreparedQueryCreate, 4008 Query: &structs.PreparedQuery{ 4009 Name: "test", 4010 Service: structs.ServiceQuery{ 4011 Service: "web", 4012 }, 4013 }, 4014 } 4015 if err := a.RPC("PreparedQuery.Apply", args, &id); err != nil { 4016 t.Fatalf("err: %v", err) 4017 } 4018 } 4019 4020 // Look up the service directly and via prepared query. Ensure the 4021 // response is truncated each time. 4022 questions := []string{ 4023 "web.service.consul.", 4024 id + ".query.consul.", 4025 } 4026 for _, question := range questions { 4027 m := new(dns.Msg) 4028 m.SetQuestion(question, dns.TypeANY) 4029 4030 c := new(dns.Client) 4031 in, _, err := c.Exchange(m, a.DNSAddr()) 4032 if err != nil && err != dns.ErrTruncated { 4033 t.Fatalf("err: %v", err) 4034 } 4035 4036 // Check for the truncate bit 4037 if !in.Truncated { 4038 t.Fatalf("should have truncate bit") 4039 } 4040 } 4041 } 4042 4043 func TestDNS_ServiceLookup_LargeResponses(t *testing.T) { 4044 t.Parallel() 4045 a := NewTestAgent(t, t.Name(), ` 4046 dns_config { 4047 enable_truncate = true 4048 } 4049 `) 4050 defer a.Shutdown() 4051 testrpc.WaitForLeader(t, a.RPC, "dc1") 4052 4053 longServiceName := "this-is-a-very-very-very-very-very-long-name-for-a-service" 4054 4055 // Register a lot of nodes. 4056 for i := 0; i < 4; i++ { 4057 args := &structs.RegisterRequest{ 4058 Datacenter: "dc1", 4059 Node: fmt.Sprintf("foo%d", i), 4060 Address: fmt.Sprintf("127.0.0.%d", i+1), 4061 Service: &structs.NodeService{ 4062 Service: longServiceName, 4063 Tags: []string{"master"}, 4064 Port: 12345, 4065 }, 4066 } 4067 4068 var out struct{} 4069 if err := a.RPC("Catalog.Register", args, &out); err != nil { 4070 t.Fatalf("err: %v", err) 4071 } 4072 } 4073 4074 // Register an equivalent prepared query. 4075 { 4076 args := &structs.PreparedQueryRequest{ 4077 Datacenter: "dc1", 4078 Op: structs.PreparedQueryCreate, 4079 Query: &structs.PreparedQuery{ 4080 Name: longServiceName, 4081 Service: structs.ServiceQuery{ 4082 Service: longServiceName, 4083 Tags: []string{"master"}, 4084 }, 4085 }, 4086 } 4087 var id string 4088 if err := a.RPC("PreparedQuery.Apply", args, &id); err != nil { 4089 t.Fatalf("err: %v", err) 4090 } 4091 } 4092 4093 // Look up the service directly and via prepared query. 4094 questions := []string{ 4095 "_" + longServiceName + "._master.service.consul.", 4096 longServiceName + ".query.consul.", 4097 } 4098 for _, question := range questions { 4099 m := new(dns.Msg) 4100 m.SetQuestion(question, dns.TypeSRV) 4101 4102 c := new(dns.Client) 4103 in, _, err := c.Exchange(m, a.DNSAddr()) 4104 if err != nil && err != dns.ErrTruncated { 4105 t.Fatalf("err: %v", err) 4106 } 4107 4108 // Make sure the response size is RFC 1035-compliant for UDP messages 4109 if in.Len() > 512 { 4110 t.Fatalf("Bad: %d", in.Len()) 4111 } 4112 4113 // We should only have two answers now 4114 if len(in.Answer) != 2 { 4115 t.Fatalf("Bad: %d", len(in.Answer)) 4116 } 4117 4118 // Make sure the ADDITIONAL section matches the ANSWER section. 4119 if len(in.Answer) != len(in.Extra) { 4120 t.Fatalf("Bad: %d vs. %d", len(in.Answer), len(in.Extra)) 4121 } 4122 for i := 0; i < len(in.Answer); i++ { 4123 srv, ok := in.Answer[i].(*dns.SRV) 4124 if !ok { 4125 t.Fatalf("Bad: %#v", in.Answer[i]) 4126 } 4127 4128 a, ok := in.Extra[i].(*dns.A) 4129 if !ok { 4130 t.Fatalf("Bad: %#v", in.Extra[i]) 4131 } 4132 4133 if srv.Target != a.Hdr.Name { 4134 t.Fatalf("Bad: %#v %#v", srv, a) 4135 } 4136 } 4137 4138 // Check for the truncate bit 4139 if !in.Truncated { 4140 t.Fatalf("should have truncate bit") 4141 } 4142 } 4143 } 4144 4145 func testDNSServiceLookupResponseLimits(t *testing.T, answerLimit int, qType uint16, 4146 expectedService, expectedQuery, expectedQueryID int) (bool, error) { 4147 a := NewTestAgent(t, t.Name(), ` 4148 node_name = "test-node" 4149 dns_config { 4150 udp_answer_limit = `+fmt.Sprintf("%d", answerLimit)+` 4151 } 4152 `) 4153 defer a.Shutdown() 4154 testrpc.WaitForLeader(t, a.RPC, "dc1") 4155 4156 for i := 0; i < generateNumNodes; i++ { 4157 nodeAddress := fmt.Sprintf("127.0.0.%d", i+1) 4158 if rand.Float64() < pctNodesWithIPv6 { 4159 nodeAddress = fmt.Sprintf("fe80::%d", i+1) 4160 } 4161 args := &structs.RegisterRequest{ 4162 Datacenter: "dc1", 4163 Node: fmt.Sprintf("foo%d", i), 4164 Address: nodeAddress, 4165 Service: &structs.NodeService{ 4166 Service: "api-tier", 4167 Port: 8080, 4168 }, 4169 } 4170 4171 var out struct{} 4172 if err := a.RPC("Catalog.Register", args, &out); err != nil { 4173 return false, fmt.Errorf("err: %v", err) 4174 } 4175 } 4176 var id string 4177 { 4178 args := &structs.PreparedQueryRequest{ 4179 Datacenter: "dc1", 4180 Op: structs.PreparedQueryCreate, 4181 Query: &structs.PreparedQuery{ 4182 Name: "api-tier", 4183 Service: structs.ServiceQuery{ 4184 Service: "api-tier", 4185 }, 4186 }, 4187 } 4188 4189 if err := a.RPC("PreparedQuery.Apply", args, &id); err != nil { 4190 return false, fmt.Errorf("err: %v", err) 4191 } 4192 } 4193 4194 // Look up the service directly and via prepared query. 4195 questions := []string{ 4196 "api-tier.service.consul.", 4197 "api-tier.query.consul.", 4198 id + ".query.consul.", 4199 } 4200 for idx, question := range questions { 4201 m := new(dns.Msg) 4202 m.SetQuestion(question, qType) 4203 4204 c := &dns.Client{Net: "udp"} 4205 in, _, err := c.Exchange(m, a.DNSAddr()) 4206 if err != nil { 4207 return false, fmt.Errorf("err: %v", err) 4208 } 4209 4210 switch idx { 4211 case 0: 4212 if (expectedService > 0 && len(in.Answer) != expectedService) || 4213 (expectedService < -1 && len(in.Answer) < lib.AbsInt(expectedService)) { 4214 return false, fmt.Errorf("%d/%d answers received for type %v for %s, sz:=%d", len(in.Answer), answerLimit, qType, question, in.Len()) 4215 } 4216 case 1: 4217 if (expectedQuery > 0 && len(in.Answer) != expectedQuery) || 4218 (expectedQuery < -1 && len(in.Answer) < lib.AbsInt(expectedQuery)) { 4219 return false, fmt.Errorf("%d/%d answers received for type %v for %s, sz:=%d", len(in.Answer), answerLimit, qType, question, in.Len()) 4220 } 4221 case 2: 4222 if (expectedQueryID > 0 && len(in.Answer) != expectedQueryID) || 4223 (expectedQueryID < -1 && len(in.Answer) < lib.AbsInt(expectedQueryID)) { 4224 return false, fmt.Errorf("%d/%d answers received for type %v for %s, sz:=%d", len(in.Answer), answerLimit, qType, question, in.Len()) 4225 } 4226 default: 4227 panic("abort") 4228 } 4229 } 4230 4231 return true, nil 4232 } 4233 4234 func checkDNSService(t *testing.T, generateNumNodes int, aRecordLimit int, qType uint16, 4235 expectedResultsCount int, udpSize uint16, udpAnswerLimit int) error { 4236 a := NewTestAgent(t, t.Name(), ` 4237 node_name = "test-node" 4238 dns_config { 4239 a_record_limit = `+fmt.Sprintf("%d", aRecordLimit)+` 4240 udp_answer_limit = `+fmt.Sprintf("%d", aRecordLimit)+` 4241 } 4242 `) 4243 defer a.Shutdown() 4244 testrpc.WaitForLeader(t, a.RPC, "dc1") 4245 4246 for i := 0; i < generateNumNodes; i++ { 4247 nodeAddress := fmt.Sprintf("127.0.0.%d", i+1) 4248 if rand.Float64() < pctNodesWithIPv6 { 4249 nodeAddress = fmt.Sprintf("fe80::%d", i+1) 4250 } 4251 args := &structs.RegisterRequest{ 4252 Datacenter: "dc1", 4253 Node: fmt.Sprintf("foo%d", i), 4254 Address: nodeAddress, 4255 Service: &structs.NodeService{ 4256 Service: "api-tier", 4257 Port: 8080, 4258 }, 4259 } 4260 4261 var out struct{} 4262 if err := a.RPC("Catalog.Register", args, &out); err != nil { 4263 return fmt.Errorf("err: %v", err) 4264 } 4265 } 4266 var id string 4267 { 4268 args := &structs.PreparedQueryRequest{ 4269 Datacenter: "dc1", 4270 Op: structs.PreparedQueryCreate, 4271 Query: &structs.PreparedQuery{ 4272 Name: "api-tier", 4273 Service: structs.ServiceQuery{ 4274 Service: "api-tier", 4275 }, 4276 }, 4277 } 4278 4279 if err := a.RPC("PreparedQuery.Apply", args, &id); err != nil { 4280 return fmt.Errorf("err: %v", err) 4281 } 4282 } 4283 4284 // Look up the service directly and via prepared query. 4285 questions := []string{ 4286 "api-tier.service.consul.", 4287 "api-tier.query.consul.", 4288 id + ".query.consul.", 4289 } 4290 for _, question := range questions { 4291 m := new(dns.Msg) 4292 4293 m.SetQuestion(question, qType) 4294 protocol := "tcp" 4295 if udpSize > 0 { 4296 protocol = "udp" 4297 } 4298 if udpSize > 512 { 4299 m.SetEdns0(udpSize, true) 4300 } 4301 c := &dns.Client{Net: protocol, UDPSize: 8192} 4302 in, _, err := c.Exchange(m, a.DNSAddr()) 4303 if err != nil { 4304 return fmt.Errorf("err: %v", err) 4305 } 4306 if len(in.Answer) != expectedResultsCount { 4307 return fmt.Errorf("%d/%d answers received for type %v for %s (%s)", len(in.Answer), expectedResultsCount, qType, question, protocol) 4308 } 4309 } 4310 4311 return nil 4312 } 4313 4314 func TestDNS_ServiceLookup_ARecordLimits(t *testing.T) { 4315 t.Parallel() 4316 tests := []struct { 4317 name string 4318 aRecordLimit int 4319 expectedAResults int 4320 expectedAAAAResults int 4321 expectedSRVResults int 4322 numNodesTotal int 4323 udpSize uint16 4324 udpAnswerLimit int 4325 }{ 4326 // UDP + EDNS 4327 {"udp-edns-1", 1, 1, 1, 30, 30, 8192, 3}, 4328 {"udp-edns-2", 2, 2, 1, 30, 30, 8192, 3}, 4329 {"udp-edns-3", 3, 3, 1, 30, 30, 8192, 3}, 4330 {"udp-edns-4", 4, 4, 1, 30, 30, 8192, 3}, 4331 {"udp-edns-5", 5, 5, 1, 30, 30, 8192, 3}, 4332 {"udp-edns-6", 6, 6, 1, 30, 30, 8192, 3}, 4333 {"udp-edns-max", 6, 3, 3, 3, 3, 8192, 3}, 4334 // All UDP without EDNS have a limit of 2 answers due to udpAnswerLimit 4335 // Even SRV records are limit to 2 records 4336 {"udp-limit-1", 1, 1, 1, 1, 1, 512, 2}, 4337 {"udp-limit-2", 2, 2, 2, 2, 2, 512, 2}, 4338 // AAAA results limited by size of payload 4339 {"udp-limit-3", 3, 2, 2, 2, 2, 512, 2}, 4340 {"udp-limit-4", 4, 2, 2, 2, 2, 512, 2}, 4341 {"udp-limit-5", 5, 2, 2, 2, 2, 512, 2}, 4342 {"udp-limit-6", 6, 2, 2, 2, 2, 512, 2}, 4343 {"udp-limit-max", 6, 2, 2, 2, 2, 512, 2}, 4344 // All UDP without EDNS and no udpAnswerLimit 4345 // Size of records is limited by UDP payload 4346 {"udp-1", 1, 1, 1, 1, 1, 512, 0}, 4347 {"udp-2", 2, 2, 2, 2, 2, 512, 0}, 4348 {"udp-3", 3, 2, 2, 2, 2, 512, 0}, 4349 {"udp-4", 4, 2, 2, 2, 2, 512, 0}, 4350 {"udp-5", 5, 2, 2, 2, 2, 512, 0}, 4351 {"udp-6", 6, 2, 2, 2, 2, 512, 0}, 4352 // Only 3 A and 3 SRV records on 512 bytes 4353 {"udp-max", 6, 2, 2, 2, 2, 512, 0}, 4354 4355 {"tcp-1", 1, 1, 1, 30, 30, 0, 0}, 4356 {"tcp-2", 2, 2, 2, 30, 30, 0, 0}, 4357 {"tcp-3", 3, 3, 3, 30, 30, 0, 0}, 4358 {"tcp-4", 4, 4, 4, 30, 30, 0, 0}, 4359 {"tcp-5", 5, 5, 5, 30, 30, 0, 0}, 4360 {"tcp-6", 6, 6, 5, 30, 30, 0, 0}, 4361 {"tcp-max", 6, 2, 2, 2, 2, 0, 0}, 4362 } 4363 for _, test := range tests { 4364 test := test // capture loop var 4365 4366 queriesLimited := []uint16{ 4367 dns.TypeA, 4368 dns.TypeAAAA, 4369 dns.TypeANY, 4370 } 4371 // All those queries should have at max queriesLimited elements 4372 for idx, qType := range queriesLimited { 4373 t.Run(fmt.Sprintf("ARecordLimit %d qType: %d", idx, qType), func(t *testing.T) { 4374 t.Parallel() 4375 err := checkDNSService(t, test.numNodesTotal, test.aRecordLimit, qType, test.expectedAResults, test.udpSize, test.udpAnswerLimit) 4376 if err != nil { 4377 t.Fatalf("Expected lookup %s to pass: %v", test.name, err) 4378 } 4379 }) 4380 } 4381 // No limits but the size of records for SRV records, since not subject to randomization issues 4382 t.Run("SRV lookup limitARecord", func(t *testing.T) { 4383 t.Parallel() 4384 err := checkDNSService(t, test.expectedSRVResults, test.aRecordLimit, dns.TypeSRV, test.numNodesTotal, test.udpSize, test.udpAnswerLimit) 4385 if err != nil { 4386 t.Fatalf("Expected service SRV lookup %s to pass: %v", test.name, err) 4387 } 4388 }) 4389 } 4390 } 4391 4392 func TestDNS_ServiceLookup_AnswerLimits(t *testing.T) { 4393 t.Parallel() 4394 // Build a matrix of config parameters (udpAnswerLimit), and the 4395 // length of the response per query type and question. Negative 4396 // values imply the test must return at least the abs(value) number 4397 // of records in the answer section. This is required because, for 4398 // example, on OS-X and Linux, the number of answers returned in a 4399 // 512B response is different even though both platforms are x86_64 4400 // and using the same version of Go. 4401 // 4402 // TODO(sean@): Why is it not identical everywhere when using the 4403 // same compiler? 4404 tests := []struct { 4405 name string 4406 udpAnswerLimit int 4407 expectedAService int 4408 expectedAQuery int 4409 expectedAQueryID int 4410 expectedAAAAService int 4411 expectedAAAAQuery int 4412 expectedAAAAQueryID int 4413 expectedANYService int 4414 expectedANYQuery int 4415 expectedANYQueryID int 4416 }{ 4417 {"0", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 4418 {"1", 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, 4419 {"2", 2, 2, 2, 2, 2, 2, 2, 2, 2, 2}, 4420 {"3", 3, 3, 3, 3, 3, 3, 3, 3, 3, 3}, 4421 {"4", 4, 4, 4, 4, 4, 4, 4, 4, 4, 4}, 4422 {"5", 5, 5, 5, 5, 5, 5, 5, 5, 5, 5}, 4423 {"6", 6, 6, 6, 6, 6, 6, 5, 6, 6, -5}, 4424 {"7", 7, 7, 7, 6, 7, 7, 5, 7, 7, -5}, 4425 {"8", 8, 8, 8, 6, 8, 8, 5, 8, 8, -5}, 4426 {"9", 9, 8, 8, 6, 8, 8, 5, 8, 8, -5}, 4427 {"20", 20, 8, 8, 6, 8, 8, 5, 8, -5, -5}, 4428 {"30", 30, 8, 8, 6, 8, 8, 5, 8, -5, -5}, 4429 } 4430 for _, test := range tests { 4431 test := test // capture loop var 4432 t.Run(fmt.Sprintf("A lookup %v", test), func(t *testing.T) { 4433 t.Parallel() 4434 ok, err := testDNSServiceLookupResponseLimits(t, test.udpAnswerLimit, dns.TypeA, test.expectedAService, test.expectedAQuery, test.expectedAQueryID) 4435 if !ok { 4436 t.Fatalf("Expected service A lookup %s to pass: %v", test.name, err) 4437 } 4438 }) 4439 4440 t.Run(fmt.Sprintf("AAAA lookup %v", test), func(t *testing.T) { 4441 t.Parallel() 4442 ok, err := testDNSServiceLookupResponseLimits(t, test.udpAnswerLimit, dns.TypeAAAA, test.expectedAAAAService, test.expectedAAAAQuery, test.expectedAAAAQueryID) 4443 if !ok { 4444 t.Fatalf("Expected service AAAA lookup %s to pass: %v", test.name, err) 4445 } 4446 }) 4447 4448 t.Run(fmt.Sprintf("ANY lookup %v", test), func(t *testing.T) { 4449 t.Parallel() 4450 ok, err := testDNSServiceLookupResponseLimits(t, test.udpAnswerLimit, dns.TypeANY, test.expectedANYService, test.expectedANYQuery, test.expectedANYQueryID) 4451 if !ok { 4452 t.Fatalf("Expected service ANY lookup %s to pass: %v", test.name, err) 4453 } 4454 }) 4455 } 4456 } 4457 4458 func TestDNS_ServiceLookup_CNAME(t *testing.T) { 4459 t.Parallel() 4460 recursor := makeRecursor(t, dns.Msg{ 4461 Answer: []dns.RR{ 4462 dnsCNAME("www.google.com", "google.com"), 4463 dnsA("google.com", "1.2.3.4"), 4464 }, 4465 }) 4466 defer recursor.Shutdown() 4467 4468 a := NewTestAgent(t, t.Name(), ` 4469 recursors = ["`+recursor.Addr+`"] 4470 `) 4471 defer a.Shutdown() 4472 testrpc.WaitForLeader(t, a.RPC, "dc1") 4473 4474 // Register a node with a name for an address. 4475 { 4476 args := &structs.RegisterRequest{ 4477 Datacenter: "dc1", 4478 Node: "google", 4479 Address: "www.google.com", 4480 Service: &structs.NodeService{ 4481 Service: "search", 4482 Port: 80, 4483 }, 4484 } 4485 4486 var out struct{} 4487 if err := a.RPC("Catalog.Register", args, &out); err != nil { 4488 t.Fatalf("err: %v", err) 4489 } 4490 } 4491 4492 // Register an equivalent prepared query. 4493 var id string 4494 { 4495 args := &structs.PreparedQueryRequest{ 4496 Datacenter: "dc1", 4497 Op: structs.PreparedQueryCreate, 4498 Query: &structs.PreparedQuery{ 4499 Name: "test", 4500 Service: structs.ServiceQuery{ 4501 Service: "search", 4502 }, 4503 }, 4504 } 4505 if err := a.RPC("PreparedQuery.Apply", args, &id); err != nil { 4506 t.Fatalf("err: %v", err) 4507 } 4508 } 4509 4510 // Look up the service directly and via prepared query. 4511 questions := []string{ 4512 "search.service.consul.", 4513 id + ".query.consul.", 4514 } 4515 for _, question := range questions { 4516 m := new(dns.Msg) 4517 m.SetQuestion(question, dns.TypeANY) 4518 4519 c := new(dns.Client) 4520 in, _, err := c.Exchange(m, a.DNSAddr()) 4521 if err != nil { 4522 t.Fatalf("err: %v", err) 4523 } 4524 4525 // Service CNAME, google CNAME, google A record 4526 if len(in.Answer) != 3 { 4527 t.Fatalf("Bad: %#v", in) 4528 } 4529 4530 // Should have service CNAME 4531 cnRec, ok := in.Answer[0].(*dns.CNAME) 4532 if !ok { 4533 t.Fatalf("Bad: %#v", in.Answer[0]) 4534 } 4535 if cnRec.Target != "www.google.com." { 4536 t.Fatalf("Bad: %#v", in.Answer[0]) 4537 } 4538 4539 // Should have google CNAME 4540 cnRec, ok = in.Answer[1].(*dns.CNAME) 4541 if !ok { 4542 t.Fatalf("Bad: %#v", in.Answer[1]) 4543 } 4544 if cnRec.Target != "google.com." { 4545 t.Fatalf("Bad: %#v", in.Answer[1]) 4546 } 4547 4548 // Check we recursively resolve 4549 if _, ok := in.Answer[2].(*dns.A); !ok { 4550 t.Fatalf("Bad: %#v", in.Answer[2]) 4551 } 4552 } 4553 } 4554 4555 func TestDNS_NodeLookup_TTL(t *testing.T) { 4556 t.Parallel() 4557 recursor := makeRecursor(t, dns.Msg{ 4558 Answer: []dns.RR{ 4559 dnsCNAME("www.google.com", "google.com"), 4560 dnsA("google.com", "1.2.3.4"), 4561 }, 4562 }) 4563 defer recursor.Shutdown() 4564 4565 a := NewTestAgent(t, t.Name(), ` 4566 recursors = ["`+recursor.Addr+`"] 4567 dns_config { 4568 node_ttl = "10s" 4569 allow_stale = true 4570 max_stale = "1s" 4571 } 4572 `) 4573 defer a.Shutdown() 4574 testrpc.WaitForLeader(t, a.RPC, "dc1") 4575 4576 // Register node 4577 args := &structs.RegisterRequest{ 4578 Datacenter: "dc1", 4579 Node: "foo", 4580 Address: "127.0.0.1", 4581 } 4582 4583 var out struct{} 4584 if err := a.RPC("Catalog.Register", args, &out); err != nil { 4585 t.Fatalf("err: %v", err) 4586 } 4587 4588 m := new(dns.Msg) 4589 m.SetQuestion("foo.node.consul.", dns.TypeANY) 4590 4591 c := new(dns.Client) 4592 in, _, err := c.Exchange(m, a.DNSAddr()) 4593 if err != nil { 4594 t.Fatalf("err: %v", err) 4595 } 4596 4597 if len(in.Answer) != 1 { 4598 t.Fatalf("Bad: %#v", in) 4599 } 4600 4601 aRec, ok := in.Answer[0].(*dns.A) 4602 if !ok { 4603 t.Fatalf("Bad: %#v", in.Answer[0]) 4604 } 4605 if aRec.A.String() != "127.0.0.1" { 4606 t.Fatalf("Bad: %#v", in.Answer[0]) 4607 } 4608 if aRec.Hdr.Ttl != 10 { 4609 t.Fatalf("Bad: %#v", in.Answer[0]) 4610 } 4611 4612 // Register node with IPv6 4613 args = &structs.RegisterRequest{ 4614 Datacenter: "dc1", 4615 Node: "bar", 4616 Address: "::4242:4242", 4617 } 4618 if err := a.RPC("Catalog.Register", args, &out); err != nil { 4619 t.Fatalf("err: %v", err) 4620 } 4621 4622 // Check an IPv6 record 4623 m = new(dns.Msg) 4624 m.SetQuestion("bar.node.consul.", dns.TypeANY) 4625 4626 in, _, err = c.Exchange(m, a.DNSAddr()) 4627 if err != nil { 4628 t.Fatalf("err: %v", err) 4629 } 4630 4631 if len(in.Answer) != 1 { 4632 t.Fatalf("Bad: %#v", in) 4633 } 4634 4635 aaaaRec, ok := in.Answer[0].(*dns.AAAA) 4636 if !ok { 4637 t.Fatalf("Bad: %#v", in.Answer[0]) 4638 } 4639 if aaaaRec.AAAA.String() != "::4242:4242" { 4640 t.Fatalf("Bad: %#v", in.Answer[0]) 4641 } 4642 if aaaaRec.Hdr.Ttl != 10 { 4643 t.Fatalf("Bad: %#v", in.Answer[0]) 4644 } 4645 4646 // Register node with CNAME 4647 args = &structs.RegisterRequest{ 4648 Datacenter: "dc1", 4649 Node: "google", 4650 Address: "www.google.com", 4651 } 4652 if err := a.RPC("Catalog.Register", args, &out); err != nil { 4653 t.Fatalf("err: %v", err) 4654 } 4655 4656 m = new(dns.Msg) 4657 m.SetQuestion("google.node.consul.", dns.TypeANY) 4658 4659 in, _, err = c.Exchange(m, a.DNSAddr()) 4660 if err != nil { 4661 t.Fatalf("err: %v", err) 4662 } 4663 4664 // Should have the CNAME record + a few A records 4665 if len(in.Answer) < 2 { 4666 t.Fatalf("Bad: %#v", in) 4667 } 4668 4669 cnRec, ok := in.Answer[0].(*dns.CNAME) 4670 if !ok { 4671 t.Fatalf("Bad: %#v", in.Answer[0]) 4672 } 4673 if cnRec.Target != "www.google.com." { 4674 t.Fatalf("Bad: %#v", in.Answer[0]) 4675 } 4676 if cnRec.Hdr.Ttl != 10 { 4677 t.Fatalf("Bad: %#v", in.Answer[0]) 4678 } 4679 } 4680 4681 func TestDNS_ServiceLookup_TTL(t *testing.T) { 4682 t.Parallel() 4683 a := NewTestAgent(t, t.Name(), ` 4684 dns_config { 4685 service_ttl = { 4686 "d*" = "42s" 4687 "db" = "10s" 4688 "db*" = "66s" 4689 "*" = "5s" 4690 } 4691 allow_stale = true 4692 max_stale = "1s" 4693 } 4694 `) 4695 defer a.Shutdown() 4696 4697 for idx, service := range []string{"db", "dblb", "dk", "api"} { 4698 nodeName := fmt.Sprintf("foo%d", idx) 4699 address := fmt.Sprintf("127.0.0.%d", idx) 4700 args := &structs.RegisterRequest{ 4701 Datacenter: "dc1", 4702 Node: nodeName, 4703 Address: address, 4704 Service: &structs.NodeService{ 4705 Service: service, 4706 Tags: []string{"master"}, 4707 Port: 12345 + idx, 4708 }, 4709 } 4710 4711 var out struct{} 4712 if err := a.RPC("Catalog.Register", args, &out); err != nil { 4713 t.Fatalf("err: %v", err) 4714 } 4715 } 4716 4717 c := new(dns.Client) 4718 expectResult := func(dnsQuery string, expectedTTL uint32) { 4719 t.Run(dnsQuery, func(t *testing.T) { 4720 m := new(dns.Msg) 4721 m.SetQuestion(dnsQuery, dns.TypeSRV) 4722 4723 in, _, err := c.Exchange(m, a.DNSAddr()) 4724 if err != nil { 4725 t.Fatalf("err: %v", err) 4726 } 4727 4728 if len(in.Answer) != 1 { 4729 t.Fatalf("Bad: %#v, len is %d", in, len(in.Answer)) 4730 } 4731 4732 srvRec, ok := in.Answer[0].(*dns.SRV) 4733 if !ok { 4734 t.Fatalf("Bad: %#v", in.Answer[0]) 4735 } 4736 if srvRec.Hdr.Ttl != expectedTTL { 4737 t.Fatalf("Bad: %#v", in.Answer[0]) 4738 } 4739 4740 aRec, ok := in.Extra[0].(*dns.A) 4741 if !ok { 4742 t.Fatalf("Bad: %#v", in.Extra[0]) 4743 } 4744 if aRec.Hdr.Ttl != expectedTTL { 4745 t.Fatalf("Bad: %#v", in.Extra[0]) 4746 } 4747 }) 4748 } 4749 // Should have its exact TTL 4750 expectResult("db.service.consul.", 10) 4751 // Should match db* 4752 expectResult("dblb.service.consul.", 66) 4753 // Should match d* 4754 expectResult("dk.service.consul.", 42) 4755 // Should match * 4756 expectResult("api.service.consul.", 5) 4757 } 4758 4759 func TestDNS_PreparedQuery_TTL(t *testing.T) { 4760 t.Parallel() 4761 a := NewTestAgent(t, t.Name(), ` 4762 dns_config { 4763 service_ttl = { 4764 "d*" = "42s" 4765 "db" = "10s" 4766 "db*" = "66s" 4767 "*" = "5s" 4768 } 4769 allow_stale = true 4770 max_stale = "1s" 4771 } 4772 `) 4773 defer a.Shutdown() 4774 testrpc.WaitForLeader(t, a.RPC, "dc1") 4775 4776 for idx, service := range []string{"db", "dblb", "dk", "api"} { 4777 nodeName := fmt.Sprintf("foo%d", idx) 4778 address := fmt.Sprintf("127.0.0.%d", idx) 4779 args := &structs.RegisterRequest{ 4780 Datacenter: "dc1", 4781 Node: nodeName, 4782 Address: address, 4783 Service: &structs.NodeService{ 4784 Service: service, 4785 Tags: []string{"master"}, 4786 Port: 12345 + idx, 4787 }, 4788 } 4789 4790 var out struct{} 4791 if err := a.RPC("Catalog.Register", args, &out); err != nil { 4792 t.Fatalf("err: %v", err) 4793 } 4794 // Register prepared query without TTL and with TTL 4795 { 4796 args := &structs.PreparedQueryRequest{ 4797 Datacenter: "dc1", 4798 Op: structs.PreparedQueryCreate, 4799 Query: &structs.PreparedQuery{ 4800 Name: service, 4801 Service: structs.ServiceQuery{ 4802 Service: service, 4803 }, 4804 }, 4805 } 4806 4807 var id string 4808 if err := a.RPC("PreparedQuery.Apply", args, &id); err != nil { 4809 t.Fatalf("err: %v", err) 4810 } 4811 queryTTL := fmt.Sprintf("%s-ttl", service) 4812 args = &structs.PreparedQueryRequest{ 4813 Datacenter: "dc1", 4814 Op: structs.PreparedQueryCreate, 4815 Query: &structs.PreparedQuery{ 4816 Name: queryTTL, 4817 Service: structs.ServiceQuery{ 4818 Service: service, 4819 }, 4820 DNS: structs.QueryDNSOptions{ 4821 TTL: "18s", 4822 }, 4823 }, 4824 } 4825 4826 if err := a.RPC("PreparedQuery.Apply", args, &id); err != nil { 4827 t.Fatalf("err: %v", err) 4828 } 4829 } 4830 } 4831 4832 c := new(dns.Client) 4833 expectResult := func(dnsQuery string, expectedTTL uint32) { 4834 t.Run(dnsQuery, func(t *testing.T) { 4835 m := new(dns.Msg) 4836 m.SetQuestion(dnsQuery, dns.TypeSRV) 4837 4838 in, _, err := c.Exchange(m, a.DNSAddr()) 4839 if err != nil { 4840 t.Fatalf("err: %v", err) 4841 } 4842 4843 if len(in.Answer) != 1 { 4844 t.Fatalf("Bad: %#v, len is %d", in, len(in.Answer)) 4845 } 4846 4847 srvRec, ok := in.Answer[0].(*dns.SRV) 4848 if !ok { 4849 t.Fatalf("Bad: %#v", in.Answer[0]) 4850 } 4851 if srvRec.Hdr.Ttl != expectedTTL { 4852 t.Fatalf("Bad: %#v", in.Answer[0]) 4853 } 4854 4855 aRec, ok := in.Extra[0].(*dns.A) 4856 if !ok { 4857 t.Fatalf("Bad: %#v", in.Extra[0]) 4858 } 4859 if aRec.Hdr.Ttl != expectedTTL { 4860 t.Fatalf("Bad: %#v", in.Extra[0]) 4861 } 4862 }) 4863 } 4864 4865 // Should have its exact TTL 4866 expectResult("db.query.consul.", 10) 4867 expectResult("db-ttl.query.consul.", 18) 4868 // Should match db* 4869 expectResult("dblb.query.consul.", 66) 4870 expectResult("dblb-ttl.query.consul.", 18) 4871 // Should match d* 4872 expectResult("dk.query.consul.", 42) 4873 expectResult("dk-ttl.query.consul.", 18) 4874 // Should be the default value 4875 expectResult("api.query.consul.", 5) 4876 expectResult("api-ttl.query.consul.", 18) 4877 } 4878 4879 func TestDNS_PreparedQuery_Failover(t *testing.T) { 4880 t.Parallel() 4881 a1 := NewTestAgent(t, t.Name(), ` 4882 datacenter = "dc1" 4883 translate_wan_addrs = true 4884 acl_datacenter = "" 4885 `) 4886 defer a1.Shutdown() 4887 4888 a2 := NewTestAgent(t, t.Name(), ` 4889 datacenter = "dc2" 4890 translate_wan_addrs = true 4891 acl_datacenter = "" 4892 `) 4893 defer a2.Shutdown() 4894 4895 // Join WAN cluster. 4896 addr := fmt.Sprintf("127.0.0.1:%d", a1.Config.SerfPortWAN) 4897 if _, err := a2.JoinWAN([]string{addr}); err != nil { 4898 t.Fatalf("err: %v", err) 4899 } 4900 retry.Run(t, func(r *retry.R) { 4901 if got, want := len(a1.WANMembers()), 2; got < want { 4902 r.Fatalf("got %d WAN members want at least %d", got, want) 4903 } 4904 if got, want := len(a2.WANMembers()), 2; got < want { 4905 r.Fatalf("got %d WAN members want at least %d", got, want) 4906 } 4907 }) 4908 4909 // Register a remote node with a service. This is in a retry since we 4910 // need the datacenter to have a route which takes a little more time 4911 // beyond the join, and we don't have direct access to the router here. 4912 retry.Run(t, func(r *retry.R) { 4913 args := &structs.RegisterRequest{ 4914 Datacenter: "dc2", 4915 Node: "foo", 4916 Address: "127.0.0.1", 4917 TaggedAddresses: map[string]string{ 4918 "wan": "127.0.0.2", 4919 }, 4920 Service: &structs.NodeService{ 4921 Service: "db", 4922 }, 4923 } 4924 4925 var out struct{} 4926 if err := a2.RPC("Catalog.Register", args, &out); err != nil { 4927 r.Fatalf("err: %v", err) 4928 } 4929 }) 4930 4931 // Register a local prepared query. 4932 { 4933 args := &structs.PreparedQueryRequest{ 4934 Datacenter: "dc1", 4935 Op: structs.PreparedQueryCreate, 4936 Query: &structs.PreparedQuery{ 4937 Name: "my-query", 4938 Service: structs.ServiceQuery{ 4939 Service: "db", 4940 Failover: structs.QueryDatacenterOptions{ 4941 Datacenters: []string{"dc2"}, 4942 }, 4943 }, 4944 }, 4945 } 4946 var id string 4947 if err := a1.RPC("PreparedQuery.Apply", args, &id); err != nil { 4948 t.Fatalf("err: %v", err) 4949 } 4950 } 4951 4952 // Look up the SRV record via the query. 4953 m := new(dns.Msg) 4954 m.SetQuestion("my-query.query.consul.", dns.TypeSRV) 4955 4956 c := new(dns.Client) 4957 clAddr := a1.config.DNSAddrs[0] 4958 in, _, err := c.Exchange(m, clAddr.String()) 4959 if err != nil { 4960 t.Fatalf("err: %v", err) 4961 } 4962 4963 // Make sure we see the remote DC and that the address gets 4964 // translated. 4965 if len(in.Answer) != 1 { 4966 t.Fatalf("Bad: %#v", in) 4967 } 4968 if in.Answer[0].Header().Name != "my-query.query.consul." { 4969 t.Fatalf("Bad: %#v", in.Answer[0]) 4970 } 4971 srv, ok := in.Answer[0].(*dns.SRV) 4972 if !ok { 4973 t.Fatalf("Bad: %#v", in.Answer[0]) 4974 } 4975 if srv.Target != "7f000002.addr.dc2.consul." { 4976 t.Fatalf("Bad: %#v", in.Answer[0]) 4977 } 4978 4979 a, ok := in.Extra[0].(*dns.A) 4980 if !ok { 4981 t.Fatalf("Bad: %#v", in.Extra[0]) 4982 } 4983 if a.Hdr.Name != "7f000002.addr.dc2.consul." { 4984 t.Fatalf("Bad: %#v", in.Extra[0]) 4985 } 4986 if a.A.String() != "127.0.0.2" { 4987 t.Fatalf("Bad: %#v", in.Extra[0]) 4988 } 4989 } 4990 4991 func TestDNS_ServiceLookup_SRV_RFC(t *testing.T) { 4992 t.Parallel() 4993 a := NewTestAgent(t, t.Name(), "") 4994 defer a.Shutdown() 4995 testrpc.WaitForLeader(t, a.RPC, "dc1") 4996 4997 // Register node 4998 args := &structs.RegisterRequest{ 4999 Datacenter: "dc1", 5000 Node: "foo", 5001 Address: "127.0.0.1", 5002 Service: &structs.NodeService{ 5003 Service: "db", 5004 Tags: []string{"master"}, 5005 Port: 12345, 5006 }, 5007 } 5008 5009 var out struct{} 5010 if err := a.RPC("Catalog.Register", args, &out); err != nil { 5011 t.Fatalf("err: %v", err) 5012 } 5013 5014 questions := []string{ 5015 "_db._master.service.dc1.consul.", 5016 "_db._master.service.consul.", 5017 "_db._master.dc1.consul.", 5018 "_db._master.consul.", 5019 } 5020 5021 for _, question := range questions { 5022 m := new(dns.Msg) 5023 m.SetQuestion(question, dns.TypeSRV) 5024 5025 c := new(dns.Client) 5026 in, _, err := c.Exchange(m, a.DNSAddr()) 5027 if err != nil { 5028 t.Fatalf("err: %v", err) 5029 } 5030 5031 if len(in.Answer) != 1 { 5032 t.Fatalf("Bad: %#v", in) 5033 } 5034 5035 srvRec, ok := in.Answer[0].(*dns.SRV) 5036 if !ok { 5037 t.Fatalf("Bad: %#v", in.Answer[0]) 5038 } 5039 if srvRec.Port != 12345 { 5040 t.Fatalf("Bad: %#v", srvRec) 5041 } 5042 if srvRec.Target != "foo.node.dc1.consul." { 5043 t.Fatalf("Bad: %#v", srvRec) 5044 } 5045 if srvRec.Hdr.Ttl != 0 { 5046 t.Fatalf("Bad: %#v", in.Answer[0]) 5047 } 5048 5049 aRec, ok := in.Extra[0].(*dns.A) 5050 if !ok { 5051 t.Fatalf("Bad: %#v", in.Extra[0]) 5052 } 5053 if aRec.Hdr.Name != "foo.node.dc1.consul." { 5054 t.Fatalf("Bad: %#v", in.Extra[0]) 5055 } 5056 if aRec.A.String() != "127.0.0.1" { 5057 t.Fatalf("Bad: %#v", in.Extra[0]) 5058 } 5059 if aRec.Hdr.Ttl != 0 { 5060 t.Fatalf("Bad: %#v", in.Extra[0]) 5061 } 5062 } 5063 5064 } 5065 5066 func TestDNS_ServiceLookup_SRV_RFC_TCP_Default(t *testing.T) { 5067 t.Parallel() 5068 a := NewTestAgent(t, t.Name(), "") 5069 defer a.Shutdown() 5070 testrpc.WaitForLeader(t, a.RPC, "dc1") 5071 5072 // Register node 5073 args := &structs.RegisterRequest{ 5074 Datacenter: "dc1", 5075 Node: "foo", 5076 Address: "127.0.0.1", 5077 Service: &structs.NodeService{ 5078 Service: "db", 5079 Tags: []string{"master"}, 5080 Port: 12345, 5081 }, 5082 } 5083 5084 var out struct{} 5085 if err := a.RPC("Catalog.Register", args, &out); err != nil { 5086 t.Fatalf("err: %v", err) 5087 } 5088 5089 questions := []string{ 5090 "_db._tcp.service.dc1.consul.", 5091 "_db._tcp.service.consul.", 5092 "_db._tcp.dc1.consul.", 5093 "_db._tcp.consul.", 5094 } 5095 5096 for _, question := range questions { 5097 m := new(dns.Msg) 5098 m.SetQuestion(question, dns.TypeSRV) 5099 5100 c := new(dns.Client) 5101 in, _, err := c.Exchange(m, a.DNSAddr()) 5102 if err != nil { 5103 t.Fatalf("err: %v", err) 5104 } 5105 5106 if len(in.Answer) != 1 { 5107 t.Fatalf("Bad: %#v", in) 5108 } 5109 5110 srvRec, ok := in.Answer[0].(*dns.SRV) 5111 if !ok { 5112 t.Fatalf("Bad: %#v", in.Answer[0]) 5113 } 5114 if srvRec.Port != 12345 { 5115 t.Fatalf("Bad: %#v", srvRec) 5116 } 5117 if srvRec.Target != "foo.node.dc1.consul." { 5118 t.Fatalf("Bad: %#v", srvRec) 5119 } 5120 if srvRec.Hdr.Ttl != 0 { 5121 t.Fatalf("Bad: %#v", in.Answer[0]) 5122 } 5123 5124 aRec, ok := in.Extra[0].(*dns.A) 5125 if !ok { 5126 t.Fatalf("Bad: %#v", in.Extra[0]) 5127 } 5128 if aRec.Hdr.Name != "foo.node.dc1.consul." { 5129 t.Fatalf("Bad: %#v", in.Extra[0]) 5130 } 5131 if aRec.A.String() != "127.0.0.1" { 5132 t.Fatalf("Bad: %#v", in.Extra[0]) 5133 } 5134 if aRec.Hdr.Ttl != 0 { 5135 t.Fatalf("Bad: %#v", in.Extra[0]) 5136 } 5137 } 5138 5139 } 5140 5141 func TestDNS_ServiceLookup_FilterACL(t *testing.T) { 5142 t.Parallel() 5143 tests := []struct { 5144 token string 5145 results int 5146 }{ 5147 {"root", 1}, 5148 {"anonymous", 0}, 5149 } 5150 for _, tt := range tests { 5151 t.Run("ACLToken == "+tt.token, func(t *testing.T) { 5152 a := NewTestAgent(t, t.Name(), ` 5153 acl_token = "`+tt.token+`" 5154 acl_master_token = "root" 5155 acl_datacenter = "dc1" 5156 acl_down_policy = "deny" 5157 acl_default_policy = "deny" 5158 `) 5159 defer a.Shutdown() 5160 testrpc.WaitForLeader(t, a.RPC, "dc1") 5161 5162 // Register a service 5163 args := &structs.RegisterRequest{ 5164 Datacenter: "dc1", 5165 Node: "foo", 5166 Address: "127.0.0.1", 5167 Service: &structs.NodeService{ 5168 Service: "foo", 5169 Port: 12345, 5170 }, 5171 WriteRequest: structs.WriteRequest{Token: "root"}, 5172 } 5173 var out struct{} 5174 if err := a.RPC("Catalog.Register", args, &out); err != nil { 5175 t.Fatalf("err: %v", err) 5176 } 5177 5178 // Set up the DNS query 5179 c := new(dns.Client) 5180 m := new(dns.Msg) 5181 m.SetQuestion("foo.service.consul.", dns.TypeA) 5182 5183 in, _, err := c.Exchange(m, a.DNSAddr()) 5184 if err != nil { 5185 t.Fatalf("err: %v", err) 5186 } 5187 if len(in.Answer) != tt.results { 5188 t.Fatalf("Bad: %#v", in) 5189 } 5190 }) 5191 } 5192 } 5193 5194 func TestDNS_ServiceLookup_MetaTXT(t *testing.T) { 5195 a := NewTestAgent(t, t.Name(), `dns_config = { enable_additional_node_meta_txt = true }`) 5196 defer a.Shutdown() 5197 testrpc.WaitForLeader(t, a.RPC, "dc1") 5198 5199 args := &structs.RegisterRequest{ 5200 Datacenter: "dc1", 5201 Node: "bar", 5202 Address: "127.0.0.1", 5203 NodeMeta: map[string]string{ 5204 "key": "value", 5205 }, 5206 Service: &structs.NodeService{ 5207 Service: "db", 5208 Tags: []string{"master"}, 5209 Port: 12345, 5210 }, 5211 } 5212 5213 var out struct{} 5214 if err := a.RPC("Catalog.Register", args, &out); err != nil { 5215 t.Fatalf("err: %v", err) 5216 } 5217 5218 m := new(dns.Msg) 5219 m.SetQuestion("db.service.consul.", dns.TypeSRV) 5220 5221 c := new(dns.Client) 5222 in, _, err := c.Exchange(m, a.DNSAddr()) 5223 if err != nil { 5224 t.Fatalf("err: %v", err) 5225 } 5226 5227 wantAdditional := []dns.RR{ 5228 &dns.A{ 5229 Hdr: dns.RR_Header{Name: "bar.node.dc1.consul.", Rrtype: dns.TypeA, Class: dns.ClassINET, Rdlength: 0x4}, 5230 A: []byte{0x7f, 0x0, 0x0, 0x1}, // 127.0.0.1 5231 }, 5232 &dns.TXT{ 5233 Hdr: dns.RR_Header{Name: "bar.node.dc1.consul.", Rrtype: dns.TypeTXT, Class: dns.ClassINET, Rdlength: 0xa}, 5234 Txt: []string{"key=value"}, 5235 }, 5236 } 5237 verify.Values(t, "additional", in.Extra, wantAdditional) 5238 } 5239 5240 func TestDNS_ServiceLookup_SuppressTXT(t *testing.T) { 5241 a := NewTestAgent(t, t.Name(), `dns_config = { enable_additional_node_meta_txt = false }`) 5242 defer a.Shutdown() 5243 testrpc.WaitForLeader(t, a.RPC, "dc1") 5244 5245 // Register a node with a service. 5246 args := &structs.RegisterRequest{ 5247 Datacenter: "dc1", 5248 Node: "bar", 5249 Address: "127.0.0.1", 5250 NodeMeta: map[string]string{ 5251 "key": "value", 5252 }, 5253 Service: &structs.NodeService{ 5254 Service: "db", 5255 Tags: []string{"master"}, 5256 Port: 12345, 5257 }, 5258 } 5259 5260 var out struct{} 5261 if err := a.RPC("Catalog.Register", args, &out); err != nil { 5262 t.Fatalf("err: %v", err) 5263 } 5264 5265 m := new(dns.Msg) 5266 m.SetQuestion("db.service.consul.", dns.TypeSRV) 5267 5268 c := new(dns.Client) 5269 in, _, err := c.Exchange(m, a.DNSAddr()) 5270 if err != nil { 5271 t.Fatalf("err: %v", err) 5272 } 5273 5274 wantAdditional := []dns.RR{ 5275 &dns.A{ 5276 Hdr: dns.RR_Header{Name: "bar.node.dc1.consul.", Rrtype: dns.TypeA, Class: dns.ClassINET, Rdlength: 0x4}, 5277 A: []byte{0x7f, 0x0, 0x0, 0x1}, // 127.0.0.1 5278 }, 5279 } 5280 verify.Values(t, "additional", in.Extra, wantAdditional) 5281 } 5282 5283 func TestDNS_AddressLookup(t *testing.T) { 5284 t.Parallel() 5285 a := NewTestAgent(t, t.Name(), "") 5286 defer a.Shutdown() 5287 testrpc.WaitForLeader(t, a.RPC, "dc1") 5288 5289 // Look up the addresses 5290 cases := map[string]string{ 5291 "7f000001.addr.dc1.consul.": "127.0.0.1", 5292 } 5293 for question, answer := range cases { 5294 m := new(dns.Msg) 5295 m.SetQuestion(question, dns.TypeSRV) 5296 5297 c := new(dns.Client) 5298 in, _, err := c.Exchange(m, a.DNSAddr()) 5299 if err != nil { 5300 t.Fatalf("err: %v", err) 5301 } 5302 5303 if len(in.Answer) != 1 { 5304 t.Fatalf("Bad: %#v", in) 5305 } 5306 5307 aRec, ok := in.Answer[0].(*dns.A) 5308 if !ok { 5309 t.Fatalf("Bad: %#v", in.Answer[0]) 5310 } 5311 if aRec.A.To4().String() != answer { 5312 t.Fatalf("Bad: %#v", aRec) 5313 } 5314 if aRec.Hdr.Ttl != 0 { 5315 t.Fatalf("Bad: %#v", in.Answer[0]) 5316 } 5317 } 5318 } 5319 5320 func TestDNS_AddressLookupIPV6(t *testing.T) { 5321 t.Parallel() 5322 a := NewTestAgent(t, t.Name(), "") 5323 defer a.Shutdown() 5324 testrpc.WaitForLeader(t, a.RPC, "dc1") 5325 5326 // Look up the addresses 5327 cases := map[string]string{ 5328 "2607002040050808000000000000200e.addr.consul.": "2607:20:4005:808::200e", 5329 "2607112040051808ffffffffffff200e.addr.consul.": "2607:1120:4005:1808:ffff:ffff:ffff:200e", 5330 } 5331 for question, answer := range cases { 5332 m := new(dns.Msg) 5333 m.SetQuestion(question, dns.TypeSRV) 5334 5335 c := new(dns.Client) 5336 in, _, err := c.Exchange(m, a.DNSAddr()) 5337 if err != nil { 5338 t.Fatalf("err: %v", err) 5339 } 5340 5341 if len(in.Answer) != 1 { 5342 t.Fatalf("Bad: %#v", in) 5343 } 5344 5345 aaaaRec, ok := in.Answer[0].(*dns.AAAA) 5346 if !ok { 5347 t.Fatalf("Bad: %#v", in.Answer[0]) 5348 } 5349 if aaaaRec.AAAA.To16().String() != answer { 5350 t.Fatalf("Bad: %#v", aaaaRec) 5351 } 5352 if aaaaRec.Hdr.Ttl != 0 { 5353 t.Fatalf("Bad: %#v", in.Answer[0]) 5354 } 5355 } 5356 } 5357 5358 func TestDNS_NonExistingLookup(t *testing.T) { 5359 t.Parallel() 5360 a := NewTestAgent(t, t.Name(), "") 5361 defer a.Shutdown() 5362 testrpc.WaitForLeader(t, a.RPC, "dc1") 5363 5364 // lookup a non-existing node, we should receive a SOA 5365 m := new(dns.Msg) 5366 m.SetQuestion("nonexisting.consul.", dns.TypeANY) 5367 5368 c := new(dns.Client) 5369 in, _, err := c.Exchange(m, a.DNSAddr()) 5370 if err != nil { 5371 t.Fatalf("err: %v", err) 5372 } 5373 5374 if len(in.Ns) != 1 { 5375 t.Fatalf("Bad: %#v %#v", in, len(in.Answer)) 5376 } 5377 5378 soaRec, ok := in.Ns[0].(*dns.SOA) 5379 if !ok { 5380 t.Fatalf("Bad: %#v", in.Ns[0]) 5381 } 5382 if soaRec.Hdr.Ttl != 0 { 5383 t.Fatalf("Bad: %#v", in.Ns[0]) 5384 } 5385 } 5386 5387 func TestDNS_NonExistingLookupEmptyAorAAAA(t *testing.T) { 5388 t.Parallel() 5389 a := NewTestAgent(t, t.Name(), "") 5390 defer a.Shutdown() 5391 testrpc.WaitForLeader(t, a.RPC, "dc1") 5392 5393 // Register a v6-only service and a v4-only service. 5394 { 5395 args := &structs.RegisterRequest{ 5396 Datacenter: "dc1", 5397 Node: "foov6", 5398 Address: "fe80::1", 5399 Service: &structs.NodeService{ 5400 Service: "webv6", 5401 Port: 8000, 5402 }, 5403 } 5404 5405 var out struct{} 5406 if err := a.RPC("Catalog.Register", args, &out); err != nil { 5407 t.Fatalf("err: %v", err) 5408 } 5409 5410 args = &structs.RegisterRequest{ 5411 Datacenter: "dc1", 5412 Node: "foov4", 5413 Address: "127.0.0.1", 5414 Service: &structs.NodeService{ 5415 Service: "webv4", 5416 Port: 8000, 5417 }, 5418 } 5419 5420 if err := a.RPC("Catalog.Register", args, &out); err != nil { 5421 t.Fatalf("err: %v", err) 5422 } 5423 } 5424 5425 // Register equivalent prepared queries. 5426 { 5427 args := &structs.PreparedQueryRequest{ 5428 Datacenter: "dc1", 5429 Op: structs.PreparedQueryCreate, 5430 Query: &structs.PreparedQuery{ 5431 Name: "webv4", 5432 Service: structs.ServiceQuery{ 5433 Service: "webv4", 5434 }, 5435 }, 5436 } 5437 5438 var id string 5439 if err := a.RPC("PreparedQuery.Apply", args, &id); err != nil { 5440 t.Fatalf("err: %v", err) 5441 } 5442 5443 args = &structs.PreparedQueryRequest{ 5444 Datacenter: "dc1", 5445 Op: structs.PreparedQueryCreate, 5446 Query: &structs.PreparedQuery{ 5447 Name: "webv6", 5448 Service: structs.ServiceQuery{ 5449 Service: "webv6", 5450 }, 5451 }, 5452 } 5453 5454 if err := a.RPC("PreparedQuery.Apply", args, &id); err != nil { 5455 t.Fatalf("err: %v", err) 5456 } 5457 } 5458 5459 // Check for ipv6 records on ipv4-only service directly and via the 5460 // prepared query. 5461 questions := []string{ 5462 "webv4.service.consul.", 5463 "webv4.query.consul.", 5464 } 5465 for _, question := range questions { 5466 m := new(dns.Msg) 5467 m.SetQuestion(question, dns.TypeAAAA) 5468 5469 c := new(dns.Client) 5470 in, _, err := c.Exchange(m, a.DNSAddr()) 5471 if err != nil { 5472 t.Fatalf("err: %v", err) 5473 } 5474 5475 if len(in.Ns) != 1 { 5476 t.Fatalf("Bad: %#v", in) 5477 } 5478 soaRec, ok := in.Ns[0].(*dns.SOA) 5479 if !ok { 5480 t.Fatalf("Bad: %#v", in.Ns[0]) 5481 } 5482 if soaRec.Hdr.Ttl != 0 { 5483 t.Fatalf("Bad: %#v", in.Ns[0]) 5484 } 5485 5486 if in.Rcode != dns.RcodeSuccess { 5487 t.Fatalf("Bad: %#v", in) 5488 } 5489 5490 } 5491 5492 // Check for ipv4 records on ipv6-only service directly and via the 5493 // prepared query. 5494 questions = []string{ 5495 "webv6.service.consul.", 5496 "webv6.query.consul.", 5497 } 5498 for _, question := range questions { 5499 m := new(dns.Msg) 5500 m.SetQuestion(question, dns.TypeA) 5501 5502 c := new(dns.Client) 5503 in, _, err := c.Exchange(m, a.DNSAddr()) 5504 if err != nil { 5505 t.Fatalf("err: %v", err) 5506 } 5507 5508 if len(in.Ns) != 1 { 5509 t.Fatalf("Bad: %#v", in) 5510 } 5511 5512 soaRec, ok := in.Ns[0].(*dns.SOA) 5513 if !ok { 5514 t.Fatalf("Bad: %#v", in.Ns[0]) 5515 } 5516 if soaRec.Hdr.Ttl != 0 { 5517 t.Fatalf("Bad: %#v", in.Ns[0]) 5518 } 5519 5520 if in.Rcode != dns.RcodeSuccess { 5521 t.Fatalf("Bad: %#v", in) 5522 } 5523 } 5524 } 5525 5526 func TestDNS_PreparedQuery_AllowStale(t *testing.T) { 5527 t.Parallel() 5528 a := NewTestAgent(t, t.Name(), ` 5529 dns_config { 5530 allow_stale = true 5531 max_stale = "1s" 5532 } 5533 `) 5534 defer a.Shutdown() 5535 testrpc.WaitForLeader(t, a.RPC, "dc1") 5536 5537 m := MockPreparedQuery{ 5538 executeFn: func(args *structs.PreparedQueryExecuteRequest, reply *structs.PreparedQueryExecuteResponse) error { 5539 // Return a response that's perpetually too stale. 5540 reply.LastContact = 2 * time.Second 5541 return nil 5542 }, 5543 } 5544 5545 if err := a.registerEndpoint("PreparedQuery", &m); err != nil { 5546 t.Fatalf("err: %v", err) 5547 } 5548 5549 // Make sure that the lookup terminates and results in an SOA since 5550 // the query doesn't exist. 5551 { 5552 m := new(dns.Msg) 5553 m.SetQuestion("nope.query.consul.", dns.TypeSRV) 5554 5555 c := new(dns.Client) 5556 in, _, err := c.Exchange(m, a.DNSAddr()) 5557 if err != nil { 5558 t.Fatalf("err: %v", err) 5559 } 5560 5561 if len(in.Ns) != 1 { 5562 t.Fatalf("Bad: %#v", in) 5563 } 5564 5565 soaRec, ok := in.Ns[0].(*dns.SOA) 5566 if !ok { 5567 t.Fatalf("Bad: %#v", in.Ns[0]) 5568 } 5569 if soaRec.Hdr.Ttl != 0 { 5570 t.Fatalf("Bad: %#v", in.Ns[0]) 5571 } 5572 5573 } 5574 } 5575 5576 func TestDNS_InvalidQueries(t *testing.T) { 5577 t.Parallel() 5578 a := NewTestAgent(t, t.Name(), "") 5579 defer a.Shutdown() 5580 testrpc.WaitForLeader(t, a.RPC, "dc1") 5581 5582 // Try invalid forms of queries that should hit the special invalid case 5583 // of our query parser. 5584 questions := []string{ 5585 "consul.", 5586 "node.consul.", 5587 "service.consul.", 5588 "query.consul.", 5589 "foo.node.dc1.extra.consul.", 5590 "foo.service.dc1.extra.consul.", 5591 "foo.query.dc1.extra.consul.", 5592 } 5593 for _, question := range questions { 5594 m := new(dns.Msg) 5595 m.SetQuestion(question, dns.TypeSRV) 5596 5597 c := new(dns.Client) 5598 in, _, err := c.Exchange(m, a.DNSAddr()) 5599 if err != nil { 5600 t.Fatalf("err: %v", err) 5601 } 5602 5603 if len(in.Ns) != 1 { 5604 t.Fatalf("Bad: %#v", in) 5605 } 5606 5607 soaRec, ok := in.Ns[0].(*dns.SOA) 5608 if !ok { 5609 t.Fatalf("Bad: %#v", in.Ns[0]) 5610 } 5611 if soaRec.Hdr.Ttl != 0 { 5612 t.Fatalf("Bad: %#v", in.Ns[0]) 5613 } 5614 5615 } 5616 } 5617 5618 func TestDNS_PreparedQuery_AgentSource(t *testing.T) { 5619 t.Parallel() 5620 a := NewTestAgent(t, t.Name(), "") 5621 defer a.Shutdown() 5622 testrpc.WaitForLeader(t, a.RPC, "dc1") 5623 5624 m := MockPreparedQuery{ 5625 executeFn: func(args *structs.PreparedQueryExecuteRequest, reply *structs.PreparedQueryExecuteResponse) error { 5626 // Check that the agent inserted its self-name and datacenter to 5627 // the RPC request body. 5628 if args.Agent.Datacenter != a.Config.Datacenter || 5629 args.Agent.Node != a.Config.NodeName { 5630 t.Fatalf("bad: %#v", args.Agent) 5631 } 5632 return nil 5633 }, 5634 } 5635 5636 if err := a.registerEndpoint("PreparedQuery", &m); err != nil { 5637 t.Fatalf("err: %v", err) 5638 } 5639 5640 { 5641 m := new(dns.Msg) 5642 m.SetQuestion("foo.query.consul.", dns.TypeSRV) 5643 5644 c := new(dns.Client) 5645 if _, _, err := c.Exchange(m, a.DNSAddr()); err != nil { 5646 t.Fatalf("err: %v", err) 5647 } 5648 } 5649 } 5650 5651 func TestDNS_trimUDPResponse_NoTrim(t *testing.T) { 5652 t.Parallel() 5653 req := &dns.Msg{} 5654 resp := &dns.Msg{ 5655 Answer: []dns.RR{ 5656 &dns.SRV{ 5657 Hdr: dns.RR_Header{ 5658 Name: "redis-cache-redis.service.consul.", 5659 Rrtype: dns.TypeSRV, 5660 Class: dns.ClassINET, 5661 }, 5662 Target: "ip-10-0-1-185.node.dc1.consul.", 5663 }, 5664 }, 5665 Extra: []dns.RR{ 5666 &dns.A{ 5667 Hdr: dns.RR_Header{ 5668 Name: "ip-10-0-1-185.node.dc1.consul.", 5669 Rrtype: dns.TypeA, 5670 Class: dns.ClassINET, 5671 }, 5672 A: net.ParseIP("10.0.1.185"), 5673 }, 5674 }, 5675 } 5676 5677 cfg := config.DefaultRuntimeConfig(`data_dir = "a" bind_addr = "127.0.0.1"`) 5678 if trimmed := trimUDPResponse(req, resp, cfg.DNSUDPAnswerLimit); trimmed { 5679 t.Fatalf("Bad %#v", *resp) 5680 } 5681 5682 expected := &dns.Msg{ 5683 Answer: []dns.RR{ 5684 &dns.SRV{ 5685 Hdr: dns.RR_Header{ 5686 Name: "redis-cache-redis.service.consul.", 5687 Rrtype: dns.TypeSRV, 5688 Class: dns.ClassINET, 5689 }, 5690 Target: "ip-10-0-1-185.node.dc1.consul.", 5691 }, 5692 }, 5693 Extra: []dns.RR{ 5694 &dns.A{ 5695 Hdr: dns.RR_Header{ 5696 Name: "ip-10-0-1-185.node.dc1.consul.", 5697 Rrtype: dns.TypeA, 5698 Class: dns.ClassINET, 5699 }, 5700 A: net.ParseIP("10.0.1.185"), 5701 }, 5702 }, 5703 } 5704 if !reflect.DeepEqual(resp, expected) { 5705 t.Fatalf("Bad %#v vs. %#v", *resp, *expected) 5706 } 5707 } 5708 5709 func TestDNS_trimUDPResponse_TrimLimit(t *testing.T) { 5710 t.Parallel() 5711 cfg := config.DefaultRuntimeConfig(`data_dir = "a" bind_addr = "127.0.0.1"`) 5712 5713 req, resp, expected := &dns.Msg{}, &dns.Msg{}, &dns.Msg{} 5714 for i := 0; i < cfg.DNSUDPAnswerLimit+1; i++ { 5715 target := fmt.Sprintf("ip-10-0-1-%d.node.dc1.consul.", 185+i) 5716 srv := &dns.SRV{ 5717 Hdr: dns.RR_Header{ 5718 Name: "redis-cache-redis.service.consul.", 5719 Rrtype: dns.TypeSRV, 5720 Class: dns.ClassINET, 5721 }, 5722 Target: target, 5723 } 5724 a := &dns.A{ 5725 Hdr: dns.RR_Header{ 5726 Name: target, 5727 Rrtype: dns.TypeA, 5728 Class: dns.ClassINET, 5729 }, 5730 A: net.ParseIP(fmt.Sprintf("10.0.1.%d", 185+i)), 5731 } 5732 5733 resp.Answer = append(resp.Answer, srv) 5734 resp.Extra = append(resp.Extra, a) 5735 if i < cfg.DNSUDPAnswerLimit { 5736 expected.Answer = append(expected.Answer, srv) 5737 expected.Extra = append(expected.Extra, a) 5738 } 5739 } 5740 5741 if trimmed := trimUDPResponse(req, resp, cfg.DNSUDPAnswerLimit); !trimmed { 5742 t.Fatalf("Bad %#v", *resp) 5743 } 5744 if !reflect.DeepEqual(resp, expected) { 5745 t.Fatalf("Bad %#v vs. %#v", *resp, *expected) 5746 } 5747 } 5748 5749 func TestDNS_trimUDPResponse_TrimSize(t *testing.T) { 5750 t.Parallel() 5751 cfg := config.DefaultRuntimeConfig(`data_dir = "a" bind_addr = "127.0.0.1"`) 5752 5753 req, resp := &dns.Msg{}, &dns.Msg{} 5754 for i := 0; i < 100; i++ { 5755 target := fmt.Sprintf("ip-10-0-1-%d.node.dc1.consul.", 185+i) 5756 srv := &dns.SRV{ 5757 Hdr: dns.RR_Header{ 5758 Name: "redis-cache-redis.service.consul.", 5759 Rrtype: dns.TypeSRV, 5760 Class: dns.ClassINET, 5761 }, 5762 Target: target, 5763 } 5764 a := &dns.A{ 5765 Hdr: dns.RR_Header{ 5766 Name: target, 5767 Rrtype: dns.TypeA, 5768 Class: dns.ClassINET, 5769 }, 5770 A: net.ParseIP(fmt.Sprintf("10.0.1.%d", 185+i)), 5771 } 5772 5773 resp.Answer = append(resp.Answer, srv) 5774 resp.Extra = append(resp.Extra, a) 5775 } 5776 5777 // We don't know the exact trim, but we know the resulting answer 5778 // data should match its extra data. 5779 if trimmed := trimUDPResponse(req, resp, cfg.DNSUDPAnswerLimit); !trimmed { 5780 t.Fatalf("Bad %#v", *resp) 5781 } 5782 if len(resp.Answer) == 0 || len(resp.Answer) != len(resp.Extra) { 5783 t.Fatalf("Bad %#v", *resp) 5784 } 5785 for i := range resp.Answer { 5786 srv, ok := resp.Answer[i].(*dns.SRV) 5787 if !ok { 5788 t.Fatalf("should be SRV") 5789 } 5790 5791 a, ok := resp.Extra[i].(*dns.A) 5792 if !ok { 5793 t.Fatalf("should be A") 5794 } 5795 5796 if srv.Target != a.Header().Name { 5797 t.Fatalf("Bad %#v vs. %#v", *srv, *a) 5798 } 5799 } 5800 } 5801 5802 func TestDNS_trimUDPResponse_TrimSizeEDNS(t *testing.T) { 5803 t.Parallel() 5804 cfg := config.DefaultRuntimeConfig(`data_dir = "a" bind_addr = "127.0.0.1"`) 5805 5806 req, resp := &dns.Msg{}, &dns.Msg{} 5807 5808 for i := 0; i < 100; i++ { 5809 target := fmt.Sprintf("ip-10-0-1-%d.node.dc1.consul.", 150+i) 5810 srv := &dns.SRV{ 5811 Hdr: dns.RR_Header{ 5812 Name: "redis-cache-redis.service.consul.", 5813 Rrtype: dns.TypeSRV, 5814 Class: dns.ClassINET, 5815 }, 5816 Target: target, 5817 } 5818 a := &dns.A{ 5819 Hdr: dns.RR_Header{ 5820 Name: target, 5821 Rrtype: dns.TypeA, 5822 Class: dns.ClassINET, 5823 }, 5824 A: net.ParseIP(fmt.Sprintf("10.0.1.%d", 150+i)), 5825 } 5826 5827 resp.Answer = append(resp.Answer, srv) 5828 resp.Extra = append(resp.Extra, a) 5829 } 5830 5831 // Copy over to a new slice since we are trimming both. 5832 reqEDNS, respEDNS := &dns.Msg{}, &dns.Msg{} 5833 reqEDNS.SetEdns0(2048, true) 5834 respEDNS.Answer = append(respEDNS.Answer, resp.Answer...) 5835 respEDNS.Extra = append(respEDNS.Extra, resp.Extra...) 5836 5837 // Trim each response 5838 if trimmed := trimUDPResponse(req, resp, cfg.DNSUDPAnswerLimit); !trimmed { 5839 t.Errorf("expected response to be trimmed: %#v", resp) 5840 } 5841 if trimmed := trimUDPResponse(reqEDNS, respEDNS, cfg.DNSUDPAnswerLimit); !trimmed { 5842 t.Errorf("expected edns to be trimmed: %#v", resp) 5843 } 5844 5845 // Check answer lengths 5846 if len(resp.Answer) == 0 || len(resp.Answer) != len(resp.Extra) { 5847 t.Errorf("bad response answer length: %#v", resp) 5848 } 5849 if len(respEDNS.Answer) == 0 || len(respEDNS.Answer) != len(respEDNS.Extra) { 5850 t.Errorf("bad edns answer length: %#v", resp) 5851 } 5852 5853 // Due to the compression, we can't check exact equality of sizes, but we can 5854 // make two requests and ensure that the edns one returns a larger payload 5855 // than the non-edns0 one. 5856 if len(resp.Answer) >= len(respEDNS.Answer) { 5857 t.Errorf("expected edns have larger answer: %#v\n%#v", resp, respEDNS) 5858 } 5859 if len(resp.Extra) >= len(respEDNS.Extra) { 5860 t.Errorf("expected edns have larger extra: %#v\n%#v", resp, respEDNS) 5861 } 5862 5863 // Verify that the things point where they should 5864 for i := range resp.Answer { 5865 srv, ok := resp.Answer[i].(*dns.SRV) 5866 if !ok { 5867 t.Errorf("%d should be an SRV", i) 5868 } 5869 5870 a, ok := resp.Extra[i].(*dns.A) 5871 if !ok { 5872 t.Errorf("%d should be an A", i) 5873 } 5874 5875 if srv.Target != a.Header().Name { 5876 t.Errorf("%d: bad %#v vs. %#v", i, srv, a) 5877 } 5878 } 5879 } 5880 5881 func TestDNS_syncExtra(t *testing.T) { 5882 t.Parallel() 5883 resp := &dns.Msg{ 5884 Answer: []dns.RR{ 5885 // These two are on the same host so the redundant extra 5886 // records should get deduplicated. 5887 &dns.SRV{ 5888 Hdr: dns.RR_Header{ 5889 Name: "redis-cache-redis.service.consul.", 5890 Rrtype: dns.TypeSRV, 5891 Class: dns.ClassINET, 5892 }, 5893 Port: 1001, 5894 Target: "ip-10-0-1-185.node.dc1.consul.", 5895 }, 5896 &dns.SRV{ 5897 Hdr: dns.RR_Header{ 5898 Name: "redis-cache-redis.service.consul.", 5899 Rrtype: dns.TypeSRV, 5900 Class: dns.ClassINET, 5901 }, 5902 Port: 1002, 5903 Target: "ip-10-0-1-185.node.dc1.consul.", 5904 }, 5905 // This one isn't in the Consul domain so it will get a 5906 // CNAME and then an A record from the recursor. 5907 &dns.SRV{ 5908 Hdr: dns.RR_Header{ 5909 Name: "redis-cache-redis.service.consul.", 5910 Rrtype: dns.TypeSRV, 5911 Class: dns.ClassINET, 5912 }, 5913 Port: 1003, 5914 Target: "demo.consul.io.", 5915 }, 5916 // This one isn't in the Consul domain and it will get 5917 // a CNAME and A record from a recursor that alters the 5918 // case of the name. This proves we look up in the index 5919 // in a case-insensitive way. 5920 &dns.SRV{ 5921 Hdr: dns.RR_Header{ 5922 Name: "redis-cache-redis.service.consul.", 5923 Rrtype: dns.TypeSRV, 5924 Class: dns.ClassINET, 5925 }, 5926 Port: 1001, 5927 Target: "insensitive.consul.io.", 5928 }, 5929 // This is also a CNAME, but it'll be set up to loop to 5930 // make sure we don't crash. 5931 &dns.SRV{ 5932 Hdr: dns.RR_Header{ 5933 Name: "redis-cache-redis.service.consul.", 5934 Rrtype: dns.TypeSRV, 5935 Class: dns.ClassINET, 5936 }, 5937 Port: 1001, 5938 Target: "deadly.consul.io.", 5939 }, 5940 // This is also a CNAME, but it won't have another record. 5941 &dns.SRV{ 5942 Hdr: dns.RR_Header{ 5943 Name: "redis-cache-redis.service.consul.", 5944 Rrtype: dns.TypeSRV, 5945 Class: dns.ClassINET, 5946 }, 5947 Port: 1001, 5948 Target: "nope.consul.io.", 5949 }, 5950 }, 5951 Extra: []dns.RR{ 5952 // These should get deduplicated. 5953 &dns.A{ 5954 Hdr: dns.RR_Header{ 5955 Name: "ip-10-0-1-185.node.dc1.consul.", 5956 Rrtype: dns.TypeA, 5957 Class: dns.ClassINET, 5958 }, 5959 A: net.ParseIP("10.0.1.185"), 5960 }, 5961 &dns.A{ 5962 Hdr: dns.RR_Header{ 5963 Name: "ip-10-0-1-185.node.dc1.consul.", 5964 Rrtype: dns.TypeA, 5965 Class: dns.ClassINET, 5966 }, 5967 A: net.ParseIP("10.0.1.185"), 5968 }, 5969 // This is a normal CNAME followed by an A record but we 5970 // have flipped the order. The algorithm should emit them 5971 // in the opposite order. 5972 &dns.A{ 5973 Hdr: dns.RR_Header{ 5974 Name: "fakeserver.consul.io.", 5975 Rrtype: dns.TypeA, 5976 Class: dns.ClassINET, 5977 }, 5978 A: net.ParseIP("127.0.0.1"), 5979 }, 5980 &dns.CNAME{ 5981 Hdr: dns.RR_Header{ 5982 Name: "demo.consul.io.", 5983 Rrtype: dns.TypeCNAME, 5984 Class: dns.ClassINET, 5985 }, 5986 Target: "fakeserver.consul.io.", 5987 }, 5988 // These differ in case to test case insensitivity. 5989 &dns.CNAME{ 5990 Hdr: dns.RR_Header{ 5991 Name: "INSENSITIVE.CONSUL.IO.", 5992 Rrtype: dns.TypeCNAME, 5993 Class: dns.ClassINET, 5994 }, 5995 Target: "Another.Server.Com.", 5996 }, 5997 &dns.A{ 5998 Hdr: dns.RR_Header{ 5999 Name: "another.server.com.", 6000 Rrtype: dns.TypeA, 6001 Class: dns.ClassINET, 6002 }, 6003 A: net.ParseIP("127.0.0.1"), 6004 }, 6005 // This doesn't appear in the answer, so should get 6006 // dropped. 6007 &dns.A{ 6008 Hdr: dns.RR_Header{ 6009 Name: "ip-10-0-1-186.node.dc1.consul.", 6010 Rrtype: dns.TypeA, 6011 Class: dns.ClassINET, 6012 }, 6013 A: net.ParseIP("10.0.1.186"), 6014 }, 6015 // These two test edge cases with CNAME handling. 6016 &dns.CNAME{ 6017 Hdr: dns.RR_Header{ 6018 Name: "deadly.consul.io.", 6019 Rrtype: dns.TypeCNAME, 6020 Class: dns.ClassINET, 6021 }, 6022 Target: "deadly.consul.io.", 6023 }, 6024 &dns.CNAME{ 6025 Hdr: dns.RR_Header{ 6026 Name: "nope.consul.io.", 6027 Rrtype: dns.TypeCNAME, 6028 Class: dns.ClassINET, 6029 }, 6030 Target: "notthere.consul.io.", 6031 }, 6032 }, 6033 } 6034 6035 index := make(map[string]dns.RR) 6036 indexRRs(resp.Extra, index) 6037 syncExtra(index, resp) 6038 6039 expected := &dns.Msg{ 6040 Answer: resp.Answer, 6041 Extra: []dns.RR{ 6042 &dns.A{ 6043 Hdr: dns.RR_Header{ 6044 Name: "ip-10-0-1-185.node.dc1.consul.", 6045 Rrtype: dns.TypeA, 6046 Class: dns.ClassINET, 6047 }, 6048 A: net.ParseIP("10.0.1.185"), 6049 }, 6050 &dns.CNAME{ 6051 Hdr: dns.RR_Header{ 6052 Name: "demo.consul.io.", 6053 Rrtype: dns.TypeCNAME, 6054 Class: dns.ClassINET, 6055 }, 6056 Target: "fakeserver.consul.io.", 6057 }, 6058 &dns.A{ 6059 Hdr: dns.RR_Header{ 6060 Name: "fakeserver.consul.io.", 6061 Rrtype: dns.TypeA, 6062 Class: dns.ClassINET, 6063 }, 6064 A: net.ParseIP("127.0.0.1"), 6065 }, 6066 &dns.CNAME{ 6067 Hdr: dns.RR_Header{ 6068 Name: "INSENSITIVE.CONSUL.IO.", 6069 Rrtype: dns.TypeCNAME, 6070 Class: dns.ClassINET, 6071 }, 6072 Target: "Another.Server.Com.", 6073 }, 6074 &dns.A{ 6075 Hdr: dns.RR_Header{ 6076 Name: "another.server.com.", 6077 Rrtype: dns.TypeA, 6078 Class: dns.ClassINET, 6079 }, 6080 A: net.ParseIP("127.0.0.1"), 6081 }, 6082 &dns.CNAME{ 6083 Hdr: dns.RR_Header{ 6084 Name: "deadly.consul.io.", 6085 Rrtype: dns.TypeCNAME, 6086 Class: dns.ClassINET, 6087 }, 6088 Target: "deadly.consul.io.", 6089 }, 6090 &dns.CNAME{ 6091 Hdr: dns.RR_Header{ 6092 Name: "nope.consul.io.", 6093 Rrtype: dns.TypeCNAME, 6094 Class: dns.ClassINET, 6095 }, 6096 Target: "notthere.consul.io.", 6097 }, 6098 }, 6099 } 6100 if !reflect.DeepEqual(resp, expected) { 6101 t.Fatalf("Bad %#v vs. %#v", *resp, *expected) 6102 } 6103 } 6104 6105 func TestDNS_Compression_trimUDPResponse(t *testing.T) { 6106 t.Parallel() 6107 cfg := config.DefaultRuntimeConfig(`data_dir = "a" bind_addr = "127.0.0.1"`) 6108 6109 req, m := dns.Msg{}, dns.Msg{} 6110 trimUDPResponse(&req, &m, cfg.DNSUDPAnswerLimit) 6111 if m.Compress { 6112 t.Fatalf("compression should be off") 6113 } 6114 6115 // The trim function temporarily turns off compression, so we need to 6116 // make sure the setting gets restored properly. 6117 m.Compress = true 6118 trimUDPResponse(&req, &m, cfg.DNSUDPAnswerLimit) 6119 if !m.Compress { 6120 t.Fatalf("compression should be on") 6121 } 6122 } 6123 6124 func TestDNS_Compression_Query(t *testing.T) { 6125 t.Parallel() 6126 a := NewTestAgent(t, t.Name(), "") 6127 defer a.Shutdown() 6128 testrpc.WaitForLeader(t, a.RPC, "dc1") 6129 6130 // Register a node with a service. 6131 { 6132 args := &structs.RegisterRequest{ 6133 Datacenter: "dc1", 6134 Node: "foo", 6135 Address: "127.0.0.1", 6136 Service: &structs.NodeService{ 6137 Service: "db", 6138 Tags: []string{"master"}, 6139 Port: 12345, 6140 }, 6141 } 6142 6143 var out struct{} 6144 if err := a.RPC("Catalog.Register", args, &out); err != nil { 6145 t.Fatalf("err: %v", err) 6146 } 6147 } 6148 6149 // Register an equivalent prepared query. 6150 var id string 6151 { 6152 args := &structs.PreparedQueryRequest{ 6153 Datacenter: "dc1", 6154 Op: structs.PreparedQueryCreate, 6155 Query: &structs.PreparedQuery{ 6156 Name: "test", 6157 Service: structs.ServiceQuery{ 6158 Service: "db", 6159 }, 6160 }, 6161 } 6162 if err := a.RPC("PreparedQuery.Apply", args, &id); err != nil { 6163 t.Fatalf("err: %v", err) 6164 } 6165 } 6166 6167 // Look up the service directly and via prepared query. 6168 questions := []string{ 6169 "db.service.consul.", 6170 id + ".query.consul.", 6171 } 6172 for _, question := range questions { 6173 m := new(dns.Msg) 6174 m.SetQuestion(question, dns.TypeSRV) 6175 6176 conn, err := dns.Dial("udp", a.DNSAddr()) 6177 if err != nil { 6178 t.Fatalf("err: %v", err) 6179 } 6180 6181 // Do a manual exchange with compression on (the default). 6182 a.DNSDisableCompression(false) 6183 if err := conn.WriteMsg(m); err != nil { 6184 t.Fatalf("err: %v", err) 6185 } 6186 p := make([]byte, dns.MaxMsgSize) 6187 compressed, err := conn.Read(p) 6188 if err != nil { 6189 t.Fatalf("err: %v", err) 6190 } 6191 6192 // Disable compression and try again. 6193 a.DNSDisableCompression(true) 6194 if err := conn.WriteMsg(m); err != nil { 6195 t.Fatalf("err: %v", err) 6196 } 6197 unc, err := conn.Read(p) 6198 if err != nil { 6199 t.Fatalf("err: %v", err) 6200 } 6201 6202 // We can't see the compressed status given the DNS API, so we 6203 // just make sure the message is smaller to see if it's 6204 // respecting the flag. 6205 if compressed == 0 || unc == 0 || compressed >= unc { 6206 t.Fatalf("'%s' doesn't look compressed: %d vs. %d", question, compressed, unc) 6207 } 6208 } 6209 } 6210 6211 func TestDNS_Compression_ReverseLookup(t *testing.T) { 6212 t.Parallel() 6213 a := NewTestAgent(t, t.Name(), "") 6214 defer a.Shutdown() 6215 testrpc.WaitForLeader(t, a.RPC, "dc1") 6216 6217 // Register node. 6218 args := &structs.RegisterRequest{ 6219 Datacenter: "dc1", 6220 Node: "foo2", 6221 Address: "127.0.0.2", 6222 } 6223 var out struct{} 6224 if err := a.RPC("Catalog.Register", args, &out); err != nil { 6225 t.Fatalf("err: %v", err) 6226 } 6227 6228 m := new(dns.Msg) 6229 m.SetQuestion("2.0.0.127.in-addr.arpa.", dns.TypeANY) 6230 6231 conn, err := dns.Dial("udp", a.DNSAddr()) 6232 if err != nil { 6233 t.Fatalf("err: %v", err) 6234 } 6235 6236 // Do a manual exchange with compression on (the default). 6237 if err := conn.WriteMsg(m); err != nil { 6238 t.Fatalf("err: %v", err) 6239 } 6240 p := make([]byte, dns.MaxMsgSize) 6241 compressed, err := conn.Read(p) 6242 if err != nil { 6243 t.Fatalf("err: %v", err) 6244 } 6245 6246 // Disable compression and try again. 6247 a.DNSDisableCompression(true) 6248 if err := conn.WriteMsg(m); err != nil { 6249 t.Fatalf("err: %v", err) 6250 } 6251 unc, err := conn.Read(p) 6252 if err != nil { 6253 t.Fatalf("err: %v", err) 6254 } 6255 6256 // We can't see the compressed status given the DNS API, so we just make 6257 // sure the message is smaller to see if it's respecting the flag. 6258 if compressed == 0 || unc == 0 || compressed >= unc { 6259 t.Fatalf("doesn't look compressed: %d vs. %d", compressed, unc) 6260 } 6261 } 6262 6263 func TestDNS_Compression_Recurse(t *testing.T) { 6264 t.Parallel() 6265 recursor := makeRecursor(t, dns.Msg{ 6266 Answer: []dns.RR{dnsA("apple.com", "1.2.3.4")}, 6267 }) 6268 defer recursor.Shutdown() 6269 6270 a := NewTestAgent(t, t.Name(), ` 6271 recursors = ["`+recursor.Addr+`"] 6272 `) 6273 defer a.Shutdown() 6274 testrpc.WaitForTestAgent(t, a.RPC, "dc1") 6275 6276 m := new(dns.Msg) 6277 m.SetQuestion("apple.com.", dns.TypeANY) 6278 6279 conn, err := dns.Dial("udp", a.DNSAddr()) 6280 if err != nil { 6281 t.Fatalf("err: %v", err) 6282 } 6283 6284 // Do a manual exchange with compression on (the default). 6285 if err := conn.WriteMsg(m); err != nil { 6286 t.Fatalf("err: %v", err) 6287 } 6288 p := make([]byte, dns.MaxMsgSize) 6289 compressed, err := conn.Read(p) 6290 if err != nil { 6291 t.Fatalf("err: %v", err) 6292 } 6293 6294 // Disable compression and try again. 6295 a.DNSDisableCompression(true) 6296 if err := conn.WriteMsg(m); err != nil { 6297 t.Fatalf("err: %v", err) 6298 } 6299 unc, err := conn.Read(p) 6300 if err != nil { 6301 t.Fatalf("err: %v", err) 6302 } 6303 6304 // We can't see the compressed status given the DNS API, so we just make 6305 // sure the message is smaller to see if it's respecting the flag. 6306 if compressed == 0 || unc == 0 || compressed >= unc { 6307 t.Fatalf("doesn't look compressed: %d vs. %d", compressed, unc) 6308 } 6309 } 6310 6311 func TestDNSInvalidRegex(t *testing.T) { 6312 tests := []struct { 6313 desc string 6314 in string 6315 invalid bool 6316 }{ 6317 {"Valid Hostname", "testnode", false}, 6318 {"Valid Hostname", "test-node", false}, 6319 {"Invalid Hostname with special chars", "test#$$!node", true}, 6320 {"Invalid Hostname with special chars in the end", "testnode%^", true}, 6321 {"Whitespace", " ", true}, 6322 {"Only special chars", "./$", true}, 6323 } 6324 for _, test := range tests { 6325 t.Run(test.desc, func(t *testing.T) { 6326 if got, want := InvalidDnsRe.MatchString(test.in), test.invalid; got != want { 6327 t.Fatalf("Expected %v to return %v", test.in, want) 6328 } 6329 }) 6330 6331 } 6332 } 6333 6334 func TestDNS_formatNodeRecord(t *testing.T) { 6335 s := &DNSServer{} 6336 6337 node := &structs.Node{ 6338 Meta: map[string]string{ 6339 "key": "value", 6340 "key2": "value2", 6341 }, 6342 } 6343 6344 records, meta := s.formatNodeRecord(node, "198.18.0.1", "test.node.consul", dns.TypeA, 5*time.Minute, false, 3, false) 6345 require.Len(t, records, 1) 6346 require.Len(t, meta, 0) 6347 6348 records, meta = s.formatNodeRecord(node, "198.18.0.1", "test.node.consul", dns.TypeA, 5*time.Minute, false, 3, true) 6349 require.Len(t, records, 1) 6350 require.Len(t, meta, 2) 6351 }