File: http.go

package info (click to toggle)
wait4x 3.6.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 744 kB
  • sloc: makefile: 248; sh: 13
file content (458 lines) | stat: -rw-r--r-- 10,597 bytes parent folder | download
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
// Copyright 2019-2025 The Wait4X Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package http provides the HTTP checker for the Wait4X application.
package http

import (
	"context"
	"crypto/tls"
	"crypto/x509"
	"errors"
	"io"
	"net"
	"net/http"
	"net/url"
	"os"
	"regexp"
	"strings"
	"time"

	"github.com/antchfx/htmlquery"
	"github.com/tidwall/gjson"
	"golang.org/x/net/http2"
	"wait4x.dev/v3/checker"
)

// Option configures an HTTP.
type Option func(h *HTTP)

const (
	// DefaultConnectionTimeout is the default connection timeout duration
	DefaultConnectionTimeout = 3 * time.Second
	// DefaultInsecureSkipTLSVerify is the default insecure skip tls verify
	DefaultInsecureSkipTLSVerify = false
	// DefaultNoRedirect is the default auto redirect
	DefaultNoRedirect = false
)

// HTTP is an HTTP checker
type HTTP struct {
	address               string
	timeout               time.Duration
	expectBodyRegex       string
	expectBodyJSON        string
	expectBodyXPath       string
	expectHeader          string
	requestHeaders        http.Header
	requestBody           io.Reader
	expectStatusCode      int
	insecureSkipTLSVerify bool
	noRedirect            bool
	caFile                string
	certFile              string
	keyFile               string
	h2c                   bool
}

// New creates the HTTP checker
func New(address string, opts ...Option) checker.Checker {
	h := &HTTP{
		address:               address,
		timeout:               DefaultConnectionTimeout,
		insecureSkipTLSVerify: DefaultInsecureSkipTLSVerify,
		noRedirect:            DefaultNoRedirect,
	}

	// apply the list of options to HTTP
	for _, opt := range opts {
		opt(h)
	}

	return h
}

// WithTimeout configures a time limit for requests made by the HTTP client
func WithTimeout(timeout time.Duration) Option {
	return func(h *HTTP) {
		h.timeout = timeout
	}
}

// WithExpectBodyRegex configures response body expectation
func WithExpectBodyRegex(regex string) Option {
	return func(h *HTTP) {
		h.expectBodyRegex = regex
	}
}

// WithExpectBodyJSON configures response json expectation
func WithExpectBodyJSON(json string) Option {
	return func(h *HTTP) {
		h.expectBodyJSON = json
	}
}

// WithExpectBodyXPath configures response xpath expectation
func WithExpectBodyXPath(xpath string) Option {
	return func(h *HTTP) {
		h.expectBodyXPath = xpath
	}
}

// WithExpectHeader configures response header expectation
func WithExpectHeader(header string) Option {
	return func(h *HTTP) {
		h.expectHeader = header
	}
}

// WithRequestHeaders configures request header
func WithRequestHeaders(headers http.Header) Option {
	return func(h *HTTP) {
		h.requestHeaders = headers
	}
}

// WithRequestBody configures request body
func WithRequestBody(body io.Reader) Option {
	return func(h *HTTP) {
		h.requestBody = body
	}
}

// WithRequestHeader configures request header
func WithRequestHeader(key string, value []string) Option {
	return func(h *HTTP) {
		if h.requestHeaders == nil {
			h.requestHeaders = http.Header{}
		}
		h.requestHeaders[key] = value
	}
}

// WithExpectStatusCode configures response status code expectation
func WithExpectStatusCode(code int) Option {
	return func(h *HTTP) {
		h.expectStatusCode = code
	}
}

// WithInsecureSkipTLSVerify configures insecure skip tls verify
func WithInsecureSkipTLSVerify(insecureSkipTLSVerify bool) Option {
	return func(h *HTTP) {
		h.insecureSkipTLSVerify = insecureSkipTLSVerify
	}
}

// WithNoRedirect configures auto redirect
func WithNoRedirect(noRedirect bool) Option {
	return func(h *HTTP) {
		h.noRedirect = noRedirect
	}
}

// WithCAFile configures CA file
func WithCAFile(path string) Option {
	return func(h *HTTP) {
		h.caFile = path
	}
}

// WithCertFile configures Cert file
func WithCertFile(path string) Option {
	return func(h *HTTP) {
		h.certFile = path
	}
}

// WithKeyFile configures key file
func WithKeyFile(path string) Option {
	return func(h *HTTP) {
		h.keyFile = path
	}
}

// WithH2C enables prior-knowledge HTTP/2 over cleartext (h2c) for http:// URLs.
func WithH2C(enable bool) Option {
	return func(h *HTTP) {
		h.h2c = enable
	}
}

// Identity returns the identity of the checker
func (h *HTTP) Identity() (string, error) {
	return h.address, nil
}

// Check checks HTTP connection
func (h *HTTP) Check(ctx context.Context) (err error) {
	tlsConfig, err := h.getTLSConfig()
	if err != nil {
		return
	}

	// Base transport (also used for HTTPS and for HTTP when h2c is not applicable).
	baseTransport := &http.Transport{
		TLSClientConfig: tlsConfig,
		Proxy:           http.ProxyFromEnvironment,
	}

	transport := http.RoundTripper(baseTransport)

	// Opt-in h2c (prior-knowledge) for cleartext HTTP when:
	// - explicitly enabled,
	// - scheme is http,
	// - no proxy is configured for this URL,
	// - noRedirect is true (avoid redirect cross-scheme issues with a single transport).
	if h.h2c && h.noRedirect {
		if u, perr := url.Parse(h.address); perr == nil && strings.EqualFold(u.Scheme, "http") {
			if p, _ := http.ProxyFromEnvironment(&http.Request{URL: u}); p == nil {
				transport = &http2.Transport{
					AllowHTTP: true,
					DialTLS: func(network, addr string, _ *tls.Config) (net.Conn, error) {
						return net.DialTimeout(network, addr, h.timeout)
					},
				}
			}
		}
	}

	httpClient := &http.Client{
		Timeout:   h.timeout,
		Transport: transport,
	}

	if h.noRedirect {
		httpClient.CheckRedirect = func(_ *http.Request, _ []*http.Request) error {
			return http.ErrUseLastResponse
		}
	}

	method := http.MethodGet
	if h.requestBody != nil {
		method = http.MethodPost
	}

	req, err := http.NewRequestWithContext(ctx, method, h.address, h.requestBody)
	if err != nil {
		return err
	}

	req.Header = h.requestHeaders

	resp, err := httpClient.Do(req)
	if err != nil {
		if os.IsTimeout(err) {
			return checker.NewExpectedError(
				"timed out while making an http call", err,
				"timeout", h.timeout,
			)
		} else if checker.IsConnectionRefused(err) {
			return checker.NewExpectedError(
				"failed to establish an http connection", err,
				"address", h.address,
			)
		}

		return err
	}

	defer func(body io.ReadCloser) {
		if cerr := body.Close(); cerr != nil {
			err = cerr
		}
	}(resp.Body)

	if h.expectStatusCode != 0 {
		err := h.checkingStatusCodeExpectation(resp)
		if err != nil {
			return err
		}
	}

	if h.expectBodyRegex != "" {
		err := h.checkingBodyExpectation(resp)
		if err != nil {
			return err
		}
	}

	if h.expectBodyJSON != "" {
		err := h.checkingJSONExpectation(resp)
		if err != nil {
			return err
		}
	}

	if h.expectBodyXPath != "" {
		err := h.checkingXPathExpectation(resp)
		if err != nil {
			return err
		}
	}

	if h.expectHeader != "" {
		return h.checkingHeaderExpectation(resp)
	}

	return nil
}

// getTLSConfig prepares TLS config
func (h *HTTP) getTLSConfig() (*tls.Config, error) {
	cfg := tls.Config{
		InsecureSkipVerify: h.insecureSkipTLSVerify,
	}

	if h.insecureSkipTLSVerify {
		return &cfg, nil
	}

	// Cert and key files.
	if h.certFile != "" || h.keyFile != "" {
		cert, err := tls.LoadX509KeyPair(h.certFile, h.keyFile)
		if err != nil {
			return nil, err
		}
		cfg.Certificates = []tls.Certificate{cert}
	}

	// CA file.
	if h.caFile != "" {
		ca, err := os.ReadFile(h.caFile)
		if err != nil {
			return nil, err
		}
		certPool := x509.NewCertPool()
		if !certPool.AppendCertsFromPEM(ca) {
			return nil, errors.New("can't append the CA file")
		}
		cfg.RootCAs = certPool
	}

	return &cfg, nil
}

func (h *HTTP) checkingStatusCodeExpectation(resp *http.Response) error {
	if h.expectStatusCode != resp.StatusCode {
		return checker.NewExpectedError(
			"the status code doesn't expect", nil,
			"actual", resp.StatusCode, "expect", h.expectStatusCode,
		)
	}

	return nil
}

func (h *HTTP) checkingBodyExpectation(resp *http.Response) error {
	bodyBytes, err := io.ReadAll(resp.Body)
	if err != nil {
		return err
	}

	bodyString := string(bodyBytes)
	matched, _ := regexp.MatchString(h.expectBodyRegex, bodyString)

	if !matched {
		return checker.NewExpectedError(
			"the body doesn't expect", nil,
			"actual", h.truncateString(bodyString, 50), "expect", h.expectBodyRegex,
		)
	}

	return nil
}

func (h *HTTP) checkingJSONExpectation(resp *http.Response) error {
	bodyBytes, err := io.ReadAll(resp.Body)
	if err != nil {
		return err
	}

	bodyString := string(bodyBytes)
	value := gjson.Get(bodyString, h.expectBodyJSON)

	if !value.Exists() {
		return checker.NewExpectedError(
			"the JSON doesn't match", nil,
			"actual", h.truncateString(bodyString, 50), "expect", h.expectBodyJSON,
		)
	}

	return nil
}

func (h *HTTP) checkingXPathExpectation(resp *http.Response) error {
	bodyBytes, err := io.ReadAll(resp.Body)
	if err != nil {
		return err
	}

	bodyString := string(bodyBytes)
	doc, err := htmlquery.Parse(strings.NewReader(bodyString))
	if err != nil {
		return err
	}

	node, err := htmlquery.Query(doc, h.expectBodyXPath)
	if err != nil {
		return err
	}
	if node == nil {
		return checker.NewExpectedError(
			"the XPath doesn't match", nil,
			"actual", h.truncateString(bodyString, 50), "expect", h.expectBodyXPath,
		)
	}

	return nil
}

func (h *HTTP) checkingHeaderExpectation(resp *http.Response) error {
	// Key value. e.g. Content-Type=application/json
	expectedHeaderParsed := strings.SplitN(h.expectHeader, "=", 2)
	if len(expectedHeaderParsed) == 2 {
		headerValue := resp.Header.Get(expectedHeaderParsed[0])
		matched, _ := regexp.MatchString(expectedHeaderParsed[1], headerValue)
		if !matched {
			return checker.NewExpectedError(
				"the http header key and value doesn't expect", nil,
				"actual", headerValue, "expect", h.expectHeader,
			)
		}
	}

	// Only key.
	if _, ok := resp.Header[expectedHeaderParsed[0]]; !ok {
		return checker.NewExpectedError(
			"the http header key doesn't expect", nil,
			"actual", resp.Header, "expect", h.expectHeader,
		)
	}

	return nil
}

func (h *HTTP) truncateString(str string, num int) string {
	truncatedStr := str
	if len(str) > num {
		if num > 3 {
			num -= 3
		}
		truncatedStr = str[0:num] + "..."
	}

	return truncatedStr
}