-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
470 lines (406 loc) · 12.5 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
package main
import (
"bytes"
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"net"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
func main() {
cmd := &cobra.Command{
Use: "http-assert <URL>",
Short: "Perform HTTP request and assert received HTTP response",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
c := Client{
LogLevel: mustParseLogLevel(),
SkipSslChecks: viper.GetBool("insecure"),
Timeout: time.Duration(viper.GetInt("max-time")) * time.Second,
HostMappings: mustParseHostMappings(viper.GetStringSlice("maphost")),
}
c.Init()
m, _ := cmd.Flags().GetString("request")
b := io.Reader(http.NoBody)
if d, _ := cmd.Flags().GetString("data"); d != "" {
b = strings.NewReader(d)
}
req, err := http.NewRequestWithContext(cmd.Context(), m, args[0], b)
if err != nil {
die(91, "Cannot create request '%s %s': %s", m, args[0], err)
}
vs, _ := cmd.Flags().GetStringArray("header")
for _, v := range vs {
name, value := parseHeaderLine(v)
req.Header.Add(name, value)
}
if err := c.Do(req, parseAssertionFlags(cmd)...); err != nil {
die(93, "Cannot perform request: %s", err)
}
},
}
// Deviations from curl's --resolve:
// - use `=` to separate src and dst
// - add [:dstport]
cmd.PersistentFlags().StringArray("maphost", nil,
"Provide a custom address for a specific host and port pair; "+
"e.g. <srchostname:srcport=dsthostname[:dstport]>")
cmd.PersistentFlags().BoolP("verbose", "v", false, "Be verbose; log info messages")
cmd.PersistentFlags().BoolP("silent", "s", false, "Be silent; log errors only")
cmd.PersistentFlags().String("log-level", "",
"Set log level; possible values: debug, info (default), warn, error")
cmd.PersistentFlags().BoolP("insecure", "k", false, "Disable checking SSL certificates")
cmd.PersistentFlags().IntP("max-time", "m", 20,
"Maximum time in seconds that you allow each request to take")
cmd.Flags().StringP("request", "X", "GET", "Set method for HTTP request")
cmd.Flags().StringArrayP("header", "H", nil, "Set header for HTTP request")
cmd.Flags().StringP("data", "d", "",
"Sends the specified data in a POST request to the HTTP server")
registerAssertionFlags(cmd)
_ = viper.BindPFlag("verbose", cmd.PersistentFlags().Lookup("verbose"))
_ = viper.BindPFlag("silent", cmd.PersistentFlags().Lookup("silent"))
_ = viper.BindPFlag("log-level", cmd.PersistentFlags().Lookup("log-level"))
_ = viper.BindPFlag("insecure", cmd.PersistentFlags().Lookup("insecure"))
_ = viper.BindPFlag("max-time", cmd.PersistentFlags().Lookup("max-time"))
_ = viper.BindPFlag("maphost", cmd.PersistentFlags().Lookup("maphost"))
viper.SetEnvPrefix("HTTP_ASSERT")
viper.GetViper().SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
viper.AutomaticEnv()
if err := cmd.ExecuteContext(context.Background()); err != nil {
die(103, "%s", err)
}
}
func die(rc int, format string, args ...interface{}) {
if !strings.HasSuffix(format, "\n") {
format += "\n"
}
fmt.Fprintf(os.Stderr, "\nError: "+format, args...)
os.Exit(rc)
}
type LogLevel int
const (
LError LogLevel = iota
LWarn
LInfo
LDebug
)
func mustParseLogLevel() LogLevel {
levelStr := viper.GetString("log-level")
if levelStr == "" {
if viper.GetBool("verbose") {
return LDebug
}
if viper.GetBool("silent") {
return LError
}
return LInfo
}
res, ok := parseLogLevel(levelStr)
if !ok {
die(71, "Invalid value for --log-level flag: %q", levelStr)
}
return res
}
func parseLogLevel(s string) (LogLevel, bool) {
switch s {
case "error":
return LError, true
case "warn":
return LWarn, true
case "info":
return LInfo, true
case "debug":
return LDebug, true
default:
return 0, false
}
}
func mustParseHostMappings(vals []string) []hostMapping {
res, err := parseHostMappings(vals)
if err != nil {
die(71, "Invalid value for --maphost flag: %s", vals)
}
return res
}
func parseHostMappings(vals []string) ([]hostMapping, error) {
var res []hostMapping
for _, v := range vals {
// format: srchostname:srcport=dsthostname:dstport
i := strings.Index(v, "=")
if i <= 0 {
return nil, fmt.Errorf("value %q has no separator, =", v)
}
srchost, dsthost := v[:i], v[i+1:]
if j := strings.Index(srchost, ":"); j < 0 {
return nil, fmt.Errorf("value %q has no src port %q", v, srchost)
} else if _, err := strconv.Atoi(srchost[j+1:]); err != nil {
return nil, fmt.Errorf("value %q has invalid src port %q", v, srchost[j+1:])
} else if k := strings.Index(dsthost, ":"); k > 0 {
if _, err := strconv.Atoi(dsthost[k+1:]); err != nil {
return nil, fmt.Errorf("value %q has invalid dst port %q", v, dsthost[k+1:])
}
}
res = append(res, hostMapping{Src: srchost, Dst: dsthost})
}
return res, nil
}
func registerAssertionFlags(cmd *cobra.Command) {
cmd.Flags().Int("assert-status", 0, "Assert response status equals the provided value")
cmd.Flags().StringArray("assert-header", nil, "Assert header equals the provided regexp")
cmd.Flags().StringArray("assert-header-eq", nil, "Assert header equals the provided regexp")
cmd.Flags().StringArray("assert-header-missing", nil, "Assert header is missing")
cmd.Flags().String("assert-body", "", "Assert body equals the provided value")
cmd.Flags().String("assert-body-eq", "", "Assert body equals the provided value")
cmd.Flags().Bool("assert-body-empty", false, "Assert body is empty")
// Common shorthands
cmd.Flags().Bool("assert-ok", false, "Assert response is successful (2xx)")
cmd.Flags().String("assert-redirect", "", "Assert response redirects to the provided URL")
cmd.Flags().String("assert-redirect-eq", "", "Assert response redirects to the provided URL")
}
func parseAssertionFlags(cmd *cobra.Command) []Assertion {
var res []Assertion
if cmd.Flags().Changed("assert-ok") {
if v, _ := cmd.Flags().GetBool("assert-ok"); v {
res = append(res, AssertStatusOK())
} else {
res = append(res, AssertStatusNOK())
}
}
if cmd.Flags().Changed("assert-redirect") {
v, _ := cmd.Flags().GetString("assert-redirect")
res = append(res, AssertRedirectMatch(v))
}
if cmd.Flags().Changed("assert-redirect-eq") {
v, _ := cmd.Flags().GetString("assert-redirect-eq")
res = append(res, AssertRedirectEqual(v))
}
if cmd.Flags().Changed("assert-status") {
s, _ := cmd.Flags().GetInt("assert-status")
res = append(res, AssertStatusEqual(s))
}
if cmd.Flags().Changed("assert-header") {
vs, _ := cmd.Flags().GetStringArray("assert-header")
res = append(res, parseHeaderAssertions(vs, false)...)
}
if cmd.Flags().Changed("assert-header-eq") {
vs, _ := cmd.Flags().GetStringArray("assert-header-eq")
res = append(res, parseHeaderAssertions(vs, true)...)
}
if cmd.Flags().Changed("assert-header-missing") {
vs, _ := cmd.Flags().GetStringArray("assert-header-missing")
for _, v := range vs {
res = append(res, AssertHeaderMissing(strings.TrimSpace(v)))
}
}
if cmd.Flags().Changed("assert-body") {
v, _ := cmd.Flags().GetString("assert-body")
res = append(res, AssertBodyMatch(v))
}
if cmd.Flags().Changed("assert-body-eq") {
v, _ := cmd.Flags().GetString("assert-body-eq")
res = append(res, AssertBodyEqual(v))
}
if v, _ := cmd.Flags().GetBool("assert-body-empty"); v {
res = append(res, AssertBodyEmpty())
}
return res
}
func parseHeaderAssertions(vs []string, exactMatch bool) []Assertion {
var res []Assertion
for _, v := range vs {
name, value := parseHeaderLine(v)
if exactMatch {
if value == "" {
res = append(res, AssertHeaderPresent(name))
} else {
res = append(res, AssertHeaderEqual(name, value))
}
} else {
if value == "" {
res = append(res, AssertHeaderPresent(name))
} else {
res = append(res, AssertHeaderMatch(name, value))
}
}
}
return res
}
type Client struct {
LogLevel LogLevel
SkipSslChecks bool
Timeout time.Duration
HostMappings []hostMapping
}
func (c *Client) Init() {
// Just print the configuration
if len(c.HostMappings) > 0 {
c.logDebug("HostMappings %d:\n", len(c.HostMappings))
for i := range c.HostMappings {
c.logDebug("- %q -> %q\n", c.HostMappings[i].Src, c.HostMappings[i].Dst)
}
}
}
func (c Client) Do(req *http.Request, assertions ...Assertion) error {
if len(assertions) == 0 {
return fmt.Errorf("no assertions defined")
}
c.logInfo("[.] %s %s %s", req.Proto, req.Method, req.URL)
startedAt := time.Now()
res, err := c.getHttpClient().Do(req)
if err != nil {
var b strings.Builder
fmt.Fprintf(&b, "failed to send request:\n- %s\n", err)
c.writeHttpDetails(&b, req, nil)
return errors.New(b.String())
}
defer res.Body.Close()
c.logInfo("[:] %s %s\n", res.Proto, res.Status)
httpRes := &httpResponse{Response: res}
httpRes.BodyBytes, _ = io.ReadAll(res.Body)
var assertErrors []error
for i := range assertions {
if err := assertions[i](httpRes); err != nil {
assertErrors = append(assertErrors, err)
}
}
if len(assertErrors) > 0 {
c.logInfo("[-] FAILED %s\n\n", time.Since(startedAt))
var b strings.Builder
fmt.Fprintf(&b, "%d assertions failed:\n", len(assertErrors))
for i := range assertErrors {
fmt.Fprintf(&b, "- %s\n", assertErrors[i])
}
c.writeHttpDetails(&b, req, httpRes)
return errors.New(b.String())
}
c.logInfo("[+] PASSED %s\n\n", time.Since(startedAt))
return nil
}
func (c Client) writeHttpDetails(w io.Writer, req *http.Request, res *httpResponse) {
fmt.Fprintf(w, "\nFAILED: %s %s (%s)\n\n", req.Method, req.URL, req.Proto)
_ = req.Write(w)
_, _ = w.Write([]byte("\n\n"))
if res != nil {
res.writeTo(w, c.LogLevel >= LInfo)
_, _ = w.Write([]byte("\n\n"))
}
}
func (c Client) getHttpClient() *http.Client {
dialer := &net.Dialer{
Timeout: 10 * time.Second,
KeepAlive: 20 * time.Second,
}
tr := &http.Transport{
ForceAttemptHTTP2: false,
MaxIdleConns: 10,
IdleConnTimeout: 20 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
Proxy: http.ProxyFromEnvironment,
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
return dialer.DialContext(ctx, network, c.getDstHost(addr))
},
}
if c.SkipSslChecks {
tr.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
}
return &http.Client{
Timeout: c.Timeout,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse // Disallow redirects
},
Transport: tr,
}
}
func (c Client) getDstHost(addr string) string {
for _, r := range c.HostMappings {
if r.Matches(addr) {
return r.DstHost()
}
}
return addr
}
func (c Client) logDebug(format string, args ...interface{}) {
c.log(LDebug, format, args...)
}
func (c Client) logInfo(format string, args ...interface{}) {
c.log(LInfo, format, args...)
}
//nolint:unused
func (c Client) logWarn(format string, args ...interface{}) {
c.log(LWarn, format, args...)
}
//nolint:unused
func (c Client) logError(format string, args ...interface{}) {
c.log(LError, format, args...)
}
func (c Client) log(l LogLevel, format string, args ...interface{}) {
if l > c.LogLevel {
return
}
if !strings.HasSuffix(format, "\n") {
format += "\n"
}
fmt.Fprintf(os.Stderr, format, args...)
}
type httpResponse struct {
*http.Response
BodyBytes []byte
}
func (r httpResponse) writeTo(w io.Writer, withBody bool) {
// Ensure to close previous body
b := r.Response.Body
defer b.Close()
if withBody {
var b bytes.Buffer
croppedBytes := printPayload(&b, r.BodyBytes, 256)
if croppedBytes > 0 {
fmt.Fprintf(&b, "\n\n << Payload is cropped: %d bytes are hidden >>", croppedBytes)
}
r.Response.Body = io.NopCloser(&b)
} else {
r.Response.Body = io.NopCloser(strings.NewReader(" << Payload is omitted >>"))
}
_ = r.Response.Write(w)
}
type hostMapping struct {
// Src is the source host in the form of `hostname:port`.
Src string
// Dst is the destination host in the form of either `hostname:port` or just
// `hostname`. If just the hostname is specified without a port then the
// source port will be used.
Dst string
}
func (r hostMapping) Matches(host string) bool {
if r.Src == "" {
return false
}
if r.Src == "*" || r.Src == "*:*" {
return true
}
if strings.HasPrefix(r.Src, "*:") {
// Match by port only
return strings.HasSuffix(host, r.Src[1:])
}
return r.Src == host
}
func (r hostMapping) DstHost() string {
// Dst already has a port
if idx := strings.Index(r.Dst, ":"); idx >= 0 {
return r.Dst
}
// Use the source port
var port string
if idx := strings.Index(r.Src, ":"); idx >= 0 {
port = r.Src[idx:]
}
return r.Dst + port
}