forked from 0xERR0R/blocky
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelper.go
278 lines (236 loc) · 7.02 KB
/
helper.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
package helpertest
import (
"bytes"
"context"
"fmt"
"net"
"net/http"
"net/http/httptest"
"os"
"strings"
"github.com/0xERR0R/blocky/log"
"github.com/0xERR0R/blocky/model"
"github.com/miekg/dns"
"github.com/onsi/ginkgo/v2"
"github.com/onsi/gomega"
"github.com/onsi/gomega/gcustom"
"github.com/onsi/gomega/types"
)
const (
A = dns.Type(dns.TypeA)
AAAA = dns.Type(dns.TypeAAAA)
CNAME = dns.Type(dns.TypeCNAME)
HTTPS = dns.Type(dns.TypeHTTPS)
MX = dns.Type(dns.TypeMX)
PTR = dns.Type(dns.TypePTR)
SRV = dns.Type(dns.TypeSRV)
TXT = dns.Type(dns.TypeTXT)
DS = dns.Type(dns.TypeDS)
)
// GetIntPort returns a port for the current testing
// process by adding the current ginkgo parallel process to
// the base port and returning it as int.
func GetIntPort(port int) int {
return port + ginkgo.GinkgoParallelProcess()
}
// GetStringPort returns a port for the current testing
// process by adding the current ginkgo parallel process to
// the base port and returning it as string.
func GetStringPort(port int) string {
return fmt.Sprintf("%d", GetIntPort(port))
}
// GetHostPort returns a host:port string for the current testing
// process by adding the current ginkgo parallel process to
// the base port and returning it as string.
func GetHostPort(host string, port int) string {
return net.JoinHostPort(host, GetStringPort(port))
}
// TempFile creates temp file with passed data
func TempFile(data string) *os.File {
f, err := os.CreateTemp("", "prefix")
if err != nil {
log.Log().Fatal(err)
}
_, err = f.WriteString(data)
if err != nil {
log.Log().Fatal(err)
}
return f
}
// TestServer creates temp http server with passed data
func TestServer(data string) *httptest.Server {
srv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
_, err := rw.Write([]byte(data))
if err != nil {
log.Log().Fatal("can't write to buffer:", err)
}
}))
ginkgo.DeferCleanup(srv.Close)
return srv
}
// DoGetRequest performs a GET request
func DoGetRequest(ctx context.Context, url string,
fn func(w http.ResponseWriter, r *http.Request),
) (*httptest.ResponseRecorder, *bytes.Buffer) {
r, _ := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
rr := httptest.NewRecorder()
handler := http.HandlerFunc(fn)
handler.ServeHTTP(rr, r)
return rr, rr.Body
}
func ToAnswer(m *model.Response) []dns.RR {
return m.Res.Answer
}
func ToExtra(m *model.Response) []dns.RR {
return m.Res.Extra
}
func HaveNoAnswer() types.GomegaMatcher {
return gomega.WithTransform(ToAnswer, gomega.BeEmpty())
}
func HaveReason(reason string) types.GomegaMatcher {
return gcustom.MakeMatcher(func(m *model.Response) (bool, error) {
return m.Reason == reason, nil
}).WithTemplate(
"Expected:\n{{.Actual}}\n{{.To}} have reason:\n{{format .Data 1}}",
reason,
)
}
func HaveResponseType(c model.ResponseType) types.GomegaMatcher {
return gcustom.MakeMatcher(func(m *model.Response) (bool, error) {
return m.RType == c, nil
}).WithTemplate(
"Expected:\n{{.Actual}}\n{{.To}} have ResponseType:\n{{format .Data 1}}",
c.String(),
)
}
func HaveReturnCode(code int) types.GomegaMatcher {
return gcustom.MakeMatcher(func(m *model.Response) (bool, error) {
return m.Res.Rcode == code, nil
}).WithTemplate(
"Expected:\n{{.Actual}}\n{{.To}} have RCode:\n{{format .Data 1}}",
fmt.Sprintf("%d (%s)", code, dns.RcodeToString[code]),
)
}
// HaveEdnsOption checks if the given message contains an EDNS0 record with the given option code.
func HaveEdnsOption(code uint16) types.GomegaMatcher {
return gcustom.MakeMatcher(func(actual any) (bool, error) {
var opt *dns.OPT
switch msg := actual.(type) {
case *model.Response:
opt = msg.Res.IsEdns0()
case *dns.Msg:
opt = msg.IsEdns0()
}
if opt != nil {
for _, o := range opt.Option {
if o.Option() == code {
return true, nil
}
}
}
return false, nil
}).WithTemplate(
"Expected:\n{{.Actual}}\n{{.To}} have EDNS option:\n{{format .Data 1}}",
code,
)
}
func HaveTTL(matcher types.GomegaMatcher) types.GomegaMatcher {
return gomega.WithTransform(func(actual interface{}) (uint32, error) {
// Handle different types of input
var records []dns.RR
switch i := actual.(type) {
case *model.Response:
records = i.Res.Answer
case *dns.Msg:
records = i.Answer
case []dns.RR:
records = i
case dns.RR:
records = []dns.RR{i}
default:
return 0, fmt.Errorf("unsupported type for TTL matching: %T", actual)
}
// No records to match
if len(records) == 0 {
return 0, fmt.Errorf("answer must not be empty")
}
// Return TTL of the first record
// This is a reasonable approach since typically all records in a response
// have the same TTL, and we're usually testing against a specific expected value
return records[0].Header().Ttl, nil
}, matcher)
}
// BeDNSRecord returns new dns matcher
func BeDNSRecord(domain string, dnsType dns.Type, answer string) types.GomegaMatcher {
return &dnsRecordMatcher{
domain: domain,
dnsType: dnsType,
answer: answer,
}
}
type dnsRecordMatcher struct {
domain string
dnsType dns.Type
answer string
}
func (matcher *dnsRecordMatcher) matchSingle(rr dns.RR) bool {
if (rr.Header().Name != matcher.domain) ||
(dns.Type(rr.Header().Rrtype) != matcher.dnsType) {
return false
}
switch v := rr.(type) {
case *dns.A:
return v.A.String() == matcher.answer
case *dns.AAAA:
return v.AAAA.To16().Equal(net.ParseIP(matcher.answer))
case *dns.CNAME:
return v.Target == matcher.answer
case *dns.PTR:
return v.Ptr == matcher.answer
case *dns.SRV:
return fmt.Sprintf("%d %d %d %s", v.Priority, v.Weight, v.Port, v.Target) == matcher.answer
case *dns.TXT:
return strings.Join(v.Txt, " ") == matcher.answer
case *dns.MX:
return v.Mx == matcher.answer
}
return false
}
// Match checks the DNS record
func (matcher *dnsRecordMatcher) Match(actual interface{}) (success bool, err error) {
// Handle different types of input
var records []dns.RR
switch i := actual.(type) {
case *model.Response:
records = i.Res.Answer
case *dns.Msg:
records = i.Answer
case []dns.RR:
records = i
case dns.RR:
records = []dns.RR{i}
default:
return false, fmt.Errorf("unsupported type for DNS record matching: %T", actual)
}
// No records to match
if len(records) == 0 {
return false, nil
}
// Try to match any of the records
for _, rr := range records {
if match := matcher.matchSingle(rr); match {
return true, nil
}
}
return false, nil
}
// FailureMessage generates a failure message
func (matcher *dnsRecordMatcher) FailureMessage(actual interface{}) (message string) {
return fmt.Sprintf("Expected\n\t%s\n to contain\n\t domain '%s', type '%s', answer '%s'",
actual, matcher.domain, dns.TypeToString[uint16(matcher.dnsType)], matcher.answer)
}
// NegatedFailureMessage creates negated message
func (matcher *dnsRecordMatcher) NegatedFailureMessage(actual interface{}) (message string) {
return fmt.Sprintf("Expected\n\t%s\n not to contain\n\t domain '%s', type '%s', answer '%s'",
actual, matcher.domain, dns.TypeToString[uint16(matcher.dnsType)], matcher.answer)
}