forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 1
/
dns.go
232 lines (189 loc) · 5.38 KB
/
dns.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
package test
import (
"context"
"fmt"
"net"
"reflect"
"regexp"
"strings"
"time"
"sync"
"github.com/miekg/dns"
)
var (
muDefaultResolver sync.RWMutex
DomainsToAddresses = map[string][]string{
"host1.": {"127.0.0.1"},
"host2.": {"127.0.0.1"},
"host3.": {"127.0.0.1"},
}
DomainsToIgnore = []string{
"redis.",
"tyk-redis.",
"mongo.", // For dashboard integration tests
"tyk-mongo.",
}
)
type dnsMockHandler struct {
domainsToAddresses map[string][]string
domainsToErrors map[string]int
muDomainsToAddresses sync.RWMutex
}
func (d *dnsMockHandler) ServeDNS(w dns.ResponseWriter, r *dns.Msg) {
msg := dns.Msg{}
msg.SetReply(r)
switch r.Question[0].Qtype {
case dns.TypeA:
msg.Authoritative = true
domain := msg.Question[0].Name
d.muDomainsToAddresses.RLock()
defer d.muDomainsToAddresses.RUnlock()
if rcode, ok := d.domainsToErrors[domain]; ok {
m := new(dns.Msg)
m.SetRcode(r, rcode)
w.WriteMsg(m)
return
}
for _, ignore := range DomainsToIgnore {
if strings.HasPrefix(domain, ignore) {
resolver := &net.Resolver{}
ipAddrs, err := resolver.LookupIPAddr(context.Background(), domain)
if err != nil {
m := new(dns.Msg)
m.SetRcode(r, dns.RcodeServerFailure)
w.WriteMsg(m)
return
}
msg.Answer = append(msg.Answer, &dns.A{
Hdr: dns.RR_Header{Name: domain, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 60},
A: ipAddrs[0].IP,
})
w.WriteMsg(&msg)
return
}
}
var addresses []string
for d, ips := range d.domainsToAddresses {
if strings.HasPrefix(domain, d) {
addresses = ips
}
}
if len(addresses) == 0 {
// ^ start of line
// localhost\. match literally
// ()* match between 0 and unlimited times
// [[:alnum:]]+\. match single character in [a-zA-Z0-9] minimum one time and ending in . literally
reg := regexp.MustCompile(`^localhost\.([[:alnum:]]+\.)*`)
if matched := reg.MatchString(domain); !matched {
panic(fmt.Sprintf("domain not mocked: %s", domain))
}
addresses = []string{"127.0.0.1"}
}
for _, addr := range addresses {
msg.Answer = append(msg.Answer, &dns.A{
Hdr: dns.RR_Header{Name: domain, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 60},
A: net.ParseIP(addr),
})
}
}
w.WriteMsg(&msg)
}
type DnsMockHandle struct {
id string
mockServer *dns.Server
ShutdownDnsMock func() error
}
func (h *DnsMockHandle) PushDomains(domainsMap map[string][]string, domainsErrorMap map[string]int) func() {
handler := h.mockServer.Handler.(*dnsMockHandler)
handler.muDomainsToAddresses.Lock()
defer handler.muDomainsToAddresses.Unlock()
dta := handler.domainsToAddresses
dte := handler.domainsToErrors
prevDta := map[string][]string{}
prevDte := map[string]int{}
for key, value := range dta {
prevDta[key] = value
}
for key, value := range dte {
prevDte[key] = value
}
pullDomainsFunc := func() {
handler := h.mockServer.Handler.(*dnsMockHandler)
handler.muDomainsToAddresses.Lock()
defer handler.muDomainsToAddresses.Unlock()
handler.domainsToAddresses = prevDta
handler.domainsToErrors = prevDte
}
for key, ips := range domainsMap {
addr, ok := dta[key]
if !ok {
dta[key] = ips
} else {
dta[key] = append(addr, ips...)
}
}
for key, rCode := range domainsErrorMap {
dte[key] = rCode
}
return pullDomainsFunc
}
// InitDNSMock initializes dns server on udp:0 address and replaces net.DefaultResolver in order
// to route all dns queries within tests to this server.
// InitDNSMock returns handle, which can be used to add/remove dns query mock responses or initialization error.
func InitDNSMock(domainsMap map[string][]string, domainsErrorMap map[string]int) (*DnsMockHandle, error) {
addr, _ := net.ResolveUDPAddr("udp", ":0")
conn, err := net.ListenUDP("udp", addr)
if err != nil {
return &DnsMockHandle{}, err
}
startResultChannel := make(chan error)
started := func() {
startResultChannel <- nil
}
mockServer := &dns.Server{PacketConn: conn, NotifyStartedFunc: started}
handle := &DnsMockHandle{id: time.Now().String(), mockServer: mockServer}
dnsMux := &dnsMockHandler{muDomainsToAddresses: sync.RWMutex{}}
if domainsMap != nil {
dnsMux.domainsToAddresses = domainsMap
} else {
dnsMux.domainsToAddresses = DomainsToAddresses
}
if domainsErrorMap != nil {
dnsMux.domainsToErrors = domainsErrorMap
}
mockServer.Handler = dnsMux
go func() {
startResultChannel <- mockServer.ActivateAndServe()
}()
err = <-startResultChannel
if err != nil {
close(startResultChannel)
return handle, err
}
muDefaultResolver.RLock()
defaultResolver := net.DefaultResolver
muDefaultResolver.RUnlock()
mockResolver := &net.Resolver{
PreferGo: true,
Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
d := net.Dialer{}
//Use write lock to prevent unsafe d.DialContext update of net.DefaultResolver
muDefaultResolver.Lock()
defer muDefaultResolver.Unlock()
return d.DialContext(ctx, network, mockServer.PacketConn.LocalAddr().String())
},
}
muDefaultResolver.Lock()
net.DefaultResolver = mockResolver
muDefaultResolver.Unlock()
handle.ShutdownDnsMock = func() error {
muDefaultResolver.Lock()
net.DefaultResolver = defaultResolver
muDefaultResolver.Unlock()
return mockServer.Shutdown()
}
return handle, nil
}
func IsDnsRecordsAddrsEqualsTo(itemAddrs, addrs []string) bool {
return reflect.DeepEqual(itemAddrs, addrs)
}