Debian Codegraph @

caddytest/caddytest.go

raw symbols SCIP
1 package caddytest
2
3 import (
4 "bytes"
5 "context"
6 "crypto/tls"
7 "encoding/json"
8 "errors"
9 "fmt"
10 "io"
11 "io/fs"
12 "log"
13 "net"
14 "net/http"
15 "net/http/cookiejar"
16 "os"
17 "path"
18 "reflect"
19 "regexp"
20 "runtime"
21 "strings"
22 "testing"
23 "time"
24
25 "github.com/aryann/difflib"
26
27 caddycmd "github.com/caddyserver/caddy/v2/cmd"
28
29 "github.com/caddyserver/caddy/v2/caddyconfig"
30 // plug in Caddy modules here
31 _ "github.com/caddyserver/caddy/v2/modules/standard"
32 )
33
34 // Config store any configuration required to make the tests run
35 type Config struct {
36 // Port we expect caddy to listening on
37 AdminPort int
38 // Certificates we expect to be loaded before attempting to run the tests
39 Certificates []string
40 // TestRequestTimeout is the time to wait for a http request to
41 TestRequestTimeout time.Duration
42 // LoadRequestTimeout is the time to wait for the config to be loaded against the caddy server
43 LoadRequestTimeout time.Duration
44 }
45
46 // Default testing values
47 var Default = Config{
48 AdminPort: 2999, // different from what a real server also running on a developer's machine might be
49 Certificates: []string{"/caddy.localhost.crt", "/caddy.localhost.key"},
50 TestRequestTimeout: 5 * time.Second,
51 LoadRequestTimeout: 5 * time.Second,
52 }
53
54 var (
55 matchKey = regexp.MustCompile(`(/[\w\d\.]+\.key)`)
56 matchCert = regexp.MustCompile(`(/[\w\d\.]+\.crt)`)
57 )
58
59 // Tester represents an instance of a test client.
60 type Tester struct {
61 Client *http.Client
62 configLoaded bool
63 t testing.TB
64 config Config
65 }
66
67 // NewTester will create a new testing client with an attached cookie jar
68 func NewTester(t testing.TB) *Tester {
69 jar, err := cookiejar.New(nil)
70 if err != nil {
71 t.Fatalf("failed to create cookiejar: %s", err)
72 }
73
74 return &Tester{
75 Client: &http.Client{
76 Transport: CreateTestingTransport(),
77 Jar: jar,
78 Timeout: Default.TestRequestTimeout,
79 },
80 configLoaded: false,
81 t: t,
82 config: Default,
83 }
84 }
85
86 // WithDefaultOverrides this will override the default test configuration with the provided values.
87 func (tc *Tester) WithDefaultOverrides(overrides Config) *Tester {
88 if overrides.AdminPort != 0 {
89 tc.config.AdminPort = overrides.AdminPort
90 }
91 if len(overrides.Certificates) > 0 {
92 tc.config.Certificates = overrides.Certificates
93 }
94 if overrides.TestRequestTimeout != 0 {
95 tc.config.TestRequestTimeout = overrides.TestRequestTimeout
96 tc.Client.Timeout = overrides.TestRequestTimeout
97 }
98 if overrides.LoadRequestTimeout != 0 {
99 tc.config.LoadRequestTimeout = overrides.LoadRequestTimeout
100 }
101
102 return tc
103 }
104
105 type configLoadError struct {
106 Response string
107 }
108
109 func (e configLoadError) Error() string { return e.Response }
110
111 func timeElapsed(start time.Time, name string) {
112 elapsed := time.Since(start)
113 log.Printf("%s took %s", name, elapsed)
114 }
115
116 // InitServer this will configure the server with a configurion of a specific
117 // type. The configType must be either "json" or the adapter type.
118 func (tc *Tester) InitServer(rawConfig string, configType string) {
119 if err := tc.initServer(rawConfig, configType); err != nil {
120 tc.t.Logf("failed to load config: %s", err)
121 tc.t.Fail()
122 }
123 if err := tc.ensureConfigRunning(rawConfig, configType); err != nil {
124 tc.t.Logf("failed ensuring config is running: %s", err)
125 tc.t.Fail()
126 }
127 }
128
129 // InitServer this will configure the server with a configurion of a specific
130 // type. The configType must be either "json" or the adapter type.
131 func (tc *Tester) initServer(rawConfig string, configType string) error {
132 if testing.Short() {
133 tc.t.SkipNow()
134 return nil
135 }
136
137 err := validateTestPrerequisites(tc)
138 if err != nil {
139 tc.t.Skipf("skipping tests as failed integration prerequisites. %s", err)
140 return nil
141 }
142
143 tc.t.Cleanup(func() {
144 if tc.t.Failed() && tc.configLoaded {
145 res, err := http.Get(fmt.Sprintf("http://localhost:%d/config/", tc.config.AdminPort))
146 if err != nil {
147 tc.t.Log("unable to read the current config")
148 return
149 }
150 defer res.Body.Close()
151 body, _ := io.ReadAll(res.Body)
152
153 var out bytes.Buffer
154 _ = json.Indent(&out, body, "", " ")
155 tc.t.Logf("----------- failed with config -----------\n%s", out.String())
156 }
157 })
158
159 rawConfig = prependCaddyFilePath(rawConfig)
160 // normalize JSON config
161 if configType == "json" {
162 tc.t.Logf("Before: %s", rawConfig)
163 var conf any
164 if err := json.Unmarshal([]byte(rawConfig), &conf); err != nil {
165 return err
166 }
167 c, err := json.Marshal(conf)
168 if err != nil {
169 return err
170 }
171 rawConfig = string(c)
172 tc.t.Logf("After: %s", rawConfig)
173 }
174 client := &http.Client{
175 Timeout: tc.config.LoadRequestTimeout,
176 }
177 start := time.Now()
178 req, err := http.NewRequest("POST", fmt.Sprintf("http://localhost:%d/load", tc.config.AdminPort), strings.NewReader(rawConfig))
179 if err != nil {
180 tc.t.Errorf("failed to create request. %s", err)
181 return err
182 }
183
184 if configType == "json" {
185 req.Header.Add("Content-Type", "application/json")
186 } else {
187 req.Header.Add("Content-Type", "text/"+configType)
188 }
189
190 res, err := client.Do(req) //nolint:gosec // no SSRF because URL is hard-coded to localhost, and port comes from config
191 if err != nil {
192 tc.t.Errorf("unable to contact caddy server. %s", err)
193 return err
194 }
195 timeElapsed(start, "caddytest: config load time")
196
197 defer res.Body.Close()
198 body, err := io.ReadAll(res.Body)
199 if err != nil {
200 tc.t.Errorf("unable to read response. %s", err)
201 return err
202 }
203
204 if res.StatusCode != 200 {
205 return configLoadError{Response: string(body)}
206 }
207
208 tc.configLoaded = true
209 return nil
210 }
211
212 func (tc *Tester) ensureConfigRunning(rawConfig string, configType string) error {
213 expectedBytes := []byte(prependCaddyFilePath(rawConfig))
214 if configType != "json" {
215 adapter := caddyconfig.GetAdapter(configType)
216 if adapter == nil {
217 return fmt.Errorf("adapter of config type is missing: %s", configType)
218 }
219 expectedBytes, _, _ = adapter.Adapt([]byte(rawConfig), nil)
220 }
221
222 var expected any
223 err := json.Unmarshal(expectedBytes, &expected)
224 if err != nil {
225 return err
226 }
227
228 client := &http.Client{
229 Timeout: tc.config.LoadRequestTimeout,
230 }
231
232 fetchConfig := func(client *http.Client) any {
233 resp, err := client.Get(fmt.Sprintf("http://localhost:%d/config/", tc.config.AdminPort))
234 if err != nil {
235 return nil
236 }
237 defer resp.Body.Close()
238 actualBytes, err := io.ReadAll(resp.Body)
239 if err != nil {
240 return nil
241 }
242 var actual any
243 err = json.Unmarshal(actualBytes, &actual)
244 if err != nil {
245 return nil
246 }
247 return actual
248 }
249
250 for retries := 10; retries > 0; retries-- {
251 if reflect.DeepEqual(expected, fetchConfig(client)) {
252 return nil
253 }
254 time.Sleep(1 * time.Second)
255 }
256 tc.t.Errorf("POSTed configuration isn't active")
257 return errors.New("EnsureConfigRunning: POSTed configuration isn't active")
258 }
259
260 const initConfig = `{
261 admin localhost:%d
262 }
263 `
264
265 // validateTestPrerequisites ensures the certificates are available in the
266 // designated path and Caddy sub-process is running.
267 func validateTestPrerequisites(tc *Tester) error {
268 // check certificates are found
269 for _, certName := range tc.config.Certificates {
270 if _, err := os.Stat(getIntegrationDir() + certName); errors.Is(err, fs.ErrNotExist) {
271 return fmt.Errorf("caddy integration test certificates (%s) not found", certName)
272 }
273 }
274
275 if isCaddyAdminRunning(tc) != nil {
276 // setup the init config file, and set the cleanup afterwards
277 f, err := os.CreateTemp("", "")
278 if err != nil {
279 return err
280 }
281 tc.t.Cleanup(func() {
282 os.Remove(f.Name()) //nolint:gosec // false positive, filename comes from std lib, no path traversal
283 })
284 if _, err := fmt.Fprintf(f, initConfig, tc.config.AdminPort); err != nil {
285 return err
286 }
287
288 // start inprocess caddy server
289 os.Args = []string{"caddy", "run", "--config", f.Name(), "--adapter", "caddyfile"}
290 go func() {
291 caddycmd.Main()
292 }()
293
294 // wait for caddy to start serving the initial config
295 for retries := 10; retries > 0 && isCaddyAdminRunning(tc) != nil; retries-- {
296 time.Sleep(1 * time.Second)
297 }
298 }
299
300 // one more time to return the error
301 return isCaddyAdminRunning(tc)
302 }
303
304 func isCaddyAdminRunning(tc *Tester) error {
305 // assert that caddy is running
306 client := &http.Client{
307 Timeout: tc.config.LoadRequestTimeout,
308 }
309 resp, err := client.Get(fmt.Sprintf("http://localhost:%d/config/", tc.config.AdminPort))
310 if err != nil {
311 return fmt.Errorf("caddy integration test caddy server not running. Expected to be listening on localhost:%d", tc.config.AdminPort)
312 }
313 resp.Body.Close()
314
315 return nil
316 }
317
318 func getIntegrationDir() string {
319 _, filename, _, ok := runtime.Caller(1)
320 if !ok {
321 panic("unable to determine the current file path")
322 }
323
324 return path.Dir(filename)
325 }
326
327 // use the convention to replace /[certificatename].[crt|key] with the full path
328 // this helps reduce the noise in test configurations and also allow this
329 // to run in any path
330 func prependCaddyFilePath(rawConfig string) string {
331 r := matchKey.ReplaceAllString(rawConfig, getIntegrationDir()+"$1")
332 r = matchCert.ReplaceAllString(r, getIntegrationDir()+"$1")
333 return r
334 }
335
336 // CreateTestingTransport creates a testing transport that forces call dialing connections to happen locally
337 func CreateTestingTransport() *http.Transport {
338 dialer := net.Dialer{
339 Timeout: 5 * time.Second,
340 KeepAlive: 5 * time.Second,
341 DualStack: true,
342 }
343
344 dialContext := func(ctx context.Context, network, addr string) (net.Conn, error) {
345 parts := strings.Split(addr, ":")
346 destAddr := fmt.Sprintf("127.0.0.1:%s", parts[1])
347 log.Printf("caddytest: redirecting the dialer from %s to %s", addr, destAddr)
348 return dialer.DialContext(ctx, network, destAddr)
349 }
350
351 return &http.Transport{
352 Proxy: http.ProxyFromEnvironment,
353 DialContext: dialContext,
354 ForceAttemptHTTP2: true,
355 MaxIdleConns: 100,
356 IdleConnTimeout: 90 * time.Second,
357 TLSHandshakeTimeout: 5 * time.Second,
358 ExpectContinueTimeout: 1 * time.Second,
359 TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, //nolint:gosec
360 }
361 }
362
363 // AssertLoadError will load a config and expect an error
364 func AssertLoadError(t *testing.T, rawConfig string, configType string, expectedError string) {
365 t.Helper()
366
367 tc := NewTester(t)
368
369 err := tc.initServer(rawConfig, configType)
370 if !strings.Contains(err.Error(), expectedError) {
371 t.Errorf("expected error \"%s\" but got \"%s\"", expectedError, err.Error())
372 }
373 }
374
375 // AssertRedirect makes a request and asserts the redirection happens
376 func (tc *Tester) AssertRedirect(requestURI string, expectedToLocation string, expectedStatusCode int) *http.Response {
377 tc.t.Helper()
378
379 redirectPolicyFunc := func(req *http.Request, via []*http.Request) error {
380 return http.ErrUseLastResponse
381 }
382
383 // using the existing client, we override the check redirect policy for this test
384 old := tc.Client.CheckRedirect
385 tc.Client.CheckRedirect = redirectPolicyFunc
386 defer func() { tc.Client.CheckRedirect = old }()
387
388 resp, err := tc.Client.Get(requestURI)
389 if err != nil {
390 tc.t.Errorf("failed to call server %s", err)
391 return nil
392 }
393
394 if expectedStatusCode != resp.StatusCode {
395 tc.t.Errorf("requesting \"%s\" expected status code: %d but got %d", requestURI, expectedStatusCode, resp.StatusCode)
396 }
397
398 loc, err := resp.Location()
399 if err != nil {
400 tc.t.Errorf("requesting \"%s\" expected location: \"%s\" but got error: %s", requestURI, expectedToLocation, err)
401 }
402 if loc == nil && expectedToLocation != "" {
403 tc.t.Errorf("requesting \"%s\" expected a Location header, but didn't get one", requestURI)
404 }
405 if loc != nil {
406 if expectedToLocation != loc.String() {
407 tc.t.Errorf("requesting \"%s\" expected location: \"%s\" but got \"%s\"", requestURI, expectedToLocation, loc.String())
408 }
409 }
410
411 return resp
412 }
413
414 // CompareAdapt adapts a config and then compares it against an expected result
415 func CompareAdapt(t testing.TB, filename, rawConfig string, adapterName string, expectedResponse string) bool {
416 t.Helper()
417
418 cfgAdapter := caddyconfig.GetAdapter(adapterName)
419 if cfgAdapter == nil {
420 t.Logf("unrecognized config adapter '%s'", adapterName)
421 return false
422 }
423
424 options := make(map[string]any)
425
426 result, warnings, err := cfgAdapter.Adapt([]byte(rawConfig), options)
427 if err != nil {
428 t.Logf("adapting config using %s adapter: %v", adapterName, err)
429 return false
430 }
431
432 // prettify results to keep tests human-manageable
433 var prettyBuf bytes.Buffer
434 err = json.Indent(&prettyBuf, result, "", "\t")
435 if err != nil {
436 return false
437 }
438 result = prettyBuf.Bytes()
439
440 if len(warnings) > 0 {
441 for _, w := range warnings {
442 t.Logf("warning: %s:%d: %s: %s", filename, w.Line, w.Directive, w.Message)
443 }
444 }
445
446 diff := difflib.Diff(
447 strings.Split(expectedResponse, "\n"),
448 strings.Split(string(result), "\n"))
449
450 // scan for failure
451 failed := false
452 for _, d := range diff {
453 if d.Delta != difflib.Common {
454 failed = true
455 break
456 }
457 }
458
459 if failed {
460 for _, d := range diff {
461 switch d.Delta {
462 case difflib.Common:
463 fmt.Printf(" %s\n", d.Payload)
464 case difflib.LeftOnly:
465 fmt.Printf(" - %s\n", d.Payload)
466 case difflib.RightOnly:
467 fmt.Printf(" + %s\n", d.Payload)
468 }
469 }
470 return false
471 }
472 return true
473 }
474
475 // AssertAdapt adapts a config and then tests it against an expected result
476 func AssertAdapt(t testing.TB, rawConfig string, adapterName string, expectedResponse string) {
477 t.Helper()
478
479 ok := CompareAdapt(t, "Caddyfile", rawConfig, adapterName, expectedResponse)
480 if !ok {
481 t.Fail()
482 }
483 }
484
485 // Generic request functions
486
487 func applyHeaders(t testing.TB, req *http.Request, requestHeaders []string) {
488 requestContentType := ""
489 for _, requestHeader := range requestHeaders {
490 arr := strings.SplitAfterN(requestHeader, ":", 2)
491 k := strings.TrimRight(arr[0], ":")
492 v := strings.TrimSpace(arr[1])
493 if k == "Content-Type" {
494 requestContentType = v
495 }
496 t.Logf("Request header: %s => %s", k, v)
497 req.Header.Set(k, v)
498 }
499
500 if requestContentType == "" {
501 t.Logf("Content-Type header not provided")
502 }
503 }
504
505 // AssertResponseCode will execute the request and verify the status code, returns a response for additional assertions
506 func (tc *Tester) AssertResponseCode(req *http.Request, expectedStatusCode int) *http.Response {
507 tc.t.Helper()
508
509 resp, err := tc.Client.Do(req) //nolint:gosec // no SSRFs demonstrated
510 if err != nil {
511 tc.t.Fatalf("failed to call server %s", err)
512 }
513
514 if expectedStatusCode != resp.StatusCode {
515 tc.t.Errorf("requesting \"%s\" expected status code: %d but got %d", req.URL.RequestURI(), expectedStatusCode, resp.StatusCode)
516 }
517
518 return resp
519 }
520
521 // AssertResponse requests a URI and asserts the status code and body.
522 func (tc *Tester) AssertResponse(req *http.Request, expectedStatusCode int, expectedBody string) (*http.Response, string) {
523 tc.t.Helper()
524
525 resp := tc.AssertResponseCode(req, expectedStatusCode)
526
527 defer resp.Body.Close()
528 bytes, err := io.ReadAll(resp.Body)
529 if err != nil {
530 tc.t.Fatalf("unable to read the response body %s", err)
531 }
532
533 body := string(bytes)
534
535 if body != expectedBody {
536 tc.t.Errorf("requesting \"%s\" expected response body \"%s\" but got \"%s\"", req.RequestURI, expectedBody, body)
537 }
538
539 return resp, body
540 }
541
542 // Verb specific test functions
543
544 // AssertGetResponse requests a URI with GET and expects a status code and body text.
545 func (tc *Tester) AssertGetResponse(requestURI string, expectedStatusCode int, expectedBody string) (*http.Response, string) {
546 tc.t.Helper()
547
548 req, err := http.NewRequest("GET", requestURI, nil)
549 if err != nil {
550 tc.t.Fatalf("unable to create request %s", err)
551 }
552
553 return tc.AssertResponse(req, expectedStatusCode, expectedBody)
554 }
555
556 // AssertDeleteResponse requests a URI with DELETE and expects a status code and body text.
557 func (tc *Tester) AssertDeleteResponse(requestURI string, expectedStatusCode int, expectedBody string) (*http.Response, string) {
558 tc.t.Helper()
559
560 req, err := http.NewRequest("DELETE", requestURI, nil)
561 if err != nil {
562 tc.t.Fatalf("unable to create request %s", err)
563 }
564
565 return tc.AssertResponse(req, expectedStatusCode, expectedBody)
566 }
567
568 // AssertPostResponseBody requests a URI with POST and asserts the response code and body.
569 func (tc *Tester) AssertPostResponseBody(requestURI string, requestHeaders []string, requestBody *bytes.Buffer, expectedStatusCode int, expectedBody string) (*http.Response, string) {
570 tc.t.Helper()
571
572 req, err := http.NewRequest("POST", requestURI, requestBody)
573 if err != nil {
574 tc.t.Errorf("failed to create request %s", err)
575 return nil, ""
576 }
577
578 applyHeaders(tc.t, req, requestHeaders)
579
580 return tc.AssertResponse(req, expectedStatusCode, expectedBody)
581 }
582
583 // AssertPutResponseBody requests a URI with PUT and asserts the response code and body.
584 func (tc *Tester) AssertPutResponseBody(requestURI string, requestHeaders []string, requestBody *bytes.Buffer, expectedStatusCode int, expectedBody string) (*http.Response, string) {
585 tc.t.Helper()
586
587 req, err := http.NewRequest("PUT", requestURI, requestBody)
588 if err != nil {
589 tc.t.Errorf("failed to create request %s", err)
590 return nil, ""
591 }
592
593 applyHeaders(tc.t, req, requestHeaders)
594
595 return tc.AssertResponse(req, expectedStatusCode, expectedBody)
596 }
597
598 // AssertPatchResponseBody requests a URI with PATCH and asserts the response code and body.
599 func (tc *Tester) AssertPatchResponseBody(requestURI string, requestHeaders []string, requestBody *bytes.Buffer, expectedStatusCode int, expectedBody string) (*http.Response, string) {
600 tc.t.Helper()
601
602 req, err := http.NewRequest("PATCH", requestURI, requestBody)
603 if err != nil {
604 tc.t.Errorf("failed to create request %s", err)
605 return nil, ""
606 }
607
608 applyHeaders(tc.t, req, requestHeaders)
609
610 return tc.AssertResponse(req, expectedStatusCode, expectedBody)
611 }