repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/caddyconfig/caddyfile/importargs.go
caddyconfig/caddyfile/importargs.go
// Copyright 2015 Matthew Holt and The Caddy 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 caddyfile import ( "regexp" "strconv" "strings" "go.uber.org/zap" "github.com/caddyserver/caddy/v2" ) // parseVariadic determines if the token is a variadic placeholder, // and if so, determines the index range (start/end) of args to use. // Returns a boolean signaling whether a variadic placeholder was found, // and the start and end indices. func parseVariadic(token Token, argCount int) (bool, int, int) { if !strings.HasPrefix(token.Text, "{args[") { return false, 0, 0 } if !strings.HasSuffix(token.Text, "]}") { return false, 0, 0 } argRange := strings.TrimSuffix(strings.TrimPrefix(token.Text, "{args["), "]}") if argRange == "" { caddy.Log().Named("caddyfile").Warn( "Placeholder "+token.Text+" cannot have an empty index", zap.String("file", token.File+":"+strconv.Itoa(token.Line)), zap.Strings("import_chain", token.imports)) return false, 0, 0 } start, end, found := strings.Cut(argRange, ":") // If no ":" delimiter is found, this is not a variadic. // The replacer will pick this up. if !found { return false, 0, 0 } // A valid token may contain several placeholders, and // they may be separated by ":". It's not variadic. // https://github.com/caddyserver/caddy/issues/5716 if strings.Contains(start, "}") || strings.Contains(end, "{") { return false, 0, 0 } var ( startIndex = 0 endIndex = argCount err error ) if start != "" { startIndex, err = strconv.Atoi(start) if err != nil { caddy.Log().Named("caddyfile").Warn( "Variadic placeholder "+token.Text+" has an invalid start index", zap.String("file", token.File+":"+strconv.Itoa(token.Line)), zap.Strings("import_chain", token.imports)) return false, 0, 0 } } if end != "" { endIndex, err = strconv.Atoi(end) if err != nil { caddy.Log().Named("caddyfile").Warn( "Variadic placeholder "+token.Text+" has an invalid end index", zap.String("file", token.File+":"+strconv.Itoa(token.Line)), zap.Strings("import_chain", token.imports)) return false, 0, 0 } } // bound check if startIndex < 0 || startIndex > endIndex || endIndex > argCount { caddy.Log().Named("caddyfile").Warn( "Variadic placeholder "+token.Text+" indices are out of bounds, only "+strconv.Itoa(argCount)+" argument(s) exist", zap.String("file", token.File+":"+strconv.Itoa(token.Line)), zap.Strings("import_chain", token.imports)) return false, 0, 0 } return true, startIndex, endIndex } // makeArgsReplacer prepares a Replacer which can replace // non-variadic args placeholders in imported tokens. func makeArgsReplacer(args []string) *caddy.Replacer { repl := caddy.NewEmptyReplacer() repl.Map(func(key string) (any, bool) { // TODO: Remove the deprecated {args.*} placeholder // support at some point in the future if matches := argsRegexpIndexDeprecated.FindStringSubmatch(key); len(matches) > 0 { // What's matched may be a substring of the key if matches[0] != key { return nil, false } value, err := strconv.Atoi(matches[1]) if err != nil { caddy.Log().Named("caddyfile").Warn( "Placeholder {args." + matches[1] + "} has an invalid index") return nil, false } if value >= len(args) { caddy.Log().Named("caddyfile").Warn( "Placeholder {args." + matches[1] + "} index is out of bounds, only " + strconv.Itoa(len(args)) + " argument(s) exist") return nil, false } caddy.Log().Named("caddyfile").Warn( "Placeholder {args." + matches[1] + "} deprecated, use {args[" + matches[1] + "]} instead") return args[value], true } // Handle args[*] form if matches := argsRegexpIndex.FindStringSubmatch(key); len(matches) > 0 { // What's matched may be a substring of the key if matches[0] != key { return nil, false } if strings.Contains(matches[1], ":") { caddy.Log().Named("caddyfile").Warn( "Variadic placeholder {args[" + matches[1] + "]} must be a token on its own") return nil, false } value, err := strconv.Atoi(matches[1]) if err != nil { caddy.Log().Named("caddyfile").Warn( "Placeholder {args[" + matches[1] + "]} has an invalid index") return nil, false } if value >= len(args) { caddy.Log().Named("caddyfile").Warn( "Placeholder {args[" + matches[1] + "]} index is out of bounds, only " + strconv.Itoa(len(args)) + " argument(s) exist") return nil, false } return args[value], true } // Not an args placeholder, ignore return nil, false }) return repl } var ( argsRegexpIndexDeprecated = regexp.MustCompile(`args\.(.+)`) argsRegexpIndex = regexp.MustCompile(`args\[(.+)]`) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/caddytest/caddytest_test.go
caddytest/caddytest_test.go
package caddytest import ( "net/http" "strings" "testing" ) func TestReplaceCertificatePaths(t *testing.T) { rawConfig := `a.caddy.localhost:9443 { tls /caddy.localhost.crt /caddy.localhost.key { } redir / https://b.caddy.localhost:9443/version 301 respond /version 200 { body "hello from a.caddy.localhost" } }` r := prependCaddyFilePath(rawConfig) if !strings.Contains(r, getIntegrationDir()+"/caddy.localhost.crt") { t.Error("expected the /caddy.localhost.crt to be expanded to include the full path") } if !strings.Contains(r, getIntegrationDir()+"/caddy.localhost.key") { t.Error("expected the /caddy.localhost.crt to be expanded to include the full path") } if !strings.Contains(r, "https://b.caddy.localhost:9443/version") { t.Error("expected redirect uri to be unchanged") } } func TestLoadUnorderedJSON(t *testing.T) { tester := NewTester(t) tester.InitServer(` { "logging": { "logs": { "default": { "level": "DEBUG", "writer": { "output": "stdout" } }, "sStdOutLogs": { "level": "DEBUG", "writer": { "output": "stdout" }, "include": [ "http.*", "admin.*" ] }, "sFileLogs": { "level": "DEBUG", "writer": { "output": "stdout" }, "include": [ "http.*", "admin.*" ] } } }, "admin": { "listen": "localhost:2999" }, "apps": { "pki": { "certificate_authorities" : { "local" : { "install_trust": false } } }, "http": { "http_port": 9080, "https_port": 9443, "servers": { "s_server": { "listen": [ ":9080" ], "routes": [ { "handle": [ { "handler": "static_response", "body": "Hello" } ] }, { "match": [ { "host": [ "localhost", "127.0.0.1" ] } ] } ], "logs": { "default_logger_name": "sStdOutLogs", "logger_names": { "localhost": "sStdOutLogs", "127.0.0.1": "sFileLogs" } } } } } } } `, "json") req, err := http.NewRequest(http.MethodGet, "http://localhost:9080/", nil) if err != nil { t.Fail() return } tester.AssertResponseCode(req, 200) }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/caddytest/caddytest.go
caddytest/caddytest.go
package caddytest import ( "bytes" "context" "crypto/tls" "encoding/json" "errors" "fmt" "io" "io/fs" "log" "net" "net/http" "net/http/cookiejar" "os" "path" "reflect" "regexp" "runtime" "strings" "testing" "time" "github.com/aryann/difflib" caddycmd "github.com/caddyserver/caddy/v2/cmd" "github.com/caddyserver/caddy/v2/caddyconfig" // plug in Caddy modules here _ "github.com/caddyserver/caddy/v2/modules/standard" ) // Config store any configuration required to make the tests run type Config struct { // Port we expect caddy to listening on AdminPort int // Certificates we expect to be loaded before attempting to run the tests Certificates []string // TestRequestTimeout is the time to wait for a http request to TestRequestTimeout time.Duration // LoadRequestTimeout is the time to wait for the config to be loaded against the caddy server LoadRequestTimeout time.Duration } // Default testing values var Default = Config{ AdminPort: 2999, // different from what a real server also running on a developer's machine might be Certificates: []string{"/caddy.localhost.crt", "/caddy.localhost.key"}, TestRequestTimeout: 5 * time.Second, LoadRequestTimeout: 5 * time.Second, } var ( matchKey = regexp.MustCompile(`(/[\w\d\.]+\.key)`) matchCert = regexp.MustCompile(`(/[\w\d\.]+\.crt)`) ) // Tester represents an instance of a test client. type Tester struct { Client *http.Client configLoaded bool t testing.TB config Config } // NewTester will create a new testing client with an attached cookie jar func NewTester(t testing.TB) *Tester { jar, err := cookiejar.New(nil) if err != nil { t.Fatalf("failed to create cookiejar: %s", err) } return &Tester{ Client: &http.Client{ Transport: CreateTestingTransport(), Jar: jar, Timeout: Default.TestRequestTimeout, }, configLoaded: false, t: t, config: Default, } } // WithDefaultOverrides this will override the default test configuration with the provided values. func (tc *Tester) WithDefaultOverrides(overrides Config) *Tester { if overrides.AdminPort != 0 { tc.config.AdminPort = overrides.AdminPort } if len(overrides.Certificates) > 0 { tc.config.Certificates = overrides.Certificates } if overrides.TestRequestTimeout != 0 { tc.config.TestRequestTimeout = overrides.TestRequestTimeout tc.Client.Timeout = overrides.TestRequestTimeout } if overrides.LoadRequestTimeout != 0 { tc.config.LoadRequestTimeout = overrides.LoadRequestTimeout } return tc } type configLoadError struct { Response string } func (e configLoadError) Error() string { return e.Response } func timeElapsed(start time.Time, name string) { elapsed := time.Since(start) log.Printf("%s took %s", name, elapsed) } // InitServer this will configure the server with a configurion of a specific // type. The configType must be either "json" or the adapter type. func (tc *Tester) InitServer(rawConfig string, configType string) { if err := tc.initServer(rawConfig, configType); err != nil { tc.t.Logf("failed to load config: %s", err) tc.t.Fail() } if err := tc.ensureConfigRunning(rawConfig, configType); err != nil { tc.t.Logf("failed ensuring config is running: %s", err) tc.t.Fail() } } // InitServer this will configure the server with a configurion of a specific // type. The configType must be either "json" or the adapter type. func (tc *Tester) initServer(rawConfig string, configType string) error { if testing.Short() { tc.t.SkipNow() return nil } err := validateTestPrerequisites(tc) if err != nil { tc.t.Skipf("skipping tests as failed integration prerequisites. %s", err) return nil } tc.t.Cleanup(func() { if tc.t.Failed() && tc.configLoaded { res, err := http.Get(fmt.Sprintf("http://localhost:%d/config/", tc.config.AdminPort)) if err != nil { tc.t.Log("unable to read the current config") return } defer res.Body.Close() body, _ := io.ReadAll(res.Body) var out bytes.Buffer _ = json.Indent(&out, body, "", " ") tc.t.Logf("----------- failed with config -----------\n%s", out.String()) } }) rawConfig = prependCaddyFilePath(rawConfig) // normalize JSON config if configType == "json" { tc.t.Logf("Before: %s", rawConfig) var conf any if err := json.Unmarshal([]byte(rawConfig), &conf); err != nil { return err } c, err := json.Marshal(conf) if err != nil { return err } rawConfig = string(c) tc.t.Logf("After: %s", rawConfig) } client := &http.Client{ Timeout: tc.config.LoadRequestTimeout, } start := time.Now() req, err := http.NewRequest("POST", fmt.Sprintf("http://localhost:%d/load", tc.config.AdminPort), strings.NewReader(rawConfig)) if err != nil { tc.t.Errorf("failed to create request. %s", err) return err } if configType == "json" { req.Header.Add("Content-Type", "application/json") } else { req.Header.Add("Content-Type", "text/"+configType) } res, err := client.Do(req) if err != nil { tc.t.Errorf("unable to contact caddy server. %s", err) return err } timeElapsed(start, "caddytest: config load time") defer res.Body.Close() body, err := io.ReadAll(res.Body) if err != nil { tc.t.Errorf("unable to read response. %s", err) return err } if res.StatusCode != 200 { return configLoadError{Response: string(body)} } tc.configLoaded = true return nil } func (tc *Tester) ensureConfigRunning(rawConfig string, configType string) error { expectedBytes := []byte(prependCaddyFilePath(rawConfig)) if configType != "json" { adapter := caddyconfig.GetAdapter(configType) if adapter == nil { return fmt.Errorf("adapter of config type is missing: %s", configType) } expectedBytes, _, _ = adapter.Adapt([]byte(rawConfig), nil) } var expected any err := json.Unmarshal(expectedBytes, &expected) if err != nil { return err } client := &http.Client{ Timeout: tc.config.LoadRequestTimeout, } fetchConfig := func(client *http.Client) any { resp, err := client.Get(fmt.Sprintf("http://localhost:%d/config/", tc.config.AdminPort)) if err != nil { return nil } defer resp.Body.Close() actualBytes, err := io.ReadAll(resp.Body) if err != nil { return nil } var actual any err = json.Unmarshal(actualBytes, &actual) if err != nil { return nil } return actual } for retries := 10; retries > 0; retries-- { if reflect.DeepEqual(expected, fetchConfig(client)) { return nil } time.Sleep(1 * time.Second) } tc.t.Errorf("POSTed configuration isn't active") return errors.New("EnsureConfigRunning: POSTed configuration isn't active") } const initConfig = `{ admin localhost:%d } ` // validateTestPrerequisites ensures the certificates are available in the // designated path and Caddy sub-process is running. func validateTestPrerequisites(tc *Tester) error { // check certificates are found for _, certName := range tc.config.Certificates { if _, err := os.Stat(getIntegrationDir() + certName); errors.Is(err, fs.ErrNotExist) { return fmt.Errorf("caddy integration test certificates (%s) not found", certName) } } if isCaddyAdminRunning(tc) != nil { // setup the init config file, and set the cleanup afterwards f, err := os.CreateTemp("", "") if err != nil { return err } tc.t.Cleanup(func() { os.Remove(f.Name()) }) if _, err := fmt.Fprintf(f, initConfig, tc.config.AdminPort); err != nil { return err } // start inprocess caddy server os.Args = []string{"caddy", "run", "--config", f.Name(), "--adapter", "caddyfile"} go func() { caddycmd.Main() }() // wait for caddy to start serving the initial config for retries := 10; retries > 0 && isCaddyAdminRunning(tc) != nil; retries-- { time.Sleep(1 * time.Second) } } // one more time to return the error return isCaddyAdminRunning(tc) } func isCaddyAdminRunning(tc *Tester) error { // assert that caddy is running client := &http.Client{ Timeout: tc.config.LoadRequestTimeout, } resp, err := client.Get(fmt.Sprintf("http://localhost:%d/config/", tc.config.AdminPort)) if err != nil { return fmt.Errorf("caddy integration test caddy server not running. Expected to be listening on localhost:%d", tc.config.AdminPort) } resp.Body.Close() return nil } func getIntegrationDir() string { _, filename, _, ok := runtime.Caller(1) if !ok { panic("unable to determine the current file path") } return path.Dir(filename) } // use the convention to replace /[certificatename].[crt|key] with the full path // this helps reduce the noise in test configurations and also allow this // to run in any path func prependCaddyFilePath(rawConfig string) string { r := matchKey.ReplaceAllString(rawConfig, getIntegrationDir()+"$1") r = matchCert.ReplaceAllString(r, getIntegrationDir()+"$1") return r } // CreateTestingTransport creates a testing transport that forces call dialing connections to happen locally func CreateTestingTransport() *http.Transport { dialer := net.Dialer{ Timeout: 5 * time.Second, KeepAlive: 5 * time.Second, DualStack: true, } dialContext := func(ctx context.Context, network, addr string) (net.Conn, error) { parts := strings.Split(addr, ":") destAddr := fmt.Sprintf("127.0.0.1:%s", parts[1]) log.Printf("caddytest: redirecting the dialer from %s to %s", addr, destAddr) return dialer.DialContext(ctx, network, destAddr) } return &http.Transport{ Proxy: http.ProxyFromEnvironment, DialContext: dialContext, ForceAttemptHTTP2: true, MaxIdleConns: 100, IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 5 * time.Second, ExpectContinueTimeout: 1 * time.Second, TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, //nolint:gosec } } // AssertLoadError will load a config and expect an error func AssertLoadError(t *testing.T, rawConfig string, configType string, expectedError string) { t.Helper() tc := NewTester(t) err := tc.initServer(rawConfig, configType) if !strings.Contains(err.Error(), expectedError) { t.Errorf("expected error \"%s\" but got \"%s\"", expectedError, err.Error()) } } // AssertRedirect makes a request and asserts the redirection happens func (tc *Tester) AssertRedirect(requestURI string, expectedToLocation string, expectedStatusCode int) *http.Response { tc.t.Helper() redirectPolicyFunc := func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse } // using the existing client, we override the check redirect policy for this test old := tc.Client.CheckRedirect tc.Client.CheckRedirect = redirectPolicyFunc defer func() { tc.Client.CheckRedirect = old }() resp, err := tc.Client.Get(requestURI) if err != nil { tc.t.Errorf("failed to call server %s", err) return nil } if expectedStatusCode != resp.StatusCode { tc.t.Errorf("requesting \"%s\" expected status code: %d but got %d", requestURI, expectedStatusCode, resp.StatusCode) } loc, err := resp.Location() if err != nil { tc.t.Errorf("requesting \"%s\" expected location: \"%s\" but got error: %s", requestURI, expectedToLocation, err) } if loc == nil && expectedToLocation != "" { tc.t.Errorf("requesting \"%s\" expected a Location header, but didn't get one", requestURI) } if loc != nil { if expectedToLocation != loc.String() { tc.t.Errorf("requesting \"%s\" expected location: \"%s\" but got \"%s\"", requestURI, expectedToLocation, loc.String()) } } return resp } // CompareAdapt adapts a config and then compares it against an expected result func CompareAdapt(t testing.TB, filename, rawConfig string, adapterName string, expectedResponse string) bool { t.Helper() cfgAdapter := caddyconfig.GetAdapter(adapterName) if cfgAdapter == nil { t.Logf("unrecognized config adapter '%s'", adapterName) return false } options := make(map[string]any) result, warnings, err := cfgAdapter.Adapt([]byte(rawConfig), options) if err != nil { t.Logf("adapting config using %s adapter: %v", adapterName, err) return false } // prettify results to keep tests human-manageable var prettyBuf bytes.Buffer err = json.Indent(&prettyBuf, result, "", "\t") if err != nil { return false } result = prettyBuf.Bytes() if len(warnings) > 0 { for _, w := range warnings { t.Logf("warning: %s:%d: %s: %s", filename, w.Line, w.Directive, w.Message) } } diff := difflib.Diff( strings.Split(expectedResponse, "\n"), strings.Split(string(result), "\n")) // scan for failure failed := false for _, d := range diff { if d.Delta != difflib.Common { failed = true break } } if failed { for _, d := range diff { switch d.Delta { case difflib.Common: fmt.Printf(" %s\n", d.Payload) case difflib.LeftOnly: fmt.Printf(" - %s\n", d.Payload) case difflib.RightOnly: fmt.Printf(" + %s\n", d.Payload) } } return false } return true } // AssertAdapt adapts a config and then tests it against an expected result func AssertAdapt(t testing.TB, rawConfig string, adapterName string, expectedResponse string) { t.Helper() ok := CompareAdapt(t, "Caddyfile", rawConfig, adapterName, expectedResponse) if !ok { t.Fail() } } // Generic request functions func applyHeaders(t testing.TB, req *http.Request, requestHeaders []string) { requestContentType := "" for _, requestHeader := range requestHeaders { arr := strings.SplitAfterN(requestHeader, ":", 2) k := strings.TrimRight(arr[0], ":") v := strings.TrimSpace(arr[1]) if k == "Content-Type" { requestContentType = v } t.Logf("Request header: %s => %s", k, v) req.Header.Set(k, v) } if requestContentType == "" { t.Logf("Content-Type header not provided") } } // AssertResponseCode will execute the request and verify the status code, returns a response for additional assertions func (tc *Tester) AssertResponseCode(req *http.Request, expectedStatusCode int) *http.Response { tc.t.Helper() resp, err := tc.Client.Do(req) if err != nil { tc.t.Fatalf("failed to call server %s", err) } if expectedStatusCode != resp.StatusCode { tc.t.Errorf("requesting \"%s\" expected status code: %d but got %d", req.URL.RequestURI(), expectedStatusCode, resp.StatusCode) } return resp } // AssertResponse request a URI and assert the status code and the body contains a string func (tc *Tester) AssertResponse(req *http.Request, expectedStatusCode int, expectedBody string) (*http.Response, string) { tc.t.Helper() resp := tc.AssertResponseCode(req, expectedStatusCode) defer resp.Body.Close() bytes, err := io.ReadAll(resp.Body) if err != nil { tc.t.Fatalf("unable to read the response body %s", err) } body := string(bytes) if body != expectedBody { tc.t.Errorf("requesting \"%s\" expected response body \"%s\" but got \"%s\"", req.RequestURI, expectedBody, body) } return resp, body } // Verb specific test functions // AssertGetResponse GET a URI and expect a statusCode and body text func (tc *Tester) AssertGetResponse(requestURI string, expectedStatusCode int, expectedBody string) (*http.Response, string) { tc.t.Helper() req, err := http.NewRequest("GET", requestURI, nil) if err != nil { tc.t.Fatalf("unable to create request %s", err) } return tc.AssertResponse(req, expectedStatusCode, expectedBody) } // AssertDeleteResponse request a URI and expect a statusCode and body text func (tc *Tester) AssertDeleteResponse(requestURI string, expectedStatusCode int, expectedBody string) (*http.Response, string) { tc.t.Helper() req, err := http.NewRequest("DELETE", requestURI, nil) if err != nil { tc.t.Fatalf("unable to create request %s", err) } return tc.AssertResponse(req, expectedStatusCode, expectedBody) } // AssertPostResponseBody POST to a URI and assert the response code and body func (tc *Tester) AssertPostResponseBody(requestURI string, requestHeaders []string, requestBody *bytes.Buffer, expectedStatusCode int, expectedBody string) (*http.Response, string) { tc.t.Helper() req, err := http.NewRequest("POST", requestURI, requestBody) if err != nil { tc.t.Errorf("failed to create request %s", err) return nil, "" } applyHeaders(tc.t, req, requestHeaders) return tc.AssertResponse(req, expectedStatusCode, expectedBody) } // AssertPutResponseBody PUT to a URI and assert the response code and body func (tc *Tester) AssertPutResponseBody(requestURI string, requestHeaders []string, requestBody *bytes.Buffer, expectedStatusCode int, expectedBody string) (*http.Response, string) { tc.t.Helper() req, err := http.NewRequest("PUT", requestURI, requestBody) if err != nil { tc.t.Errorf("failed to create request %s", err) return nil, "" } applyHeaders(tc.t, req, requestHeaders) return tc.AssertResponse(req, expectedStatusCode, expectedBody) } // AssertPatchResponseBody PATCH to a URI and assert the response code and body func (tc *Tester) AssertPatchResponseBody(requestURI string, requestHeaders []string, requestBody *bytes.Buffer, expectedStatusCode int, expectedBody string) (*http.Response, string) { tc.t.Helper() req, err := http.NewRequest("PATCH", requestURI, requestBody) if err != nil { tc.t.Errorf("failed to create request %s", err) return nil, "" } applyHeaders(tc.t, req, requestHeaders) return tc.AssertResponse(req, expectedStatusCode, expectedBody) }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/caddytest/integration/map_test.go
caddytest/integration/map_test.go
package integration import ( "bytes" "testing" "github.com/caddyserver/caddy/v2/caddytest" ) func TestMap(t *testing.T) { // arrange tester := caddytest.NewTester(t) tester.InitServer(`{ skip_install_trust admin localhost:2999 http_port 9080 https_port 9443 grace_period 1ns } localhost:9080 { map {http.request.method} {dest-1} {dest-2} { default unknown1 unknown2 ~G(.)(.) G${1}${2}-called POST post-called foobar } respond /version 200 { body "hello from localhost {dest-1} {dest-2}" } } `, "caddyfile") // act and assert tester.AssertGetResponse("http://localhost:9080/version", 200, "hello from localhost GET-called unknown2") tester.AssertPostResponseBody("http://localhost:9080/version", []string{}, bytes.NewBuffer([]byte{}), 200, "hello from localhost post-called foobar") } func TestMapRespondWithDefault(t *testing.T) { // arrange tester := caddytest.NewTester(t) tester.InitServer(`{ skip_install_trust admin localhost:2999 http_port 9080 https_port 9443 } localhost:9080 { map {http.request.method} {dest-name} { default unknown GET get-called } respond /version 200 { body "hello from localhost {dest-name}" } } `, "caddyfile") // act and assert tester.AssertGetResponse("http://localhost:9080/version", 200, "hello from localhost get-called") tester.AssertPostResponseBody("http://localhost:9080/version", []string{}, bytes.NewBuffer([]byte{}), 200, "hello from localhost unknown") } func TestMapAsJSON(t *testing.T) { // arrange tester := caddytest.NewTester(t) tester.InitServer(` { "admin": { "listen": "localhost:2999" }, "apps": { "pki": { "certificate_authorities" : { "local" : { "install_trust": false } } }, "http": { "http_port": 9080, "https_port": 9443, "servers": { "srv0": { "listen": [ ":9080" ], "routes": [ { "handle": [ { "handler": "subroute", "routes": [ { "handle": [ { "handler": "map", "source": "{http.request.method}", "destinations": ["{dest-name}"], "defaults": ["unknown"], "mappings": [ { "input": "GET", "outputs": ["get-called"] }, { "input": "POST", "outputs": ["post-called"] } ] } ] }, { "handle": [ { "body": "hello from localhost {dest-name}", "handler": "static_response", "status_code": 200 } ], "match": [ { "path": ["/version"] } ] } ] } ], "match": [ { "host": ["localhost"] } ], "terminal": true } ] } } } } }`, "json") tester.AssertGetResponse("http://localhost:9080/version", 200, "hello from localhost get-called") tester.AssertPostResponseBody("http://localhost:9080/version", []string{}, bytes.NewBuffer([]byte{}), 200, "hello from localhost post-called") }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/caddytest/integration/handler_test.go
caddytest/integration/handler_test.go
package integration import ( "bytes" "net/http" "testing" "github.com/caddyserver/caddy/v2/caddytest" ) func TestBrowse(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(` { skip_install_trust admin localhost:2999 http_port 9080 https_port 9443 grace_period 1ns } http://localhost:9080 { file_server browse } `, "caddyfile") req, err := http.NewRequest(http.MethodGet, "http://localhost:9080/", nil) if err != nil { t.Fail() return } tester.AssertResponseCode(req, 200) } func TestRespondWithJSON(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(` { skip_install_trust admin localhost:2999 http_port 9080 https_port 9443 grace_period 1ns } localhost { respond {http.request.body} } `, "caddyfile") res, _ := tester.AssertPostResponseBody("https://localhost:9443/", nil, bytes.NewBufferString(`{ "greeting": "Hello, world!" }`), 200, `{ "greeting": "Hello, world!" }`) if res.Header.Get("Content-Type") != "application/json" { t.Errorf("expected Content-Type to be application/json, but was %s", res.Header.Get("Content-Type")) } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/caddytest/integration/intercept_test.go
caddytest/integration/intercept_test.go
package integration import ( "testing" "github.com/caddyserver/caddy/v2/caddytest" ) func TestIntercept(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(`{ skip_install_trust admin localhost:2999 http_port 9080 https_port 9443 grace_period 1ns } localhost:9080 { respond /intercept "I'm a teapot" 408 header /intercept To-Intercept ok respond /no-intercept "I'm not a teapot" intercept { @teapot status 408 handle_response @teapot { header /intercept intercepted {resp.header.To-Intercept} respond /intercept "I'm a combined coffee/tea pot that is temporarily out of coffee" 503 } } } `, "caddyfile") r, _ := tester.AssertGetResponse("http://localhost:9080/intercept", 503, "I'm a combined coffee/tea pot that is temporarily out of coffee") if r.Header.Get("intercepted") != "ok" { t.Fatalf(`header "intercepted" value is not "ok": %s`, r.Header.Get("intercepted")) } tester.AssertGetResponse("http://localhost:9080/no-intercept", 200, "I'm not a teapot") }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/caddytest/integration/sni_test.go
caddytest/integration/sni_test.go
package integration import ( "testing" "github.com/caddyserver/caddy/v2/caddytest" ) func TestDefaultSNI(t *testing.T) { // arrange tester := caddytest.NewTester(t) tester.InitServer(`{ "admin": { "listen": "localhost:2999" }, "apps": { "http": { "http_port": 9080, "https_port": 9443, "grace_period": 1, "servers": { "srv0": { "listen": [ ":9443" ], "routes": [ { "handle": [ { "handler": "subroute", "routes": [ { "handle": [ { "body": "hello from a.caddy.localhost", "handler": "static_response", "status_code": 200 } ], "match": [ { "path": [ "/version" ] } ] } ] } ], "match": [ { "host": [ "127.0.0.1" ] } ], "terminal": true } ], "tls_connection_policies": [ { "certificate_selection": { "any_tag": ["cert0"] }, "match": { "sni": [ "127.0.0.1" ] } }, { "default_sni": "*.caddy.localhost" } ] } } }, "tls": { "certificates": { "load_files": [ { "certificate": "/caddy.localhost.crt", "key": "/caddy.localhost.key", "tags": [ "cert0" ] } ] } }, "pki": { "certificate_authorities" : { "local" : { "install_trust": false } } } } } `, "json") // act and assert // makes a request with no sni tester.AssertGetResponse("https://127.0.0.1:9443/version", 200, "hello from a.caddy.localhost") } func TestDefaultSNIWithNamedHostAndExplicitIP(t *testing.T) { // arrange tester := caddytest.NewTester(t) tester.InitServer(` { "admin": { "listen": "localhost:2999" }, "apps": { "http": { "http_port": 9080, "https_port": 9443, "grace_period": 1, "servers": { "srv0": { "listen": [ ":9443" ], "routes": [ { "handle": [ { "handler": "subroute", "routes": [ { "handle": [ { "body": "hello from a", "handler": "static_response", "status_code": 200 } ], "match": [ { "path": [ "/version" ] } ] } ] } ], "match": [ { "host": [ "a.caddy.localhost", "127.0.0.1" ] } ], "terminal": true } ], "tls_connection_policies": [ { "certificate_selection": { "any_tag": ["cert0"] }, "default_sni": "a.caddy.localhost", "match": { "sni": [ "a.caddy.localhost", "127.0.0.1", "" ] } }, { "default_sni": "a.caddy.localhost" } ] } } }, "tls": { "certificates": { "load_files": [ { "certificate": "/a.caddy.localhost.crt", "key": "/a.caddy.localhost.key", "tags": [ "cert0" ] } ] } }, "pki": { "certificate_authorities" : { "local" : { "install_trust": false } } } } } `, "json") // act and assert // makes a request with no sni tester.AssertGetResponse("https://127.0.0.1:9443/version", 200, "hello from a") } func TestDefaultSNIWithPortMappingOnly(t *testing.T) { // arrange tester := caddytest.NewTester(t) tester.InitServer(` { "admin": { "listen": "localhost:2999" }, "apps": { "http": { "http_port": 9080, "https_port": 9443, "grace_period": 1, "servers": { "srv0": { "listen": [ ":9443" ], "routes": [ { "handle": [ { "body": "hello from a.caddy.localhost", "handler": "static_response", "status_code": 200 } ], "match": [ { "path": [ "/version" ] } ] } ], "tls_connection_policies": [ { "certificate_selection": { "any_tag": ["cert0"] }, "default_sni": "a.caddy.localhost" } ] } } }, "tls": { "certificates": { "load_files": [ { "certificate": "/a.caddy.localhost.crt", "key": "/a.caddy.localhost.key", "tags": [ "cert0" ] } ] } }, "pki": { "certificate_authorities" : { "local" : { "install_trust": false } } } } } `, "json") // act and assert // makes a request with no sni tester.AssertGetResponse("https://127.0.0.1:9443/version", 200, "hello from a.caddy.localhost") } func TestHttpOnlyOnDomainWithSNI(t *testing.T) { caddytest.AssertAdapt(t, ` { skip_install_trust default_sni a.caddy.localhost } :80 { respond /version 200 { body "hello from localhost" } } `, "caddyfile", `{ "apps": { "http": { "servers": { "srv0": { "listen": [ ":80" ], "routes": [ { "match": [ { "path": [ "/version" ] } ], "handle": [ { "body": "hello from localhost", "handler": "static_response", "status_code": 200 } ] } ] } } }, "pki": { "certificate_authorities": { "local": { "install_trust": false } } } } }`) }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/caddytest/integration/acmeserver_test.go
caddytest/integration/acmeserver_test.go
package integration import ( "context" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "log/slog" "strings" "testing" "github.com/mholt/acmez/v3" "github.com/mholt/acmez/v3/acme" "go.uber.org/zap" "go.uber.org/zap/exp/zapslog" "github.com/caddyserver/caddy/v2/caddytest" ) func TestACMEServerDirectory(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(` { skip_install_trust local_certs admin localhost:2999 http_port 9080 https_port 9443 pki { ca local { name "Caddy Local Authority" } } } acme.localhost:9443 { acme_server } `, "caddyfile") tester.AssertGetResponse( "https://acme.localhost:9443/acme/local/directory", 200, `{"newNonce":"https://acme.localhost:9443/acme/local/new-nonce","newAccount":"https://acme.localhost:9443/acme/local/new-account","newOrder":"https://acme.localhost:9443/acme/local/new-order","revokeCert":"https://acme.localhost:9443/acme/local/revoke-cert","keyChange":"https://acme.localhost:9443/acme/local/key-change"} `) } func TestACMEServerAllowPolicy(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(` { skip_install_trust local_certs admin localhost:2999 http_port 9080 https_port 9443 pki { ca local { name "Caddy Local Authority" } } } acme.localhost { acme_server { challenges http-01 allow { domains localhost } } } `, "caddyfile") ctx := context.Background() logger, err := zap.NewDevelopment() if err != nil { t.Error(err) return } client := acmez.Client{ Client: &acme.Client{ Directory: "https://acme.localhost:9443/acme/local/directory", HTTPClient: tester.Client, Logger: slog.New(zapslog.NewHandler(logger.Core())), }, ChallengeSolvers: map[string]acmez.Solver{ acme.ChallengeTypeHTTP01: &naiveHTTPSolver{logger: logger}, }, } accountPrivateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { t.Errorf("generating account key: %v", err) } account := acme.Account{ Contact: []string{"mailto:you@example.com"}, TermsOfServiceAgreed: true, PrivateKey: accountPrivateKey, } account, err = client.NewAccount(ctx, account) if err != nil { t.Errorf("new account: %v", err) return } // Every certificate needs a key. certPrivateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { t.Errorf("generating certificate key: %v", err) return } { certs, err := client.ObtainCertificateForSANs(ctx, account, certPrivateKey, []string{"localhost"}) if err != nil { t.Errorf("obtaining certificate for allowed domain: %v", err) return } // ACME servers should usually give you the entire certificate chain // in PEM format, and sometimes even alternate chains! It's up to you // which one(s) to store and use, but whatever you do, be sure to // store the certificate and key somewhere safe and secure, i.e. don't // lose them! for _, cert := range certs { t.Logf("Certificate %q:\n%s\n\n", cert.URL, cert.ChainPEM) } } { _, err := client.ObtainCertificateForSANs(ctx, account, certPrivateKey, []string{"not-matching.localhost"}) if err == nil { t.Errorf("obtaining certificate for 'not-matching.localhost' domain") } else if err != nil && !strings.Contains(err.Error(), "urn:ietf:params:acme:error:rejectedIdentifier") { t.Logf("unexpected error: %v", err) } } } func TestACMEServerDenyPolicy(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(` { skip_install_trust local_certs admin localhost:2999 http_port 9080 https_port 9443 pki { ca local { name "Caddy Local Authority" } } } acme.localhost { acme_server { deny { domains deny.localhost } } } `, "caddyfile") ctx := context.Background() logger, err := zap.NewDevelopment() if err != nil { t.Error(err) return } client := acmez.Client{ Client: &acme.Client{ Directory: "https://acme.localhost:9443/acme/local/directory", HTTPClient: tester.Client, Logger: slog.New(zapslog.NewHandler(logger.Core())), }, ChallengeSolvers: map[string]acmez.Solver{ acme.ChallengeTypeHTTP01: &naiveHTTPSolver{logger: logger}, }, } accountPrivateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { t.Errorf("generating account key: %v", err) } account := acme.Account{ Contact: []string{"mailto:you@example.com"}, TermsOfServiceAgreed: true, PrivateKey: accountPrivateKey, } account, err = client.NewAccount(ctx, account) if err != nil { t.Errorf("new account: %v", err) return } // Every certificate needs a key. certPrivateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { t.Errorf("generating certificate key: %v", err) return } { _, err := client.ObtainCertificateForSANs(ctx, account, certPrivateKey, []string{"deny.localhost"}) if err == nil { t.Errorf("obtaining certificate for 'deny.localhost' domain") } else if err != nil && !strings.Contains(err.Error(), "urn:ietf:params:acme:error:rejectedIdentifier") { t.Logf("unexpected error: %v", err) } } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/caddytest/integration/reverseproxy_test.go
caddytest/integration/reverseproxy_test.go
package integration import ( "fmt" "net" "net/http" "os" "runtime" "strings" "testing" "time" "github.com/caddyserver/caddy/v2/caddytest" ) func TestSRVReverseProxy(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(` { "admin": { "listen": "localhost:2999" }, "apps": { "pki": { "certificate_authorities": { "local": { "install_trust": false } } }, "http": { "grace_period": 1, "servers": { "srv0": { "listen": [ ":18080" ], "routes": [ { "handle": [ { "handler": "reverse_proxy", "dynamic_upstreams": { "source": "srv", "name": "srv.host.service.consul" } } ] } ] } } } } } `, "json") } func TestDialWithPlaceholderUnix(t *testing.T) { if runtime.GOOS == "windows" { t.SkipNow() } f, err := os.CreateTemp("", "*.sock") if err != nil { t.Errorf("failed to create TempFile: %s", err) return } // a hack to get a file name within a valid path to use as socket socketName := f.Name() os.Remove(f.Name()) server := http.Server{ Handler: http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { w.Write([]byte("Hello, World!")) }), } unixListener, err := net.Listen("unix", socketName) if err != nil { t.Errorf("failed to listen on the socket: %s", err) return } go server.Serve(unixListener) t.Cleanup(func() { server.Close() }) runtime.Gosched() // Allow other goroutines to run tester := caddytest.NewTester(t) tester.InitServer(` { "admin": { "listen": "localhost:2999" }, "apps": { "pki": { "certificate_authorities": { "local": { "install_trust": false } } }, "http": { "grace_period": 1, "servers": { "srv0": { "listen": [ ":18080" ], "routes": [ { "handle": [ { "handler": "reverse_proxy", "upstreams": [ { "dial": "unix/{http.request.header.X-Caddy-Upstream-Dial}" } ] } ] } ] } } } } } `, "json") req, err := http.NewRequest(http.MethodGet, "http://localhost:18080", nil) if err != nil { t.Fail() return } req.Header.Set("X-Caddy-Upstream-Dial", socketName) tester.AssertResponse(req, 200, "Hello, World!") } func TestReverseProxyWithPlaceholderDialAddress(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(` { "admin": { "listen": "localhost:2999" }, "apps": { "pki": { "certificate_authorities": { "local": { "install_trust": false } } }, "http": { "grace_period": 1, "servers": { "srv0": { "listen": [ ":18080" ], "routes": [ { "match": [ { "host": [ "localhost" ] } ], "handle": [ { "handler": "static_response", "body": "Hello, World!" } ], "terminal": true } ], "automatic_https": { "skip": [ "localhost" ] } }, "srv1": { "listen": [ ":9080" ], "routes": [ { "match": [ { "host": [ "localhost" ] } ], "handle": [ { "handler": "reverse_proxy", "upstreams": [ { "dial": "{http.request.header.X-Caddy-Upstream-Dial}" } ] } ], "terminal": true } ], "automatic_https": { "skip": [ "localhost" ] } } } } } } `, "json") req, err := http.NewRequest(http.MethodGet, "http://localhost:9080", nil) if err != nil { t.Fail() return } req.Header.Set("X-Caddy-Upstream-Dial", "localhost:18080") tester.AssertResponse(req, 200, "Hello, World!") } func TestReverseProxyWithPlaceholderTCPDialAddress(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(` { "admin": { "listen": "localhost:2999" }, "apps": { "pki": { "certificate_authorities": { "local": { "install_trust": false } } }, "http": { "grace_period": 1, "servers": { "srv0": { "listen": [ ":18080" ], "routes": [ { "match": [ { "host": [ "localhost" ] } ], "handle": [ { "handler": "static_response", "body": "Hello, World!" } ], "terminal": true } ], "automatic_https": { "skip": [ "localhost" ] } }, "srv1": { "listen": [ ":9080" ], "routes": [ { "match": [ { "host": [ "localhost" ] } ], "handle": [ { "handler": "reverse_proxy", "upstreams": [ { "dial": "tcp/{http.request.header.X-Caddy-Upstream-Dial}:18080" } ] } ], "terminal": true } ], "automatic_https": { "skip": [ "localhost" ] } } } } } } `, "json") req, err := http.NewRequest(http.MethodGet, "http://localhost:9080", nil) if err != nil { t.Fail() return } req.Header.Set("X-Caddy-Upstream-Dial", "localhost") tester.AssertResponse(req, 200, "Hello, World!") } func TestReverseProxyHealthCheck(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(` { skip_install_trust admin localhost:2999 http_port 9080 https_port 9443 grace_period 1ns } http://localhost:2020 { respond "Hello, World!" } http://localhost:2021 { respond "ok" } http://localhost:9080 { reverse_proxy { to localhost:2020 health_uri /health health_port 2021 health_interval 10ms health_timeout 100ms health_passes 1 health_fails 1 } } `, "caddyfile") time.Sleep(100 * time.Millisecond) // TODO: for some reason this test seems particularly flaky, getting 503 when it should be 200, unless we wait tester.AssertGetResponse("http://localhost:9080/", 200, "Hello, World!") } func TestReverseProxyHealthCheckUnixSocket(t *testing.T) { if runtime.GOOS == "windows" { t.SkipNow() } tester := caddytest.NewTester(t) f, err := os.CreateTemp("", "*.sock") if err != nil { t.Errorf("failed to create TempFile: %s", err) return } // a hack to get a file name within a valid path to use as socket socketName := f.Name() os.Remove(f.Name()) server := http.Server{ Handler: http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { if strings.HasPrefix(req.URL.Path, "/health") { w.Write([]byte("ok")) return } w.Write([]byte("Hello, World!")) }), } unixListener, err := net.Listen("unix", socketName) if err != nil { t.Errorf("failed to listen on the socket: %s", err) return } go server.Serve(unixListener) t.Cleanup(func() { server.Close() }) runtime.Gosched() // Allow other goroutines to run tester.InitServer(fmt.Sprintf(` { skip_install_trust admin localhost:2999 http_port 9080 https_port 9443 grace_period 1ns } http://localhost:9080 { reverse_proxy { to unix/%s health_uri /health health_port 2021 health_interval 2s health_timeout 5s } } `, socketName), "caddyfile") tester.AssertGetResponse("http://localhost:9080/", 200, "Hello, World!") } func TestReverseProxyHealthCheckUnixSocketWithoutPort(t *testing.T) { if runtime.GOOS == "windows" { t.SkipNow() } tester := caddytest.NewTester(t) f, err := os.CreateTemp("", "*.sock") if err != nil { t.Errorf("failed to create TempFile: %s", err) return } // a hack to get a file name within a valid path to use as socket socketName := f.Name() os.Remove(f.Name()) server := http.Server{ Handler: http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { if strings.HasPrefix(req.URL.Path, "/health") { w.Write([]byte("ok")) return } w.Write([]byte("Hello, World!")) }), } unixListener, err := net.Listen("unix", socketName) if err != nil { t.Errorf("failed to listen on the socket: %s", err) return } go server.Serve(unixListener) t.Cleanup(func() { server.Close() }) runtime.Gosched() // Allow other goroutines to run tester.InitServer(fmt.Sprintf(` { skip_install_trust admin localhost:2999 http_port 9080 https_port 9443 grace_period 1ns } http://localhost:9080 { reverse_proxy { to unix/%s health_uri /health health_interval 2s health_timeout 5s } } `, socketName), "caddyfile") tester.AssertGetResponse("http://localhost:9080/", 200, "Hello, World!") }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/caddytest/integration/stream_test.go
caddytest/integration/stream_test.go
package integration import ( "compress/gzip" "context" "crypto/rand" "fmt" "io" "net/http" "net/http/httputil" "net/url" "strings" "testing" "time" "golang.org/x/net/http2" "golang.org/x/net/http2/h2c" "github.com/caddyserver/caddy/v2/caddytest" ) // (see https://github.com/caddyserver/caddy/issues/3556 for use case) func TestH2ToH2CStream(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(` { "admin": { "listen": "localhost:2999" }, "apps": { "http": { "http_port": 9080, "https_port": 9443, "grace_period": 1, "servers": { "srv0": { "listen": [ ":9443" ], "routes": [ { "handle": [ { "handler": "reverse_proxy", "transport": { "protocol": "http", "compression": false, "versions": [ "h2c", "2" ] }, "upstreams": [ { "dial": "localhost:54321" } ] } ], "match": [ { "path": [ "/tov2ray" ] } ] } ], "tls_connection_policies": [ { "certificate_selection": { "any_tag": ["cert0"] }, "default_sni": "a.caddy.localhost" } ] } } }, "tls": { "certificates": { "load_files": [ { "certificate": "/a.caddy.localhost.crt", "key": "/a.caddy.localhost.key", "tags": [ "cert0" ] } ] } }, "pki": { "certificate_authorities" : { "local" : { "install_trust": false } } } } } `, "json") expectedBody := "some data to be echoed" // start the server server := testH2ToH2CStreamServeH2C(t) go server.ListenAndServe() defer func() { ctx, cancel := context.WithTimeout(context.Background(), time.Nanosecond) defer cancel() server.Shutdown(ctx) }() r, w := io.Pipe() req := &http.Request{ Method: "PUT", Body: io.NopCloser(r), URL: &url.URL{ Scheme: "https", Host: "127.0.0.1:9443", Path: "/tov2ray", }, Proto: "HTTP/2", ProtoMajor: 2, ProtoMinor: 0, Header: make(http.Header), } // Disable any compression method from server. req.Header.Set("Accept-Encoding", "identity") resp := tester.AssertResponseCode(req, http.StatusOK) if resp.StatusCode != http.StatusOK { return } go func() { fmt.Fprint(w, expectedBody) w.Close() }() defer resp.Body.Close() bytes, err := io.ReadAll(resp.Body) if err != nil { t.Fatalf("unable to read the response body %s", err) } body := string(bytes) if !strings.Contains(body, expectedBody) { t.Errorf("requesting \"%s\" expected response body \"%s\" but got \"%s\"", req.RequestURI, expectedBody, body) } } func testH2ToH2CStreamServeH2C(t *testing.T) *http.Server { h2s := &http2.Server{} handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { rstring, err := httputil.DumpRequest(r, false) if err == nil { t.Logf("h2c server received req: %s", rstring) } // We only accept HTTP/2! if r.ProtoMajor != 2 { t.Error("Not a HTTP/2 request, rejected!") w.WriteHeader(http.StatusInternalServerError) return } if r.Host != "127.0.0.1:9443" { t.Errorf("r.Host doesn't match, %v!", r.Host) w.WriteHeader(http.StatusNotFound) return } if !strings.HasPrefix(r.URL.Path, "/tov2ray") { w.WriteHeader(http.StatusNotFound) return } w.Header().Set("Cache-Control", "no-store") w.WriteHeader(200) http.NewResponseController(w).Flush() buf := make([]byte, 4*1024) for { n, err := r.Body.Read(buf) if n > 0 { w.Write(buf[:n]) } if err != nil { if err == io.EOF { r.Body.Close() } break } } }) server := &http.Server{ Addr: "127.0.0.1:54321", Handler: h2c.NewHandler(handler, h2s), } return server } // (see https://github.com/caddyserver/caddy/issues/3606 for use case) func TestH2ToH1ChunkedResponse(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(` { "admin": { "listen": "localhost:2999" }, "logging": { "logs": { "default": { "level": "DEBUG" } } }, "apps": { "http": { "http_port": 9080, "https_port": 9443, "grace_period": 1, "servers": { "srv0": { "listen": [ ":9443" ], "routes": [ { "handle": [ { "handler": "subroute", "routes": [ { "handle": [ { "encodings": { "gzip": {} }, "handler": "encode" } ] }, { "handle": [ { "handler": "reverse_proxy", "upstreams": [ { "dial": "localhost:54321" } ] } ], "match": [ { "path": [ "/tov2ray" ] } ] } ] } ], "terminal": true } ], "tls_connection_policies": [ { "certificate_selection": { "any_tag": [ "cert0" ] }, "default_sni": "a.caddy.localhost" } ] } } }, "tls": { "certificates": { "load_files": [ { "certificate": "/a.caddy.localhost.crt", "key": "/a.caddy.localhost.key", "tags": [ "cert0" ] } ] } }, "pki": { "certificate_authorities": { "local": { "install_trust": false } } } } } `, "json") // need a large body here to trigger caddy's compression, larger than gzip.miniLength expectedBody, err := GenerateRandomString(1024) if err != nil { t.Fatalf("generate expected body failed, err: %s", err) } // start the server server := testH2ToH1ChunkedResponseServeH1(t) go server.ListenAndServe() defer func() { ctx, cancel := context.WithTimeout(context.Background(), time.Nanosecond) defer cancel() server.Shutdown(ctx) }() r, w := io.Pipe() req := &http.Request{ Method: "PUT", Body: io.NopCloser(r), URL: &url.URL{ Scheme: "https", Host: "127.0.0.1:9443", Path: "/tov2ray", }, Proto: "HTTP/2", ProtoMajor: 2, ProtoMinor: 0, Header: make(http.Header), } // underlying transport will automatically add gzip // req.Header.Set("Accept-Encoding", "gzip") go func() { fmt.Fprint(w, expectedBody) w.Close() }() resp := tester.AssertResponseCode(req, http.StatusOK) if resp.StatusCode != http.StatusOK { return } defer resp.Body.Close() bytes, err := io.ReadAll(resp.Body) if err != nil { t.Fatalf("unable to read the response body %s", err) } body := string(bytes) if body != expectedBody { t.Errorf("requesting \"%s\" expected response body \"%s\" but got \"%s\"", req.RequestURI, expectedBody, body) } } func testH2ToH1ChunkedResponseServeH1(t *testing.T) *http.Server { handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Host != "127.0.0.1:9443" { t.Errorf("r.Host doesn't match, %v!", r.Host) w.WriteHeader(http.StatusNotFound) return } if !strings.HasPrefix(r.URL.Path, "/tov2ray") { w.WriteHeader(http.StatusNotFound) return } defer r.Body.Close() bytes, err := io.ReadAll(r.Body) if err != nil { t.Fatalf("unable to read the response body %s", err) } n := len(bytes) var writer io.Writer if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") { gw, err := gzip.NewWriterLevel(w, 5) if err != nil { t.Error("can't return gzip data") w.WriteHeader(http.StatusInternalServerError) return } defer gw.Close() writer = gw w.Header().Set("Content-Encoding", "gzip") w.Header().Del("Content-Length") w.WriteHeader(200) } else { writer = w } if n > 0 { writer.Write(bytes[:]) } }) server := &http.Server{ Addr: "127.0.0.1:54321", Handler: handler, } return server } // GenerateRandomBytes returns securely generated random bytes. // It will return an error if the system's secure random // number generator fails to function correctly, in which // case the caller should not continue. func GenerateRandomBytes(n int) ([]byte, error) { b := make([]byte, n) _, err := rand.Read(b) // Note that err == nil only if we read len(b) bytes. if err != nil { return nil, err } return b, nil } // GenerateRandomString returns a securely generated random string. // It will return an error if the system's secure random // number generator fails to function correctly, in which // case the caller should not continue. func GenerateRandomString(n int) (string, error) { const letters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-" bytes, err := GenerateRandomBytes(n) if err != nil { return "", err } for i, b := range bytes { bytes[i] = letters[b%byte(len(letters))] } return string(bytes), nil }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/caddytest/integration/caddyfile_test.go
caddytest/integration/caddyfile_test.go
package integration import ( "net/http" "net/url" "testing" "github.com/caddyserver/caddy/v2/caddytest" ) func TestRespond(t *testing.T) { // arrange tester := caddytest.NewTester(t) tester.InitServer(` { admin localhost:2999 http_port 9080 https_port 9443 grace_period 1ns } localhost:9080 { respond /version 200 { body "hello from localhost" } } `, "caddyfile") // act and assert tester.AssertGetResponse("http://localhost:9080/version", 200, "hello from localhost") } func TestRedirect(t *testing.T) { // arrange tester := caddytest.NewTester(t) tester.InitServer(` { admin localhost:2999 http_port 9080 https_port 9443 grace_period 1ns } localhost:9080 { redir / http://localhost:9080/hello 301 respond /hello 200 { body "hello from localhost" } } `, "caddyfile") // act and assert tester.AssertRedirect("http://localhost:9080/", "http://localhost:9080/hello", 301) // follow redirect tester.AssertGetResponse("http://localhost:9080/", 200, "hello from localhost") } func TestDuplicateHosts(t *testing.T) { // act and assert caddytest.AssertLoadError(t, ` localhost:9080 { } localhost:9080 { } `, "caddyfile", "ambiguous site definition") } func TestReadCookie(t *testing.T) { localhost, _ := url.Parse("http://localhost") cookie := http.Cookie{ Name: "clientname", Value: "caddytest", } // arrange tester := caddytest.NewTester(t) tester.Client.Jar.SetCookies(localhost, []*http.Cookie{&cookie}) tester.InitServer(` { skip_install_trust admin localhost:2999 http_port 9080 https_port 9443 grace_period 1ns } localhost:9080 { templates { root testdata } file_server { root testdata } } `, "caddyfile") // act and assert tester.AssertGetResponse("http://localhost:9080/cookie.html", 200, "<h2>Cookie.ClientName caddytest</h2>") } func TestReplIndex(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(` { skip_install_trust admin localhost:2999 http_port 9080 https_port 9443 grace_period 1ns } localhost:9080 { templates { root testdata } file_server { root testdata index "index.{host}.html" } } `, "caddyfile") // act and assert tester.AssertGetResponse("http://localhost:9080/", 200, "") } func TestInvalidPrefix(t *testing.T) { type testCase struct { config, expectedError string } failureCases := []testCase{ { config: `wss://localhost`, expectedError: `the scheme wss:// is only supported in browsers; use https:// instead`, }, { config: `ws://localhost`, expectedError: `the scheme ws:// is only supported in browsers; use http:// instead`, }, { config: `someInvalidPrefix://localhost`, expectedError: "unsupported URL scheme someinvalidprefix://", }, { config: `h2c://localhost`, expectedError: `unsupported URL scheme h2c://`, }, { config: `localhost, wss://localhost`, expectedError: `the scheme wss:// is only supported in browsers; use https:// instead`, }, { config: `localhost { reverse_proxy ws://localhost" }`, expectedError: `the scheme ws:// is only supported in browsers; use http:// instead`, }, { config: `localhost { reverse_proxy someInvalidPrefix://localhost" }`, expectedError: `unsupported URL scheme someinvalidprefix://`, }, } for _, failureCase := range failureCases { caddytest.AssertLoadError(t, failureCase.config, "caddyfile", failureCase.expectedError) } } func TestValidPrefix(t *testing.T) { type testCase struct { rawConfig, expectedResponse string } successCases := []testCase{ { "localhost", `{ "apps": { "http": { "servers": { "srv0": { "listen": [ ":443" ], "routes": [ { "match": [ { "host": [ "localhost" ] } ], "terminal": true } ] } } } } }`, }, { "https://localhost", `{ "apps": { "http": { "servers": { "srv0": { "listen": [ ":443" ], "routes": [ { "match": [ { "host": [ "localhost" ] } ], "terminal": true } ] } } } } }`, }, { "http://localhost", `{ "apps": { "http": { "servers": { "srv0": { "listen": [ ":80" ], "routes": [ { "match": [ { "host": [ "localhost" ] } ], "terminal": true } ] } } } } }`, }, { `localhost { reverse_proxy http://localhost:3000 }`, `{ "apps": { "http": { "servers": { "srv0": { "listen": [ ":443" ], "routes": [ { "match": [ { "host": [ "localhost" ] } ], "handle": [ { "handler": "subroute", "routes": [ { "handle": [ { "handler": "reverse_proxy", "upstreams": [ { "dial": "localhost:3000" } ] } ] } ] } ], "terminal": true } ] } } } } }`, }, { `localhost { reverse_proxy https://localhost:3000 }`, `{ "apps": { "http": { "servers": { "srv0": { "listen": [ ":443" ], "routes": [ { "match": [ { "host": [ "localhost" ] } ], "handle": [ { "handler": "subroute", "routes": [ { "handle": [ { "handler": "reverse_proxy", "transport": { "protocol": "http", "tls": {} }, "upstreams": [ { "dial": "localhost:3000" } ] } ] } ] } ], "terminal": true } ] } } } } }`, }, { `localhost { reverse_proxy h2c://localhost:3000 }`, `{ "apps": { "http": { "servers": { "srv0": { "listen": [ ":443" ], "routes": [ { "match": [ { "host": [ "localhost" ] } ], "handle": [ { "handler": "subroute", "routes": [ { "handle": [ { "handler": "reverse_proxy", "transport": { "protocol": "http", "versions": [ "h2c", "2" ] }, "upstreams": [ { "dial": "localhost:3000" } ] } ] } ] } ], "terminal": true } ] } } } } }`, }, { `localhost { reverse_proxy localhost:3000 }`, `{ "apps": { "http": { "servers": { "srv0": { "listen": [ ":443" ], "routes": [ { "match": [ { "host": [ "localhost" ] } ], "handle": [ { "handler": "subroute", "routes": [ { "handle": [ { "handler": "reverse_proxy", "upstreams": [ { "dial": "localhost:3000" } ] } ] } ] } ], "terminal": true } ] } } } } }`, }, } for _, successCase := range successCases { caddytest.AssertAdapt(t, successCase.rawConfig, "caddyfile", successCase.expectedResponse) } } func TestUriReplace(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(` { admin localhost:2999 http_port 9080 } :9080 uri replace "\}" %7D uri replace "\{" %7B respond "{query}"`, "caddyfile") tester.AssertGetResponse("http://localhost:9080/endpoint?test={%20content%20}", 200, "test=%7B%20content%20%7D") } func TestUriOps(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(` { admin localhost:2999 http_port 9080 } :9080 uri query +foo bar uri query -baz uri query taz test uri query key=value example uri query changethis>changed respond "{query}"`, "caddyfile") tester.AssertGetResponse("http://localhost:9080/endpoint?foo=bar0&baz=buz&taz=nottest&changethis=val", 200, "changed=val&foo=bar0&foo=bar&key%3Dvalue=example&taz=test") } // Tests the `http.request.local.port` placeholder. // We don't test the very similar `http.request.local.host` placeholder, // because depending on the host the test is running on, localhost might // refer to 127.0.0.1 or ::1. // TODO: Test each http version separately (especially http/3) func TestHttpRequestLocalPortPlaceholder(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(` { admin localhost:2999 http_port 9080 } :9080 respond "{http.request.local.port}"`, "caddyfile") tester.AssertGetResponse("http://localhost:9080/", 200, "9080") } func TestSetThenAddQueryParams(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(` { admin localhost:2999 http_port 9080 } :9080 uri query foo bar uri query +foo baz respond "{query}"`, "caddyfile") tester.AssertGetResponse("http://localhost:9080/endpoint", 200, "foo=bar&foo=baz") } func TestSetThenDeleteParams(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(` { admin localhost:2999 http_port 9080 } :9080 uri query bar foo{query.foo} uri query -foo respond "{query}"`, "caddyfile") tester.AssertGetResponse("http://localhost:9080/endpoint?foo=bar", 200, "bar=foobar") } func TestRenameAndOtherOps(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(` { admin localhost:2999 http_port 9080 } :9080 uri query foo>bar uri query bar taz uri query +bar baz respond "{query}"`, "caddyfile") tester.AssertGetResponse("http://localhost:9080/endpoint?foo=bar", 200, "bar=taz&bar=baz") } func TestReplaceOps(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(` { admin localhost:2999 http_port 9080 } :9080 uri query foo bar baz respond "{query}"`, "caddyfile") tester.AssertGetResponse("http://localhost:9080/endpoint?foo=bar", 200, "foo=baz") } func TestReplaceWithReplacementPlaceholder(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(` { admin localhost:2999 http_port 9080 } :9080 uri query foo bar {query.placeholder} respond "{query}"`, "caddyfile") tester.AssertGetResponse("http://localhost:9080/endpoint?placeholder=baz&foo=bar", 200, "foo=baz&placeholder=baz") } func TestReplaceWithKeyPlaceholder(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(` { admin localhost:2999 http_port 9080 } :9080 uri query {query.placeholder} bar baz respond "{query}"`, "caddyfile") tester.AssertGetResponse("http://localhost:9080/endpoint?placeholder=foo&foo=bar", 200, "foo=baz&placeholder=foo") } func TestPartialReplacement(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(` { admin localhost:2999 http_port 9080 } :9080 uri query foo ar az respond "{query}"`, "caddyfile") tester.AssertGetResponse("http://localhost:9080/endpoint?foo=bar", 200, "foo=baz") } func TestNonExistingSearch(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(` { admin localhost:2999 http_port 9080 } :9080 uri query foo var baz respond "{query}"`, "caddyfile") tester.AssertGetResponse("http://localhost:9080/endpoint?foo=bar", 200, "foo=bar") } func TestReplaceAllOps(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(` { admin localhost:2999 http_port 9080 } :9080 uri query * bar baz respond "{query}"`, "caddyfile") tester.AssertGetResponse("http://localhost:9080/endpoint?foo=bar&baz=bar", 200, "baz=baz&foo=baz") } func TestUriOpsBlock(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(` { admin localhost:2999 http_port 9080 } :9080 uri query { +foo bar -baz taz test } respond "{query}"`, "caddyfile") tester.AssertGetResponse("http://localhost:9080/endpoint?foo=bar0&baz=buz&taz=nottest", 200, "foo=bar0&foo=bar&taz=test") } func TestHandleErrorSimpleCodes(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(`{ admin localhost:2999 http_port 9080 } localhost:9080 { root * /srv error /private* "Unauthorized" 410 error /hidden* "Not found" 404 handle_errors 404 410 { respond "404 or 410 error" } }`, "caddyfile") // act and assert tester.AssertGetResponse("http://localhost:9080/private", 410, "404 or 410 error") tester.AssertGetResponse("http://localhost:9080/hidden", 404, "404 or 410 error") } func TestHandleErrorRange(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(`{ admin localhost:2999 http_port 9080 } localhost:9080 { root * /srv error /private* "Unauthorized" 410 error /hidden* "Not found" 404 handle_errors 4xx { respond "Error in the [400 .. 499] range" } }`, "caddyfile") // act and assert tester.AssertGetResponse("http://localhost:9080/private", 410, "Error in the [400 .. 499] range") tester.AssertGetResponse("http://localhost:9080/hidden", 404, "Error in the [400 .. 499] range") } func TestHandleErrorSort(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(`{ admin localhost:2999 http_port 9080 } localhost:9080 { root * /srv error /private* "Unauthorized" 410 error /hidden* "Not found" 404 error /internalerr* "Internal Server Error" 500 handle_errors { respond "Fallback route: code outside the [400..499] range" } handle_errors 4xx { respond "Error in the [400 .. 499] range" } }`, "caddyfile") // act and assert tester.AssertGetResponse("http://localhost:9080/internalerr", 500, "Fallback route: code outside the [400..499] range") tester.AssertGetResponse("http://localhost:9080/hidden", 404, "Error in the [400 .. 499] range") } func TestHandleErrorRangeAndCodes(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(`{ admin localhost:2999 http_port 9080 } localhost:9080 { root * /srv error /private* "Unauthorized" 410 error /threehundred* "Moved Permanently" 301 error /internalerr* "Internal Server Error" 500 handle_errors 500 3xx { respond "Error code is equal to 500 or in the [300..399] range" } handle_errors 4xx { respond "Error in the [400 .. 499] range" } }`, "caddyfile") // act and assert tester.AssertGetResponse("http://localhost:9080/internalerr", 500, "Error code is equal to 500 or in the [300..399] range") tester.AssertGetResponse("http://localhost:9080/threehundred", 301, "Error code is equal to 500 or in the [300..399] range") tester.AssertGetResponse("http://localhost:9080/private", 410, "Error in the [400 .. 499] range") } func TestHandleErrorSubHandlers(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(`{ admin localhost:2999 http_port 9080 } localhost:9080 { root * /srv file_server error /*/internalerr* "Internal Server Error" 500 handle_errors 404 { handle /en/* { respond "not found" 404 } handle /es/* { respond "no encontrado" 404 } handle { respond "default not found" } } handle_errors { handle { respond "Default error" } handle /en/* { respond "English error" } } } `, "caddyfile") // act and assert tester.AssertGetResponse("http://localhost:9080/en/notfound", 404, "not found") tester.AssertGetResponse("http://localhost:9080/es/notfound", 404, "no encontrado") tester.AssertGetResponse("http://localhost:9080/notfound", 404, "default not found") tester.AssertGetResponse("http://localhost:9080/es/internalerr", 500, "Default error") tester.AssertGetResponse("http://localhost:9080/en/internalerr", 500, "English error") } func TestInvalidSiteAddressesAsDirectives(t *testing.T) { type testCase struct { config, expectedError string } failureCases := []testCase{ { config: ` handle { file_server }`, expectedError: `Caddyfile:2: parsed 'handle' as a site address, but it is a known directive; directives must appear in a site block`, }, { config: ` reverse_proxy localhost:9000 localhost:9001 { file_server }`, expectedError: `Caddyfile:2: parsed 'reverse_proxy' as a site address, but it is a known directive; directives must appear in a site block`, }, } for _, failureCase := range failureCases { caddytest.AssertLoadError(t, failureCase.config, "caddyfile", failureCase.expectedError) } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/caddytest/integration/leafcertloaders_test.go
caddytest/integration/leafcertloaders_test.go
package integration import ( "testing" "github.com/caddyserver/caddy/v2/caddytest" ) func TestLeafCertLoaders(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(` { "admin": { "listen": "localhost:2999" }, "apps": { "http": { "http_port": 9080, "https_port": 9443, "grace_period": 1, "servers": { "srv0": { "listen": [ ":9443" ], "routes": [ { "match": [ { "host": [ "localhost" ] } ], "terminal": true } ], "tls_connection_policies": [ { "client_authentication": { "verifiers": [ { "verifier": "leaf", "leaf_certs_loaders": [ { "loader": "file", "files": ["../leafcert.pem"] }, { "loader": "folder", "folders": ["../"] }, { "loader": "storage" }, { "loader": "pem" } ] } ] } } ] } } } } }`, "json") }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/caddytest/integration/mockdns_test.go
caddytest/integration/mockdns_test.go
package integration import ( "context" "github.com/caddyserver/certmagic" "github.com/libdns/libdns" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func init() { caddy.RegisterModule(MockDNSProvider{}) } // MockDNSProvider is a mock DNS provider, for testing config with DNS modules. type MockDNSProvider struct { Argument string `json:"argument,omitempty"` // optional argument useful for testing } // CaddyModule returns the Caddy module information. func (MockDNSProvider) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "dns.providers.mock", New: func() caddy.Module { return new(MockDNSProvider) }, } } // Provision sets up the module. func (MockDNSProvider) Provision(ctx caddy.Context) error { return nil } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. func (p *MockDNSProvider) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume directive name if d.NextArg() { p.Argument = d.Val() } if d.NextArg() { return d.Errf("unexpected argument '%s'", d.Val()) } return nil } // AppendRecords appends DNS records to the zone. func (MockDNSProvider) AppendRecords(ctx context.Context, zone string, recs []libdns.Record) ([]libdns.Record, error) { return nil, nil } // DeleteRecords deletes DNS records from the zone. func (MockDNSProvider) DeleteRecords(ctx context.Context, zone string, recs []libdns.Record) ([]libdns.Record, error) { return nil, nil } // GetRecords gets DNS records from the zone. func (MockDNSProvider) GetRecords(ctx context.Context, zone string) ([]libdns.Record, error) { return nil, nil } // SetRecords sets DNS records in the zone. func (MockDNSProvider) SetRecords(ctx context.Context, zone string, recs []libdns.Record) ([]libdns.Record, error) { return nil, nil } // Interface guard var ( _ caddyfile.Unmarshaler = (*MockDNSProvider)(nil) _ certmagic.DNSProvider = (*MockDNSProvider)(nil) _ caddy.Provisioner = (*MockDNSProvider)(nil) _ caddy.Module = (*MockDNSProvider)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/caddytest/integration/pki_test.go
caddytest/integration/pki_test.go
package integration import ( "testing" "github.com/caddyserver/caddy/v2/caddytest" ) func TestLeafCertLifetimeLessThanIntermediate(t *testing.T) { caddytest.AssertLoadError(t, ` { "admin": { "disabled": true }, "apps": { "http": { "servers": { "srv0": { "listen": [ ":443" ], "routes": [ { "handle": [ { "handler": "subroute", "routes": [ { "handle": [ { "ca": "internal", "handler": "acme_server", "lifetime": 604800000000000 } ] } ] } ] } ] } } }, "pki": { "certificate_authorities": { "internal": { "install_trust": false, "intermediate_lifetime": 604800000000000, "name": "Internal CA" } } } } } `, "json", "certificate lifetime (168h0m0s) should be less than intermediate certificate lifetime (168h0m0s)") } func TestIntermediateLifetimeLessThanRoot(t *testing.T) { caddytest.AssertLoadError(t, ` { "admin": { "disabled": true }, "apps": { "http": { "servers": { "srv0": { "listen": [ ":443" ], "routes": [ { "handle": [ { "handler": "subroute", "routes": [ { "handle": [ { "ca": "internal", "handler": "acme_server", "lifetime": 2592000000000000 } ] } ] } ] } ] } } }, "pki": { "certificate_authorities": { "internal": { "install_trust": false, "intermediate_lifetime": 311040000000000000, "name": "Internal CA" } } } } } `, "json", "intermediate certificate lifetime must be less than root certificate lifetime (86400h0m0s)") }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/caddytest/integration/listener_test.go
caddytest/integration/listener_test.go
package integration import ( "bytes" "fmt" "math/rand" "net" "net/http" "strings" "testing" "github.com/caddyserver/caddy/v2/caddytest" ) func setupListenerWrapperTest(t *testing.T, handlerFunc http.HandlerFunc) *caddytest.Tester { l, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatalf("failed to listen: %s", err) } mux := http.NewServeMux() mux.Handle("/", handlerFunc) srv := &http.Server{ Handler: mux, } go srv.Serve(l) t.Cleanup(func() { _ = srv.Close() _ = l.Close() }) tester := caddytest.NewTester(t) tester.InitServer(fmt.Sprintf(` { skip_install_trust admin localhost:2999 http_port 9080 https_port 9443 local_certs servers :9443 { listener_wrappers { http_redirect tls } } } localhost { reverse_proxy %s } `, l.Addr().String()), "caddyfile") return tester } func TestHTTPRedirectWrapperWithLargeUpload(t *testing.T) { const uploadSize = (1024 * 1024) + 1 // 1 MB + 1 byte // 1 more than an MB body := make([]byte, uploadSize) rand.New(rand.NewSource(0)).Read(body) tester := setupListenerWrapperTest(t, func(writer http.ResponseWriter, request *http.Request) { buf := new(bytes.Buffer) _, err := buf.ReadFrom(request.Body) if err != nil { t.Fatalf("failed to read body: %s", err) } if !bytes.Equal(buf.Bytes(), body) { t.Fatalf("body not the same") } writer.WriteHeader(http.StatusNoContent) }) resp, err := tester.Client.Post("https://localhost:9443", "application/octet-stream", bytes.NewReader(body)) if err != nil { t.Fatalf("failed to post: %s", err) } if resp.StatusCode != http.StatusNoContent { t.Fatalf("unexpected status: %d != %d", resp.StatusCode, http.StatusNoContent) } } func TestLargeHttpRequest(t *testing.T) { tester := setupListenerWrapperTest(t, func(writer http.ResponseWriter, request *http.Request) { t.Fatal("not supposed to handle a request") }) // We never read the body in any way, set an extra long header instead. req, _ := http.NewRequest("POST", "http://localhost:9443", nil) req.Header.Set("Long-Header", strings.Repeat("X", 1024*1024)) _, err := tester.Client.Do(req) if err == nil { t.Fatal("not supposed to succeed") } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/caddytest/integration/h2listener_test.go
caddytest/integration/h2listener_test.go
package integration import ( "fmt" "net/http" "slices" "strings" "testing" "github.com/caddyserver/caddy/v2/caddytest" ) func newH2ListenerWithVersionsWithTLSTester(t *testing.T, serverVersions []string, clientVersions []string) *caddytest.Tester { const baseConfig = ` { skip_install_trust admin localhost:2999 http_port 9080 https_port 9443 servers :9443 { protocols %s } } localhost { respond "{http.request.tls.proto} {http.request.proto}" } ` tester := caddytest.NewTester(t) tester.InitServer(fmt.Sprintf(baseConfig, strings.Join(serverVersions, " ")), "caddyfile") tr := tester.Client.Transport.(*http.Transport) tr.TLSClientConfig.NextProtos = clientVersions tr.Protocols = new(http.Protocols) if slices.Contains(clientVersions, "h2") { tr.ForceAttemptHTTP2 = true tr.Protocols.SetHTTP2(true) } if !slices.Contains(clientVersions, "http/1.1") { tr.Protocols.SetHTTP1(false) } return tester } func TestH2ListenerWithTLS(t *testing.T) { tests := []struct { serverVersions []string clientVersions []string expectedBody string failed bool }{ {[]string{"h2"}, []string{"h2"}, "h2 HTTP/2.0", false}, {[]string{"h2"}, []string{"http/1.1"}, "", true}, {[]string{"h1"}, []string{"http/1.1"}, "http/1.1 HTTP/1.1", false}, {[]string{"h1"}, []string{"h2"}, "", true}, {[]string{"h2", "h1"}, []string{"h2"}, "h2 HTTP/2.0", false}, {[]string{"h2", "h1"}, []string{"http/1.1"}, "http/1.1 HTTP/1.1", false}, } for _, tc := range tests { tester := newH2ListenerWithVersionsWithTLSTester(t, tc.serverVersions, tc.clientVersions) t.Logf("running with server versions %v and client versions %v:", tc.serverVersions, tc.clientVersions) if tc.failed { resp, err := tester.Client.Get("https://localhost:9443") if err == nil { t.Errorf("unexpected response: %d", resp.StatusCode) } } else { tester.AssertGetResponse("https://localhost:9443", 200, tc.expectedBody) } } } func newH2ListenerWithVersionsWithoutTLSTester(t *testing.T, serverVersions []string, clientVersions []string) *caddytest.Tester { const baseConfig = ` { skip_install_trust admin localhost:2999 http_port 9080 servers :9080 { protocols %s } } http://localhost { respond "{http.request.proto}" } ` tester := caddytest.NewTester(t) tester.InitServer(fmt.Sprintf(baseConfig, strings.Join(serverVersions, " ")), "caddyfile") tr := tester.Client.Transport.(*http.Transport) tr.Protocols = new(http.Protocols) if slices.Contains(clientVersions, "h2c") { tr.Protocols.SetHTTP1(false) tr.Protocols.SetUnencryptedHTTP2(true) } else if slices.Contains(clientVersions, "http/1.1") { tr.Protocols.SetHTTP1(true) tr.Protocols.SetUnencryptedHTTP2(false) } return tester } func TestH2ListenerWithoutTLS(t *testing.T) { tests := []struct { serverVersions []string clientVersions []string expectedBody string failed bool }{ {[]string{"h2c"}, []string{"h2c"}, "HTTP/2.0", false}, {[]string{"h2c"}, []string{"http/1.1"}, "", true}, {[]string{"h1"}, []string{"http/1.1"}, "HTTP/1.1", false}, {[]string{"h1"}, []string{"h2c"}, "", true}, {[]string{"h2c", "h1"}, []string{"h2c"}, "HTTP/2.0", false}, {[]string{"h2c", "h1"}, []string{"http/1.1"}, "HTTP/1.1", false}, } for _, tc := range tests { tester := newH2ListenerWithVersionsWithoutTLSTester(t, tc.serverVersions, tc.clientVersions) t.Logf("running with server versions %v and client versions %v:", tc.serverVersions, tc.clientVersions) if tc.failed { resp, err := tester.Client.Get("http://localhost:9080") if err == nil { t.Errorf("unexpected response: %d", resp.StatusCode) } } else { tester.AssertGetResponse("http://localhost:9080", 200, tc.expectedBody) } } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/caddytest/integration/autohttps_test.go
caddytest/integration/autohttps_test.go
package integration import ( "net/http" "testing" "github.com/caddyserver/caddy/v2/caddytest" ) func TestAutoHTTPtoHTTPSRedirectsImplicitPort(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(` { admin localhost:2999 skip_install_trust http_port 9080 https_port 9443 } localhost respond "Yahaha! You found me!" `, "caddyfile") tester.AssertRedirect("http://localhost:9080/", "https://localhost/", http.StatusPermanentRedirect) } func TestAutoHTTPtoHTTPSRedirectsExplicitPortSameAsHTTPSPort(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(` { skip_install_trust admin localhost:2999 http_port 9080 https_port 9443 } localhost:9443 respond "Yahaha! You found me!" `, "caddyfile") tester.AssertRedirect("http://localhost:9080/", "https://localhost/", http.StatusPermanentRedirect) } func TestAutoHTTPtoHTTPSRedirectsExplicitPortDifferentFromHTTPSPort(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(` { skip_install_trust admin localhost:2999 http_port 9080 https_port 9443 } localhost:1234 respond "Yahaha! You found me!" `, "caddyfile") tester.AssertRedirect("http://localhost:9080/", "https://localhost:1234/", http.StatusPermanentRedirect) } func TestAutoHTTPRedirectsWithHTTPListenerFirstInAddresses(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(` { "admin": { "listen": "localhost:2999" }, "apps": { "http": { "http_port": 9080, "https_port": 9443, "servers": { "ingress_server": { "listen": [ ":9080", ":9443" ], "routes": [ { "match": [ { "host": ["localhost"] } ] } ] } } }, "pki": { "certificate_authorities": { "local": { "install_trust": false } } } } } `, "json") tester.AssertRedirect("http://localhost:9080/", "https://localhost/", http.StatusPermanentRedirect) } func TestAutoHTTPRedirectsInsertedBeforeUserDefinedCatchAll(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(` { skip_install_trust admin localhost:2999 http_port 9080 https_port 9443 local_certs } http://:9080 { respond "Foo" } http://baz.localhost:9080 { respond "Baz" } bar.localhost { respond "Bar" } `, "caddyfile") tester.AssertRedirect("http://bar.localhost:9080/", "https://bar.localhost/", http.StatusPermanentRedirect) tester.AssertGetResponse("http://foo.localhost:9080/", 200, "Foo") tester.AssertGetResponse("http://baz.localhost:9080/", 200, "Baz") } func TestAutoHTTPRedirectsInsertedBeforeUserDefinedCatchAllWithNoExplicitHTTPSite(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(` { skip_install_trust admin localhost:2999 http_port 9080 https_port 9443 local_certs } http://:9080 { respond "Foo" } bar.localhost { respond "Bar" } `, "caddyfile") tester.AssertRedirect("http://bar.localhost:9080/", "https://bar.localhost/", http.StatusPermanentRedirect) tester.AssertGetResponse("http://foo.localhost:9080/", 200, "Foo") tester.AssertGetResponse("http://baz.localhost:9080/", 200, "Foo") }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/caddytest/integration/acme_test.go
caddytest/integration/acme_test.go
package integration import ( "context" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "fmt" "log/slog" "net" "net/http" "strings" "testing" "github.com/mholt/acmez/v3" "github.com/mholt/acmez/v3/acme" smallstepacme "github.com/smallstep/certificates/acme" "go.uber.org/zap" "go.uber.org/zap/exp/zapslog" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddytest" ) const acmeChallengePort = 9081 // Test the basic functionality of Caddy's ACME server func TestACMEServerWithDefaults(t *testing.T) { ctx := context.Background() logger, err := zap.NewDevelopment() if err != nil { t.Error(err) return } tester := caddytest.NewTester(t) tester.InitServer(` { skip_install_trust admin localhost:2999 http_port 9080 https_port 9443 local_certs } acme.localhost { acme_server } `, "caddyfile") client := acmez.Client{ Client: &acme.Client{ Directory: "https://acme.localhost:9443/acme/local/directory", HTTPClient: tester.Client, Logger: slog.New(zapslog.NewHandler(logger.Core())), }, ChallengeSolvers: map[string]acmez.Solver{ acme.ChallengeTypeHTTP01: &naiveHTTPSolver{logger: logger}, }, } accountPrivateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { t.Errorf("generating account key: %v", err) } account := acme.Account{ Contact: []string{"mailto:you@example.com"}, TermsOfServiceAgreed: true, PrivateKey: accountPrivateKey, } account, err = client.NewAccount(ctx, account) if err != nil { t.Errorf("new account: %v", err) return } // Every certificate needs a key. certPrivateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { t.Errorf("generating certificate key: %v", err) return } certs, err := client.ObtainCertificateForSANs(ctx, account, certPrivateKey, []string{"localhost"}) if err != nil { t.Errorf("obtaining certificate: %v", err) return } // ACME servers should usually give you the entire certificate chain // in PEM format, and sometimes even alternate chains! It's up to you // which one(s) to store and use, but whatever you do, be sure to // store the certificate and key somewhere safe and secure, i.e. don't // lose them! for _, cert := range certs { t.Logf("Certificate %q:\n%s\n\n", cert.URL, cert.ChainPEM) } } func TestACMEServerWithMismatchedChallenges(t *testing.T) { ctx := context.Background() logger := caddy.Log().Named("acmez") tester := caddytest.NewTester(t) tester.InitServer(` { skip_install_trust admin localhost:2999 http_port 9080 https_port 9443 local_certs } acme.localhost { acme_server { challenges tls-alpn-01 } } `, "caddyfile") client := acmez.Client{ Client: &acme.Client{ Directory: "https://acme.localhost:9443/acme/local/directory", HTTPClient: tester.Client, Logger: slog.New(zapslog.NewHandler(logger.Core())), }, ChallengeSolvers: map[string]acmez.Solver{ acme.ChallengeTypeHTTP01: &naiveHTTPSolver{logger: logger}, }, } accountPrivateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { t.Errorf("generating account key: %v", err) } account := acme.Account{ Contact: []string{"mailto:you@example.com"}, TermsOfServiceAgreed: true, PrivateKey: accountPrivateKey, } account, err = client.NewAccount(ctx, account) if err != nil { t.Errorf("new account: %v", err) return } // Every certificate needs a key. certPrivateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { t.Errorf("generating certificate key: %v", err) return } certs, err := client.ObtainCertificateForSANs(ctx, account, certPrivateKey, []string{"localhost"}) if len(certs) > 0 { t.Errorf("expected '0' certificates, but received '%d'", len(certs)) } if err == nil { t.Error("expected errors, but received none") } const expectedErrMsg = "no solvers available for remaining challenges (configured=[http-01] offered=[tls-alpn-01] remaining=[tls-alpn-01])" if !strings.Contains(err.Error(), expectedErrMsg) { t.Errorf(`received error message does not match expectation: expected="%s" received="%s"`, expectedErrMsg, err.Error()) } } // naiveHTTPSolver is a no-op acmez.Solver for example purposes only. type naiveHTTPSolver struct { srv *http.Server logger *zap.Logger } func (s *naiveHTTPSolver) Present(ctx context.Context, challenge acme.Challenge) error { smallstepacme.InsecurePortHTTP01 = acmeChallengePort s.srv = &http.Server{ Addr: fmt.Sprintf(":%d", acmeChallengePort), Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { host, _, err := net.SplitHostPort(r.Host) if err != nil { host = r.Host } s.logger.Info("received request on challenge server", zap.String("path", r.URL.Path)) if r.Method == "GET" && r.URL.Path == challenge.HTTP01ResourcePath() && strings.EqualFold(host, challenge.Identifier.Value) { w.Header().Add("Content-Type", "text/plain") w.Write([]byte(challenge.KeyAuthorization)) r.Close = true s.logger.Info("served key authentication", zap.String("identifier", challenge.Identifier.Value), zap.String("challenge", "http-01"), zap.String("remote", r.RemoteAddr), ) } }), } l, err := net.Listen("tcp", fmt.Sprintf(":%d", acmeChallengePort)) if err != nil { return err } s.logger.Info("present challenge", zap.Any("challenge", challenge)) go s.srv.Serve(l) return nil } func (s naiveHTTPSolver) CleanUp(ctx context.Context, challenge acme.Challenge) error { smallstepacme.InsecurePortHTTP01 = 0 s.logger.Info("cleanup", zap.Any("challenge", challenge)) if s.srv != nil { s.srv.Close() } return nil }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/caddytest/integration/caddyfile_adapt_test.go
caddytest/integration/caddyfile_adapt_test.go
package integration import ( jsonMod "encoding/json" "fmt" "os" "path/filepath" "regexp" "strings" "testing" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/caddytest" _ "github.com/caddyserver/caddy/v2/internal/testmocks" ) func TestCaddyfileAdaptToJSON(t *testing.T) { // load the list of test files from the dir files, err := os.ReadDir("./caddyfile_adapt") if err != nil { t.Errorf("failed to read caddyfile_adapt dir: %s", err) } // prep a regexp to fix strings on windows winNewlines := regexp.MustCompile(`\r?\n`) for _, f := range files { if f.IsDir() { continue } filename := f.Name() // run each file as a subtest, so that we can see which one fails more easily t.Run(filename, func(t *testing.T) { // read the test file data, err := os.ReadFile("./caddyfile_adapt/" + filename) if err != nil { t.Errorf("failed to read %s dir: %s", filename, err) } // split the Caddyfile (first) and JSON (second) parts // (append newline to Caddyfile to match formatter expectations) parts := strings.Split(string(data), "----------") caddyfile, expected := strings.TrimSpace(parts[0])+"\n", strings.TrimSpace(parts[1]) // replace windows newlines in the json with unix newlines expected = winNewlines.ReplaceAllString(expected, "\n") // replace os-specific default path for file_server's hide field replacePath, _ := jsonMod.Marshal(fmt.Sprint(".", string(filepath.Separator), "Caddyfile")) expected = strings.ReplaceAll(expected, `"./Caddyfile"`, string(replacePath)) // if the expected output is JSON, compare it if len(expected) > 0 && expected[0] == '{' { ok := caddytest.CompareAdapt(t, filename, caddyfile, "caddyfile", expected) if !ok { t.Errorf("failed to adapt %s", filename) } return } // otherwise, adapt the Caddyfile and check for errors cfgAdapter := caddyconfig.GetAdapter("caddyfile") _, _, err = cfgAdapter.Adapt([]byte(caddyfile), nil) if err == nil { t.Errorf("expected error for %s but got none", filename) } else { normalizedErr := winNewlines.ReplaceAllString(err.Error(), "\n") if !strings.Contains(normalizedErr, expected) { t.Errorf("expected error for %s to contain:\n%s\nbut got:\n%s", filename, expected, normalizedErr) } } }) } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/internal/ranges.go
internal/ranges.go
package internal // PrivateRangesCIDR returns a list of private CIDR range // strings, which can be used as a configuration shortcut. func PrivateRangesCIDR() []string { return []string{ "192.168.0.0/16", "172.16.0.0/12", "10.0.0.0/8", "127.0.0.1/8", "fd00::/8", "::1", } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/internal/sockets.go
internal/sockets.go
// Copyright 2015 Matthew Holt and The Caddy 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 internal import ( "fmt" "io/fs" "strconv" "strings" ) // SplitUnixSocketPermissionsBits takes a unix socket address in the // unusual "path|bits" format (e.g. /run/caddy.sock|0222) and tries // to split it into socket path (host) and permissions bits (port). // Colons (":") can't be used as separator, as socket paths on Windows // may include a drive letter (e.g. `unix/c:\absolute\path.sock`). // Permission bits will default to 0200 if none are specified. // Throws an error, if the first carrying bit does not // include write perms (e.g. `0422` or `022`). // Symbolic permission representation (e.g. `u=w,g=w,o=w`) // is not supported and will throw an error for now! func SplitUnixSocketPermissionsBits(addr string) (path string, fileMode fs.FileMode, err error) { addrSplit := strings.SplitN(addr, "|", 2) if len(addrSplit) == 2 { // parse octal permission bit string as uint32 fileModeUInt64, err := strconv.ParseUint(addrSplit[1], 8, 32) if err != nil { return "", 0, fmt.Errorf("could not parse octal permission bits in %s: %v", addr, err) } fileMode = fs.FileMode(fileModeUInt64) // FileMode.String() returns a string like `-rwxr-xr--` for `u=rwx,g=rx,o=r` (`0754`) if string(fileMode.String()[2]) != "w" { return "", 0, fmt.Errorf("owner of the socket requires '-w-' (write, octal: '2') permissions at least; got '%s' in %s", fileMode.String()[1:4], addr) } return addrSplit[0], fileMode, nil } // default to 0200 (symbolic: `u=w,g=,o=`) // if no permission bits are specified return addr, 0o200, nil }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/internal/logbuffer.go
internal/logbuffer.go
// Copyright 2015 Matthew Holt and The Caddy 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 internal import ( "sync" "go.uber.org/zap" "go.uber.org/zap/zapcore" ) // LogBufferCore is a zapcore.Core that buffers log entries in memory. type LogBufferCore struct { mu sync.Mutex entries []zapcore.Entry fields [][]zapcore.Field level zapcore.LevelEnabler } type LogBufferCoreInterface interface { zapcore.Core FlushTo(*zap.Logger) } func NewLogBufferCore(level zapcore.LevelEnabler) *LogBufferCore { return &LogBufferCore{ level: level, } } func (c *LogBufferCore) Enabled(lvl zapcore.Level) bool { return c.level.Enabled(lvl) } func (c *LogBufferCore) With(fields []zapcore.Field) zapcore.Core { return c } func (c *LogBufferCore) Check(entry zapcore.Entry, ce *zapcore.CheckedEntry) *zapcore.CheckedEntry { if c.Enabled(entry.Level) { return ce.AddCore(entry, c) } return ce } func (c *LogBufferCore) Write(entry zapcore.Entry, fields []zapcore.Field) error { c.mu.Lock() defer c.mu.Unlock() c.entries = append(c.entries, entry) c.fields = append(c.fields, fields) return nil } func (c *LogBufferCore) Sync() error { return nil } // FlushTo flushes buffered logs to the given zap.Logger. func (c *LogBufferCore) FlushTo(logger *zap.Logger) { c.mu.Lock() defer c.mu.Unlock() for idx, entry := range c.entries { logger.WithOptions().Check(entry.Level, entry.Message).Write(c.fields[idx]...) } c.entries = nil c.fields = nil } var ( _ zapcore.Core = (*LogBufferCore)(nil) _ LogBufferCoreInterface = (*LogBufferCore)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/internal/logs.go
internal/logs.go
package internal import "fmt" // MaxSizeSubjectsListForLog returns the keys in the map as a slice of maximum length // maxToDisplay. It is useful for logging domains being managed, for example, since a // map is typically needed for quick lookup, but a slice is needed for logging, and this // can be quite a doozy since there may be a huge amount (hundreds of thousands). func MaxSizeSubjectsListForLog(subjects map[string]struct{}, maxToDisplay int) []string { numberOfNamesToDisplay := min(len(subjects), maxToDisplay) domainsToDisplay := make([]string, 0, numberOfNamesToDisplay) for domain := range subjects { domainsToDisplay = append(domainsToDisplay, domain) if len(domainsToDisplay) >= numberOfNamesToDisplay { break } } if len(subjects) > maxToDisplay { domainsToDisplay = append(domainsToDisplay, fmt.Sprintf("(and %d more...)", len(subjects)-maxToDisplay)) } return domainsToDisplay }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/internal/testmocks/dummyverifier.go
internal/testmocks/dummyverifier.go
package testmocks import ( "crypto/x509" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/modules/caddytls" ) func init() { caddy.RegisterModule(new(dummyVerifier)) } type dummyVerifier struct{} // UnmarshalCaddyfile implements caddyfile.Unmarshaler. func (dummyVerifier) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { return nil } // CaddyModule implements caddy.Module. func (dummyVerifier) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "tls.client_auth.verifier.dummy", New: func() caddy.Module { return new(dummyVerifier) }, } } // VerifyClientCertificate implements ClientCertificateVerifier. func (dummyVerifier) VerifyClientCertificate(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error { return nil } var ( _ caddy.Module = dummyVerifier{} _ caddytls.ClientCertificateVerifier = dummyVerifier{} _ caddyfile.Unmarshaler = dummyVerifier{} )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/internal/metrics/metrics.go
internal/metrics/metrics.go
package metrics import ( "net/http" "strconv" ) func SanitizeCode(s int) string { switch s { case 0, 200: return "200" default: return strconv.Itoa(s) } } // Only support the list of "regular" HTTP methods, see // https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods var methodMap = map[string]string{ "GET": http.MethodGet, "get": http.MethodGet, "HEAD": http.MethodHead, "head": http.MethodHead, "PUT": http.MethodPut, "put": http.MethodPut, "POST": http.MethodPost, "post": http.MethodPost, "DELETE": http.MethodDelete, "delete": http.MethodDelete, "CONNECT": http.MethodConnect, "connect": http.MethodConnect, "OPTIONS": http.MethodOptions, "options": http.MethodOptions, "TRACE": http.MethodTrace, "trace": http.MethodTrace, "PATCH": http.MethodPatch, "patch": http.MethodPatch, } // SanitizeMethod sanitizes the method for use as a metric label. This helps // prevent high cardinality on the method label. The name is always upper case. func SanitizeMethod(m string) string { if m, ok := methodMap[m]; ok { return m } return "OTHER" }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/internal/metrics/metrics_test.go
internal/metrics/metrics_test.go
package metrics import ( "strings" "testing" ) func TestSanitizeMethod(t *testing.T) { tests := []struct { method string expected string }{ {method: "get", expected: "GET"}, {method: "POST", expected: "POST"}, {method: "OPTIONS", expected: "OPTIONS"}, {method: "connect", expected: "CONNECT"}, {method: "trace", expected: "TRACE"}, {method: "UNKNOWN", expected: "OTHER"}, {method: strings.Repeat("ohno", 9999), expected: "OTHER"}, } for _, d := range tests { actual := SanitizeMethod(d.method) if actual != d.expected { t.Errorf("Not same: expected %#v, but got %#v", d.expected, actual) } } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/internal/filesystems/map.go
internal/filesystems/map.go
package filesystems import ( "io/fs" "strings" "sync" ) const ( DefaultFileSystemKey = "default" ) var DefaultFileSystem = &wrapperFs{key: DefaultFileSystemKey, FS: OsFS{}} // wrapperFs exists so can easily add to wrapperFs down the line type wrapperFs struct { key string fs.FS } // FileSystemMap stores a map of filesystems // the empty key will be overwritten to be the default key // it includes a default filesystem, based off the os fs type FileSystemMap struct { m sync.Map } // note that the first invocation of key cannot be called in a racy context. func (f *FileSystemMap) key(k string) string { if k == "" { k = DefaultFileSystemKey } return k } // Register will add the filesystem with key to later be retrieved // A call with a nil fs will call unregister, ensuring that a call to Default() will never be nil func (f *FileSystemMap) Register(k string, v fs.FS) { k = f.key(k) if v == nil { f.Unregister(k) return } f.m.Store(k, &wrapperFs{key: k, FS: v}) } // Unregister will remove the filesystem with key from the filesystem map // if the key is the default key, it will set the default to the osFS instead of deleting it // modules should call this on cleanup to be safe func (f *FileSystemMap) Unregister(k string) { k = f.key(k) if k == DefaultFileSystemKey { f.m.Store(k, DefaultFileSystem) } else { f.m.Delete(k) } } // Get will get a filesystem with a given key func (f *FileSystemMap) Get(k string) (v fs.FS, ok bool) { k = f.key(k) c, ok := f.m.Load(strings.TrimSpace(k)) if !ok { if k == DefaultFileSystemKey { f.m.Store(k, DefaultFileSystem) return DefaultFileSystem, true } return nil, ok } return c.(fs.FS), true } // Default will get the default filesystem in the filesystem map func (f *FileSystemMap) Default() fs.FS { val, _ := f.Get(DefaultFileSystemKey) return val }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/internal/filesystems/os.go
internal/filesystems/os.go
package filesystems import ( "io/fs" "os" "path/filepath" ) // OsFS is a simple fs.FS implementation that uses the local // file system. (We do not use os.DirFS because we do our own // rooting or path prefixing without being constrained to a single // root folder. The standard os.DirFS implementation is problematic // since roots can be dynamic in our application.) // // OsFS also implements fs.StatFS, fs.GlobFS, fs.ReadDirFS, and fs.ReadFileFS. type OsFS struct{} func (OsFS) Open(name string) (fs.File, error) { return os.Open(name) } func (OsFS) Stat(name string) (fs.FileInfo, error) { return os.Stat(name) } func (OsFS) Glob(pattern string) ([]string, error) { return filepath.Glob(pattern) } func (OsFS) ReadDir(name string) ([]fs.DirEntry, error) { return os.ReadDir(name) } func (OsFS) ReadFile(name string) ([]byte, error) { return os.ReadFile(name) } var ( _ fs.StatFS = (*OsFS)(nil) _ fs.GlobFS = (*OsFS)(nil) _ fs.ReadDirFS = (*OsFS)(nil) _ fs.ReadFileFS = (*OsFS)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/filestorage/filestorage.go
modules/filestorage/filestorage.go
// Copyright 2015 Matthew Holt and The Caddy 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 filestorage import ( "github.com/caddyserver/certmagic" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func init() { caddy.RegisterModule(FileStorage{}) } // FileStorage is a certmagic.Storage wrapper for certmagic.FileStorage. type FileStorage struct { // The base path to the folder used for storage. Root string `json:"root,omitempty"` } // CaddyModule returns the Caddy module information. func (FileStorage) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "caddy.storage.file_system", New: func() caddy.Module { return new(FileStorage) }, } } // CertMagicStorage converts s to a certmagic.Storage instance. func (s FileStorage) CertMagicStorage() (certmagic.Storage, error) { return &certmagic.FileStorage{Path: s.Root}, nil } // UnmarshalCaddyfile sets up the storage module from Caddyfile tokens. func (s *FileStorage) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { if !d.Next() { return d.Err("expected tokens") } if d.NextArg() { s.Root = d.Val() } if d.NextArg() { return d.ArgErr() } for d.NextBlock(0) { switch d.Val() { case "root": if !d.NextArg() { return d.ArgErr() } if s.Root != "" { return d.Err("root already set") } s.Root = d.Val() if d.NextArg() { return d.ArgErr() } default: return d.Errf("unrecognized parameter '%s'", d.Val()) } } if s.Root == "" { return d.Err("missing root path (to use default, omit storage config entirely)") } return nil } // Interface guards var ( _ caddy.StorageConverter = (*FileStorage)(nil) _ caddyfile.Unmarshaler = (*FileStorage)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/subroute.go
modules/caddyhttp/subroute.go
// Copyright 2015 Matthew Holt and The Caddy 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 caddyhttp import ( "fmt" "net/http" "github.com/caddyserver/caddy/v2" ) func init() { caddy.RegisterModule(Subroute{}) } // Subroute implements a handler that compiles and executes routes. // This is useful for a batch of routes that all inherit the same // matchers, or for multiple routes that should be treated as a // single route. // // You can also use subroutes to handle errors from its handlers. // First the primary routes will be executed, and if they return an // error, the errors routes will be executed; in that case, an error // is only returned to the entry point at the server if there is an // additional error returned from the errors routes. type Subroute struct { // The primary list of routes to compile and execute. Routes RouteList `json:"routes,omitempty"` // If the primary routes return an error, error handling // can be promoted to this configuration instead. Errors *HTTPErrorConfig `json:"errors,omitempty"` } // CaddyModule returns the Caddy module information. func (Subroute) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.handlers.subroute", New: func() caddy.Module { return new(Subroute) }, } } // Provision sets up subrouting. func (sr *Subroute) Provision(ctx caddy.Context) error { if sr.Routes != nil { err := sr.Routes.Provision(ctx) if err != nil { return fmt.Errorf("setting up subroutes: %v", err) } if sr.Errors != nil { err := sr.Errors.Routes.Provision(ctx) if err != nil { return fmt.Errorf("setting up error subroutes: %v", err) } } } return nil } func (sr *Subroute) ServeHTTP(w http.ResponseWriter, r *http.Request, next Handler) error { subroute := sr.Routes.Compile(next) err := subroute.ServeHTTP(w, r) if err != nil && sr.Errors != nil { r = sr.Errors.WithError(r, err) errRoute := sr.Errors.Routes.Compile(next) return errRoute.ServeHTTP(w, r) } return err } // Interface guards var ( _ caddy.Provisioner = (*Subroute)(nil) _ MiddlewareHandler = (*Subroute)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/matchers_test.go
modules/caddyhttp/matchers_test.go
// Copyright 2015 Matthew Holt and The Caddy 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 caddyhttp import ( "context" "fmt" "net/http" "net/http/httptest" "net/url" "os" "runtime" "testing" "github.com/caddyserver/caddy/v2" ) func TestHostMatcher(t *testing.T) { err := os.Setenv("GO_BENCHMARK_DOMAIN", "localhost") if err != nil { t.Errorf("error while setting up environment: %v", err) } for i, tc := range []struct { match MatchHost input string expect bool }{ { match: MatchHost{}, input: "example.com", expect: false, }, { match: MatchHost{"example.com"}, input: "example.com", expect: true, }, { match: MatchHost{"EXAMPLE.COM"}, input: "example.com", expect: true, }, { match: MatchHost{"example.com"}, input: "EXAMPLE.COM", expect: true, }, { match: MatchHost{"example.com"}, input: "foo.example.com", expect: false, }, { match: MatchHost{"example.com"}, input: "EXAMPLE.COM", expect: true, }, { match: MatchHost{"foo.example.com"}, input: "foo.example.com", expect: true, }, { match: MatchHost{"foo.example.com"}, input: "bar.example.com", expect: false, }, { match: MatchHost{"éxàmplê.com"}, input: "xn--xmpl-0na6cm.com", expect: true, }, { match: MatchHost{"*.example.com"}, input: "example.com", expect: false, }, { match: MatchHost{"*.example.com"}, input: "SUB.EXAMPLE.COM", expect: true, }, { match: MatchHost{"*.example.com"}, input: "foo.example.com", expect: true, }, { match: MatchHost{"*.example.com"}, input: "foo.bar.example.com", expect: false, }, { match: MatchHost{"*.example.com", "example.net"}, input: "example.net", expect: true, }, { match: MatchHost{"example.net", "*.example.com"}, input: "foo.example.com", expect: true, }, { match: MatchHost{"*.example.net", "*.*.example.com"}, input: "foo.bar.example.com", expect: true, }, { match: MatchHost{"*.example.net", "sub.*.example.com"}, input: "sub.foo.example.com", expect: true, }, { match: MatchHost{"*.example.net", "sub.*.example.com"}, input: "sub.foo.example.net", expect: false, }, { match: MatchHost{"www.*.*"}, input: "www.example.com", expect: true, }, { match: MatchHost{"example.com"}, input: "example.com:5555", expect: true, }, { match: MatchHost{"{env.GO_BENCHMARK_DOMAIN}"}, input: "localhost", expect: true, }, { match: MatchHost{"{env.GO_NONEXISTENT}"}, input: "localhost", expect: false, }, } { req := &http.Request{Host: tc.input} repl := caddy.NewReplacer() ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl) req = req.WithContext(ctx) if err := tc.match.Provision(caddy.Context{}); err != nil { t.Errorf("Test %d %v: provisioning failed: %v", i, tc.match, err) } actual, err := tc.match.MatchWithError(req) if err != nil { t.Errorf("Test %d %v: matching failed: %v", i, tc.match, err) } if actual != tc.expect { t.Errorf("Test %d %v: Expected %t, got %t for '%s'", i, tc.match, tc.expect, actual, tc.input) continue } } } func TestPathMatcher(t *testing.T) { for i, tc := range []struct { match MatchPath // not URI-encoded because not parsing from a URI input string // should be valid URI encoding (escaped) since it will become part of a request expect bool provisionErr bool }{ { match: MatchPath{}, input: "/", expect: false, }, { match: MatchPath{"/"}, input: "/", expect: true, }, { match: MatchPath{"/foo/bar"}, input: "/", expect: false, }, { match: MatchPath{"/foo/bar"}, input: "/foo/bar", expect: true, }, { match: MatchPath{"/foo/bar/"}, input: "/foo/bar", expect: false, }, { match: MatchPath{"/foo/bar/"}, input: "/foo/bar/", expect: true, }, { match: MatchPath{"/foo/bar/", "/other"}, input: "/other/", expect: false, }, { match: MatchPath{"/foo/bar/", "/other"}, input: "/other", expect: true, }, { match: MatchPath{"*.ext"}, input: "/foo/bar.ext", expect: true, }, { match: MatchPath{"*.php"}, input: "/index.PHP", expect: true, }, { match: MatchPath{"*.ext"}, input: "/foo/bar.ext", expect: true, }, { match: MatchPath{"/foo/*/baz"}, input: "/foo/bar/baz", expect: true, }, { match: MatchPath{"/foo/*/baz/bam"}, input: "/foo/bar/bam", expect: false, }, { match: MatchPath{"*substring*"}, input: "/foo/substring/bar.txt", expect: true, }, { match: MatchPath{"/foo"}, input: "/foo/bar", expect: false, }, { match: MatchPath{"/foo"}, input: "/foo/bar", expect: false, }, { match: MatchPath{"/foo"}, input: "/FOO", expect: true, }, { match: MatchPath{"/foo*"}, input: "/FOOOO", expect: true, }, { match: MatchPath{"/foo/bar.txt"}, input: "/foo/BAR.txt", expect: true, }, { match: MatchPath{"/foo*"}, input: "//foo/bar", expect: true, }, { match: MatchPath{"/foo"}, input: "//foo", expect: true, }, { match: MatchPath{"//foo"}, input: "/foo", expect: false, }, { match: MatchPath{"//foo"}, input: "//foo", expect: true, }, { match: MatchPath{"/foo//*"}, input: "/foo//bar", expect: true, }, { match: MatchPath{"/foo//*"}, input: "/foo/%2Fbar", expect: true, }, { match: MatchPath{"/foo/%2F*"}, input: "/foo/%2Fbar", expect: true, }, { match: MatchPath{"/foo/%2F*"}, input: "/foo//bar", expect: false, }, { match: MatchPath{"/foo//bar"}, input: "/foo//bar", expect: true, }, { match: MatchPath{"/foo/*//bar"}, input: "/foo///bar", expect: true, }, { match: MatchPath{"/foo/%*//bar"}, input: "/foo///bar", expect: true, }, { match: MatchPath{"/foo/%*//bar"}, input: "/foo//%2Fbar", expect: true, }, { match: MatchPath{"/foo*"}, input: "/%2F/foo", expect: true, }, { match: MatchPath{"*"}, input: "/", expect: true, }, { match: MatchPath{"*"}, input: "/foo/bar", expect: true, }, { match: MatchPath{"**"}, input: "/", expect: true, }, { match: MatchPath{"**"}, input: "/foo/bar", expect: true, }, // notice these next three test cases are the same normalized path but are written differently { match: MatchPath{"/%25@.txt"}, input: "/%25@.txt", expect: true, }, { match: MatchPath{"/%25@.txt"}, input: "/%25%40.txt", expect: true, }, { match: MatchPath{"/%25%40.txt"}, input: "/%25%40.txt", expect: true, }, { match: MatchPath{"/bands/*/*"}, input: "/bands/AC%2FDC/T.N.T", expect: false, // because * operates in normalized space }, { match: MatchPath{"/bands/%*/%*"}, input: "/bands/AC%2FDC/T.N.T", expect: true, }, { match: MatchPath{"/bands/%*/%*"}, input: "/bands/AC/DC/T.N.T", expect: false, }, { match: MatchPath{"/bands/%*"}, input: "/bands/AC/DC", expect: false, // not a suffix match }, { match: MatchPath{"/bands/%*"}, input: "/bands/AC%2FDC", expect: true, }, { match: MatchPath{"/foo%2fbar/baz"}, input: "/foo%2Fbar/baz", expect: true, }, { match: MatchPath{"/foo%2fbar/baz"}, input: "/foo/bar/baz", expect: false, }, { match: MatchPath{"/foo/bar/baz"}, input: "/foo%2fbar/baz", expect: true, }, } { err := tc.match.Provision(caddy.Context{}) if err == nil && tc.provisionErr { t.Errorf("Test %d %v: Expected error provisioning, but there was no error", i, tc.match) } if err != nil && !tc.provisionErr { t.Errorf("Test %d %v: Expected no error provisioning, but there was an error: %v", i, tc.match, err) } if tc.provisionErr { continue // if it's not supposed to provision properly, pointless to test it } u, err := url.ParseRequestURI(tc.input) if err != nil { t.Fatalf("Test %d (%v): Invalid request URI (should be rejected by Go's HTTP server): %v", i, tc.input, err) } req := &http.Request{URL: u} repl := caddy.NewReplacer() ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl) req = req.WithContext(ctx) actual, err := tc.match.MatchWithError(req) if err != nil { t.Errorf("Test %d %v: matching failed: %v", i, tc.match, err) } if actual != tc.expect { t.Errorf("Test %d %v: Expected %t, got %t for '%s'", i, tc.match, tc.expect, actual, tc.input) continue } } } func TestPathMatcherWindows(t *testing.T) { // only Windows has this bug where it will ignore // trailing dots and spaces in a filename if runtime.GOOS != "windows" { return } req := &http.Request{URL: &url.URL{Path: "/index.php . . .."}} repl := caddy.NewReplacer() ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl) req = req.WithContext(ctx) match := MatchPath{"*.php"} matched, err := match.MatchWithError(req) if err != nil { t.Errorf("Expected no error, but got: %v", err) } if !matched { t.Errorf("Expected to match; should ignore trailing dots and spaces") } } func TestPathREMatcher(t *testing.T) { for i, tc := range []struct { match MatchPathRE input string expect bool expectRepl map[string]string }{ { match: MatchPathRE{}, input: "/", expect: true, }, { match: MatchPathRE{MatchRegexp{Pattern: "/"}}, input: "/", expect: true, }, { match: MatchPathRE{MatchRegexp{Pattern: "^/foo"}}, input: "/foo", expect: true, }, { match: MatchPathRE{MatchRegexp{Pattern: "^/foo"}}, input: "/foo/", expect: true, }, { match: MatchPathRE{MatchRegexp{Pattern: "^/foo"}}, input: "//foo", expect: true, }, { match: MatchPathRE{MatchRegexp{Pattern: "^/foo"}}, input: "//foo/", expect: true, }, { match: MatchPathRE{MatchRegexp{Pattern: "^/foo"}}, input: "/%2F/foo/", expect: true, }, { match: MatchPathRE{MatchRegexp{Pattern: "/bar"}}, input: "/foo/", expect: false, }, { match: MatchPathRE{MatchRegexp{Pattern: "^/bar"}}, input: "/foo/bar", expect: false, }, { match: MatchPathRE{MatchRegexp{Pattern: "^/foo/(.*)/baz$", Name: "name"}}, input: "/foo/bar/baz", expect: true, expectRepl: map[string]string{"name.1": "bar"}, }, { match: MatchPathRE{MatchRegexp{Pattern: "^/foo/(?P<myparam>.*)/baz$", Name: "name"}}, input: "/foo/bar/baz", expect: true, expectRepl: map[string]string{"name.myparam": "bar"}, }, { match: MatchPathRE{MatchRegexp{Pattern: "^/%@.txt"}}, input: "/%25@.txt", expect: true, }, { match: MatchPathRE{MatchRegexp{Pattern: "^/%25@.txt"}}, input: "/%25@.txt", expect: false, }, } { // compile the regexp and validate its name err := tc.match.Provision(caddy.Context{}) if err != nil { t.Errorf("Test %d %v: Provisioning: %v", i, tc.match, err) continue } err = tc.match.Validate() if err != nil { t.Errorf("Test %d %v: Validating: %v", i, tc.match, err) continue } // set up the fake request and its Replacer u, err := url.ParseRequestURI(tc.input) if err != nil { t.Fatalf("Test %d: Bad input URI: %v", i, err) } req := &http.Request{URL: u} repl := caddy.NewReplacer() ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl) req = req.WithContext(ctx) addHTTPVarsToReplacer(repl, req, httptest.NewRecorder()) actual, err := tc.match.MatchWithError(req) if err != nil { t.Errorf("Test %d %v: matching failed: %v", i, tc.match, err) } if actual != tc.expect { t.Errorf("Test %d [%v]: Expected %t, got %t for input '%s'", i, tc.match.Pattern, tc.expect, actual, tc.input) continue } for key, expectVal := range tc.expectRepl { placeholder := fmt.Sprintf("{http.regexp.%s}", key) actualVal := repl.ReplaceAll(placeholder, "<empty>") if actualVal != expectVal { t.Errorf("Test %d [%v]: Expected placeholder {http.regexp.%s} to be '%s' but got '%s'", i, tc.match.Pattern, key, expectVal, actualVal) continue } } } } func TestHeaderMatcher(t *testing.T) { repl := caddy.NewReplacer() repl.Set("a", "foobar") for i, tc := range []struct { match MatchHeader input http.Header // make sure these are canonical cased (std lib will do that in a real request) host string expect bool }{ { match: MatchHeader{"Field": []string{"foo"}}, input: http.Header{"Field": []string{"foo"}}, expect: true, }, { match: MatchHeader{"Field": []string{"foo", "bar"}}, input: http.Header{"Field": []string{"bar"}}, expect: true, }, { match: MatchHeader{"Field": []string{"foo", "bar"}}, input: http.Header{"Alakazam": []string{"kapow"}}, expect: false, }, { match: MatchHeader{"Field": []string{"foo", "bar"}}, input: http.Header{"Field": []string{"kapow"}}, expect: false, }, { match: MatchHeader{"Field": []string{"foo", "bar"}}, input: http.Header{"Field": []string{"kapow", "foo"}}, expect: true, }, { match: MatchHeader{"Field1": []string{"foo"}, "Field2": []string{"bar"}}, input: http.Header{"Field1": []string{"foo"}, "Field2": []string{"bar"}}, expect: true, }, { match: MatchHeader{"field1": []string{"foo"}, "field2": []string{"bar"}}, input: http.Header{"Field1": []string{"foo"}, "Field2": []string{"bar"}}, expect: true, }, { match: MatchHeader{"field1": []string{"foo"}, "field2": []string{"bar"}}, input: http.Header{"Field1": []string{"foo"}, "Field2": []string{"kapow"}}, expect: false, }, { match: MatchHeader{"field1": []string{"*"}}, input: http.Header{"Field1": []string{"foo"}}, expect: true, }, { match: MatchHeader{"field1": []string{"*"}}, input: http.Header{"Field2": []string{"foo"}}, expect: false, }, { match: MatchHeader{"Field1": []string{"foo*"}}, input: http.Header{"Field1": []string{"foo"}}, expect: true, }, { match: MatchHeader{"Field1": []string{"foo*"}}, input: http.Header{"Field1": []string{"asdf", "foobar"}}, expect: true, }, { match: MatchHeader{"Field1": []string{"*bar"}}, input: http.Header{"Field1": []string{"asdf", "foobar"}}, expect: true, }, { match: MatchHeader{"host": []string{"localhost"}}, input: http.Header{}, host: "localhost", expect: true, }, { match: MatchHeader{"host": []string{"localhost"}}, input: http.Header{}, host: "caddyserver.com", expect: false, }, { match: MatchHeader{"Must-Not-Exist": nil}, input: http.Header{}, expect: true, }, { match: MatchHeader{"Must-Not-Exist": nil}, input: http.Header{"Must-Not-Exist": []string{"do not match"}}, expect: false, }, { match: MatchHeader{"Foo": []string{"{a}"}}, input: http.Header{"Foo": []string{"foobar"}}, expect: true, }, { match: MatchHeader{"Foo": []string{"{a}"}}, input: http.Header{"Foo": []string{"asdf"}}, expect: false, }, { match: MatchHeader{"Foo": []string{"{a}*"}}, input: http.Header{"Foo": []string{"foobar-baz"}}, expect: true, }, } { req := &http.Request{Header: tc.input, Host: tc.host} ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl) req = req.WithContext(ctx) actual, err := tc.match.MatchWithError(req) if err != nil { t.Errorf("Test %d %v: matching failed: %v", i, tc.match, err) } if actual != tc.expect { t.Errorf("Test %d %v: Expected %t, got %t for '%s'", i, tc.match, tc.expect, actual, tc.input) continue } } } func TestQueryMatcher(t *testing.T) { for i, tc := range []struct { scenario string match MatchQuery input string expect bool }{ { scenario: "non match against a specific value", match: MatchQuery{"debug": []string{"1"}}, input: "/", expect: false, }, { scenario: "match against a specific value", match: MatchQuery{"debug": []string{"1"}}, input: "/?debug=1", expect: true, }, { scenario: "match against a wildcard", match: MatchQuery{"debug": []string{"*"}}, input: "/?debug=something", expect: true, }, { scenario: "non match against a wildcarded", match: MatchQuery{"debug": []string{"*"}}, input: "/?other=something", expect: false, }, { scenario: "match against an empty value", match: MatchQuery{"debug": []string{""}}, input: "/?debug", expect: true, }, { scenario: "non match against an empty value", match: MatchQuery{"debug": []string{""}}, input: "/?someparam", expect: false, }, { scenario: "empty matcher value should match empty query", match: MatchQuery{}, input: "/?", expect: true, }, { scenario: "nil matcher value should NOT match a non-empty query", match: MatchQuery{}, input: "/?foo=bar", expect: false, }, { scenario: "non-nil matcher should NOT match an empty query", match: MatchQuery{"": nil}, input: "/?", expect: false, }, { scenario: "match against a placeholder value", match: MatchQuery{"debug": []string{"{http.vars.debug}"}}, input: "/?debug=1", expect: true, }, { scenario: "match against a placeholder key", match: MatchQuery{"{http.vars.key}": []string{"1"}}, input: "/?somekey=1", expect: true, }, { scenario: "do not match when not all query params are present", match: MatchQuery{"debug": []string{"1"}, "foo": []string{"bar"}}, input: "/?debug=1", expect: false, }, { scenario: "match when all query params are present", match: MatchQuery{"debug": []string{"1"}, "foo": []string{"bar"}}, input: "/?debug=1&foo=bar", expect: true, }, { scenario: "do not match when the value of a query param does not match", match: MatchQuery{"debug": []string{"1"}, "foo": []string{"bar"}}, input: "/?debug=2&foo=bar", expect: false, }, { scenario: "do not match when all the values the query params do not match", match: MatchQuery{"debug": []string{"1"}, "foo": []string{"bar"}}, input: "/?debug=2&foo=baz", expect: false, }, { scenario: "match against two values for the same key", match: MatchQuery{"debug": []string{"1"}}, input: "/?debug=1&debug=2", expect: true, }, { scenario: "match against two values for the same key", match: MatchQuery{"debug": []string{"2", "1"}}, input: "/?debug=2&debug=1", expect: true, }, } { u, _ := url.Parse(tc.input) req := &http.Request{URL: u} repl := caddy.NewReplacer() ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl) repl.Set("http.vars.debug", "1") repl.Set("http.vars.key", "somekey") req = req.WithContext(ctx) actual, err := tc.match.MatchWithError(req) if err != nil { t.Errorf("Test %d %v: matching failed: %v", i, tc.match, err) } if actual != tc.expect { t.Errorf("Test %d %v: Expected %t, got %t for '%s'", i, tc.match, tc.expect, actual, tc.input) continue } } } func TestHeaderREMatcher(t *testing.T) { for i, tc := range []struct { match MatchHeaderRE input http.Header // make sure these are canonical cased (std lib will do that in a real request) host string expect bool expectRepl map[string]string }{ { match: MatchHeaderRE{"Field": &MatchRegexp{Pattern: "foo"}}, input: http.Header{"Field": []string{"foo"}}, expect: true, }, { match: MatchHeaderRE{"Field": &MatchRegexp{Pattern: "$foo^"}}, input: http.Header{"Field": []string{"foobar"}}, expect: false, }, { match: MatchHeaderRE{"Field": &MatchRegexp{Pattern: "^foo(.*)$", Name: "name"}}, input: http.Header{"Field": []string{"foobar"}}, expect: true, expectRepl: map[string]string{"name.1": "bar"}, }, { match: MatchHeaderRE{"Field": &MatchRegexp{Pattern: "^foo.*$", Name: "name"}}, input: http.Header{"Field": []string{"barfoo", "foobar"}}, expect: true, }, { match: MatchHeaderRE{"host": &MatchRegexp{Pattern: "^localhost$", Name: "name"}}, input: http.Header{}, host: "localhost", expect: true, }, { match: MatchHeaderRE{"host": &MatchRegexp{Pattern: "^local$", Name: "name"}}, input: http.Header{}, host: "localhost", expect: false, }, } { // compile the regexp and validate its name err := tc.match.Provision(caddy.Context{}) if err != nil { t.Errorf("Test %d %v: Provisioning: %v", i, tc.match, err) continue } err = tc.match.Validate() if err != nil { t.Errorf("Test %d %v: Validating: %v", i, tc.match, err) continue } // set up the fake request and its Replacer req := &http.Request{Header: tc.input, URL: new(url.URL), Host: tc.host} repl := caddy.NewReplacer() ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl) req = req.WithContext(ctx) addHTTPVarsToReplacer(repl, req, httptest.NewRecorder()) actual, err := tc.match.MatchWithError(req) if err != nil { t.Errorf("Test %d %v: matching failed: %v", i, tc.match, err) } if actual != tc.expect { t.Errorf("Test %d [%v]: Expected %t, got %t for input '%s'", i, tc.match, tc.expect, actual, tc.input) continue } for key, expectVal := range tc.expectRepl { placeholder := fmt.Sprintf("{http.regexp.%s}", key) actualVal := repl.ReplaceAll(placeholder, "<empty>") if actualVal != expectVal { t.Errorf("Test %d [%v]: Expected placeholder {http.regexp.%s} to be '%s' but got '%s'", i, tc.match, key, expectVal, actualVal) continue } } } } func BenchmarkHeaderREMatcher(b *testing.B) { i := 0 match := MatchHeaderRE{"Field": &MatchRegexp{Pattern: "^foo(.*)$", Name: "name"}} input := http.Header{"Field": []string{"foobar"}} var host string err := match.Provision(caddy.Context{}) if err != nil { b.Errorf("Test %d %v: Provisioning: %v", i, match, err) } err = match.Validate() if err != nil { b.Errorf("Test %d %v: Validating: %v", i, match, err) } // set up the fake request and its Replacer req := &http.Request{Header: input, URL: new(url.URL), Host: host} repl := caddy.NewReplacer() ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl) req = req.WithContext(ctx) addHTTPVarsToReplacer(repl, req, httptest.NewRecorder()) for b.Loop() { match.MatchWithError(req) } } func TestVarREMatcher(t *testing.T) { for i, tc := range []struct { desc string match MatchVarsRE input VarsMiddleware expect bool expectRepl map[string]string }{ { desc: "match static value within var set by the VarsMiddleware succeeds", match: MatchVarsRE{"Var1": &MatchRegexp{Pattern: "foo"}}, input: VarsMiddleware{"Var1": "here is foo val"}, expect: true, }, { desc: "value set by VarsMiddleware not satisfying regexp matcher fails to match", match: MatchVarsRE{"Var1": &MatchRegexp{Pattern: "$foo^"}}, input: VarsMiddleware{"Var1": "foobar"}, expect: false, }, { desc: "successfully matched value is captured and its placeholder is added to replacer", match: MatchVarsRE{"Var1": &MatchRegexp{Pattern: "^foo(.*)$", Name: "name"}}, input: VarsMiddleware{"Var1": "foobar"}, expect: true, expectRepl: map[string]string{"name.1": "bar"}, }, { desc: "matching against a value of standard variables succeeds", match: MatchVarsRE{"{http.request.method}": &MatchRegexp{Pattern: "^G.[tT]$"}}, input: VarsMiddleware{}, expect: true, }, { desc: "matching against value of var set by the VarsMiddleware and referenced by its placeholder succeeds", match: MatchVarsRE{"{http.vars.Var1}": &MatchRegexp{Pattern: "[vV]ar[0-9]"}}, input: VarsMiddleware{"Var1": "var1Value"}, expect: true, }, } { t.Run(tc.desc, func(t *testing.T) { t.Parallel() // compile the regexp and validate its name err := tc.match.Provision(caddy.Context{}) if err != nil { t.Errorf("Test %d %v: Provisioning: %v", i, tc.match, err) return } err = tc.match.Validate() if err != nil { t.Errorf("Test %d %v: Validating: %v", i, tc.match, err) return } // set up the fake request and its Replacer req := &http.Request{URL: new(url.URL), Method: http.MethodGet} repl := caddy.NewReplacer() ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl) ctx = context.WithValue(ctx, VarsCtxKey, make(map[string]any)) req = req.WithContext(ctx) addHTTPVarsToReplacer(repl, req, httptest.NewRecorder()) tc.input.ServeHTTP(httptest.NewRecorder(), req, emptyHandler) actual, err := tc.match.MatchWithError(req) if err != nil { t.Errorf("Test %d %v: matching failed: %v", i, tc.match, err) } if actual != tc.expect { t.Errorf("Test %d [%v]: Expected %t, got %t for input '%s'", i, tc.match, tc.expect, actual, tc.input) return } for key, expectVal := range tc.expectRepl { placeholder := fmt.Sprintf("{http.regexp.%s}", key) actualVal := repl.ReplaceAll(placeholder, "<empty>") if actualVal != expectVal { t.Errorf("Test %d [%v]: Expected placeholder {http.regexp.%s} to be '%s' but got '%s'", i, tc.match, key, expectVal, actualVal) return } } }) } } func TestNotMatcher(t *testing.T) { for i, tc := range []struct { host, path string match MatchNot expect bool }{ { host: "example.com", path: "/", match: MatchNot{}, expect: true, }, { host: "example.com", path: "/foo", match: MatchNot{ MatcherSets: []MatcherSet{ { MatchPath{"/foo"}, }, }, }, expect: false, }, { host: "example.com", path: "/bar", match: MatchNot{ MatcherSets: []MatcherSet{ { MatchPath{"/foo"}, }, }, }, expect: true, }, { host: "example.com", path: "/bar", match: MatchNot{ MatcherSets: []MatcherSet{ { MatchPath{"/foo"}, }, { MatchHost{"example.com"}, }, }, }, expect: false, }, { host: "example.com", path: "/bar", match: MatchNot{ MatcherSets: []MatcherSet{ { MatchPath{"/bar"}, }, { MatchHost{"example.com"}, }, }, }, expect: false, }, { host: "example.com", path: "/foo", match: MatchNot{ MatcherSets: []MatcherSet{ { MatchPath{"/bar"}, }, { MatchHost{"sub.example.com"}, }, }, }, expect: true, }, { host: "example.com", path: "/foo", match: MatchNot{ MatcherSets: []MatcherSet{ { MatchPath{"/foo"}, MatchHost{"example.com"}, }, }, }, expect: false, }, { host: "example.com", path: "/foo", match: MatchNot{ MatcherSets: []MatcherSet{ { MatchPath{"/bar"}, MatchHost{"example.com"}, }, }, }, expect: true, }, } { req := &http.Request{Host: tc.host, URL: &url.URL{Path: tc.path}} repl := caddy.NewReplacer() ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl) req = req.WithContext(ctx) actual, err := tc.match.MatchWithError(req) if err != nil { t.Errorf("Test %d %v: matching failed: %v", i, tc.match, err) } if actual != tc.expect { t.Errorf("Test %d %+v: Expected %t, got %t for: host=%s path=%s'", i, tc.match, tc.expect, actual, tc.host, tc.path) continue } } } func BenchmarkLargeHostMatcher(b *testing.B) { // this benchmark simulates a large host matcher (thousands of entries) where each // value is an exact hostname (not a placeholder or wildcard) - compare the results // of this with and without the binary search (comment out the various fast path // sections in Match) to conduct experiments const n = 10000 lastHost := fmt.Sprintf("%d.example.com", n-1) req := &http.Request{Host: lastHost} repl := caddy.NewReplacer() ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl) req = req.WithContext(ctx) matcher := make(MatchHost, n) for i := 0; i < n; i++ { matcher[i] = fmt.Sprintf("%d.example.com", i) } err := matcher.Provision(caddy.Context{}) if err != nil { b.Fatal(err) } for b.Loop() { matcher.MatchWithError(req) } } func BenchmarkHostMatcherWithoutPlaceholder(b *testing.B) { req := &http.Request{Host: "localhost"} repl := caddy.NewReplacer() ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl) req = req.WithContext(ctx) match := MatchHost{"localhost"} for b.Loop() { match.MatchWithError(req) } } func BenchmarkHostMatcherWithPlaceholder(b *testing.B) { err := os.Setenv("GO_BENCHMARK_DOMAIN", "localhost") if err != nil { b.Errorf("error while setting up environment: %v", err) } req := &http.Request{Host: "localhost"} repl := caddy.NewReplacer() ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl) req = req.WithContext(ctx) match := MatchHost{"{env.GO_BENCHMARK_DOMAIN}"} for b.Loop() { match.MatchWithError(req) } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/staticresp.go
modules/caddyhttp/staticresp.go
// Copyright 2015 Matthew Holt and The Caddy 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 caddyhttp import ( "bytes" "encoding/json" "fmt" "io" "net/http" "net/textproto" "os" "slices" "strconv" "strings" "text/template" "time" "github.com/spf13/cobra" "go.uber.org/zap" caddycmd "github.com/caddyserver/caddy/v2/cmd" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func init() { caddy.RegisterModule(StaticResponse{}) caddycmd.RegisterCommand(caddycmd.Command{ Name: "respond", Usage: `[--status <code>] [--body <content>] [--listen <addr>] [--access-log] [--debug] [--header "Field: value"] <body|status>`, Short: "Simple, hard-coded HTTP responses for development and testing", Long: ` Spins up a quick-and-clean HTTP server for development and testing purposes. With no options specified, this command listens on a random available port and answers HTTP requests with an empty 200 response. The listen address can be customized with the --listen flag and will always be printed to stdout. If the listen address includes a port range, multiple servers will be started. If a final, unnamed argument is given, it will be treated as a status code (same as the --status flag) if it is a 3-digit number. Otherwise, it is used as the response body (same as the --body flag). The --status and --body flags will always override this argument (for example, to write a body that literally says "404" but with a status code of 200, do '--status 200 404'). A body may be given in 3 ways: a flag, a final (and unnamed) argument to the command, or piped to stdin (if flag and argument are unset). Limited template evaluation is supported on the body, with the following variables: {{.N}} The server number (useful if using a port range) {{.Port}} The listener port {{.Address}} The listener address (See the docs for the text/template package in the Go standard library for information about using templates: https://pkg.go.dev/text/template) Access/request logging and more verbose debug logging can also be enabled. Response headers may be added using the --header flag for each header field. `, CobraFunc: func(cmd *cobra.Command) { cmd.Flags().StringP("listen", "l", ":0", "The address to which to bind the listener") cmd.Flags().IntP("status", "s", http.StatusOK, "The response status code") cmd.Flags().StringP("body", "b", "", "The body of the HTTP response") cmd.Flags().BoolP("access-log", "", false, "Enable the access log") cmd.Flags().BoolP("debug", "v", false, "Enable more verbose debug-level logging") cmd.Flags().StringArrayP("header", "H", []string{}, "Set a header on the response (format: \"Field: value\")") cmd.RunE = caddycmd.WrapCommandFuncForCobra(cmdRespond) }, }) } // StaticResponse implements a simple responder for static responses. type StaticResponse struct { // The HTTP status code to respond with. Can be an integer or, // if needing to use a placeholder, a string. // // If the status code is 103 (Early Hints), the response headers // will be written to the client immediately, the body will be // ignored, and the next handler will be invoked. This behavior // is EXPERIMENTAL while RFC 8297 is a draft, and may be changed // or removed. StatusCode WeakString `json:"status_code,omitempty"` // Header fields to set on the response; overwrites any existing // header fields of the same names after normalization. Headers http.Header `json:"headers,omitempty"` // The response body. If non-empty, the Content-Type header may // be added automatically if it is not explicitly configured nor // already set on the response; the default value is // "text/plain; charset=utf-8" unless the body is a valid JSON object // or array, in which case the value will be "application/json". // Other than those common special cases the Content-Type header // should be set explicitly if it is desired because MIME sniffing // is disabled for safety. Body string `json:"body,omitempty"` // If true, the server will close the client's connection // after writing the response. Close bool `json:"close,omitempty"` // Immediately and forcefully closes the connection without // writing a response. Interrupts any other HTTP streams on // the same connection. Abort bool `json:"abort,omitempty"` } // CaddyModule returns the Caddy module information. func (StaticResponse) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.handlers.static_response", New: func() caddy.Module { return new(StaticResponse) }, } } // UnmarshalCaddyfile sets up the handler from Caddyfile tokens. Syntax: // // respond [<matcher>] <status>|<body> [<status>] { // body <text> // close // } // // If there is just one argument (other than the matcher), it is considered // to be a status code if it's a valid positive integer of 3 digits. func (s *StaticResponse) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume directive name args := d.RemainingArgs() switch len(args) { case 1: if len(args[0]) == 3 { if num, err := strconv.Atoi(args[0]); err == nil && num > 0 { s.StatusCode = WeakString(args[0]) break } } s.Body = args[0] case 2: s.Body = args[0] s.StatusCode = WeakString(args[1]) default: return d.ArgErr() } for d.NextBlock(0) { switch d.Val() { case "body": if s.Body != "" { return d.Err("body already specified") } if !d.AllArgs(&s.Body) { return d.ArgErr() } case "close": if s.Close { return d.Err("close already specified") } s.Close = true default: return d.Errf("unrecognized subdirective '%s'", d.Val()) } } return nil } func (s StaticResponse) ServeHTTP(w http.ResponseWriter, r *http.Request, next Handler) error { // close the connection immediately if s.Abort { panic(http.ErrAbortHandler) } // close the connection after responding if s.Close { r.Close = true w.Header().Set("Connection", "close") } repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) // set all headers for field, vals := range s.Headers { field = textproto.CanonicalMIMEHeaderKey(repl.ReplaceAll(field, "")) newVals := make([]string, len(vals)) for i := range vals { newVals[i] = repl.ReplaceAll(vals[i], "") } w.Header()[field] = newVals } // implicitly set Content-Type header if we can do so safely // (this allows templates handler to eval templates successfully // or for clients to render JSON properly which is very common) body := repl.ReplaceKnown(s.Body, "") if body != "" && w.Header().Get("Content-Type") == "" { content := strings.TrimSpace(body) if len(content) > 2 && (content[0] == '{' && content[len(content)-1] == '}' || (content[0] == '[' && content[len(content)-1] == ']')) && json.Valid([]byte(content)) { w.Header().Set("Content-Type", "application/json") } else { w.Header().Set("Content-Type", "text/plain; charset=utf-8") } } // do not allow Go to sniff the content-type, for safety if w.Header().Get("Content-Type") == "" { w.Header()["Content-Type"] = nil } // get the status code; if this handler exists in an error route, // use the recommended status code as the default; otherwise 200 statusCode := http.StatusOK if reqErr, ok := r.Context().Value(ErrorCtxKey).(error); ok { if handlerErr, ok := reqErr.(HandlerError); ok { if handlerErr.StatusCode > 0 { statusCode = handlerErr.StatusCode } } } if codeStr := s.StatusCode.String(); codeStr != "" { intVal, err := strconv.Atoi(repl.ReplaceAll(codeStr, "")) if err != nil { return Error(http.StatusInternalServerError, err) } statusCode = intVal } // write headers w.WriteHeader(statusCode) // write response body if statusCode != http.StatusEarlyHints && body != "" { fmt.Fprint(w, body) } // continue handling after Early Hints as they are not the final response if statusCode == http.StatusEarlyHints { return next.ServeHTTP(w, r) } return nil } func buildHTTPServer(i int, port uint, addr string, statusCode int, hdr http.Header, body string, accessLog bool) (*Server, error) { var handlers []json.RawMessage // response body supports a basic template; evaluate it tplCtx := struct { N int // server number Port uint // only the port Address string // listener address }{ N: i, Port: port, Address: addr, } tpl, err := template.New("body").Parse(body) if err != nil { return nil, err } buf := new(bytes.Buffer) err = tpl.Execute(buf, tplCtx) if err != nil { return nil, err } // create route with handler handler := StaticResponse{ StatusCode: WeakString(fmt.Sprintf("%d", statusCode)), Headers: hdr, Body: buf.String(), } handlers = append(handlers, caddyconfig.JSONModuleObject(handler, "handler", "static_response", nil)) route := Route{HandlersRaw: handlers} server := &Server{ Listen: []string{addr}, ReadHeaderTimeout: caddy.Duration(10 * time.Second), IdleTimeout: caddy.Duration(30 * time.Second), MaxHeaderBytes: 1024 * 10, Routes: RouteList{route}, AutoHTTPS: &AutoHTTPSConfig{DisableRedir: true}, } if accessLog { server.Logs = new(ServerLogConfig) } return server, nil } func cmdRespond(fl caddycmd.Flags) (int, error) { caddy.TrapSignals() // get flag values listen := fl.String("listen") statusCodeFl := fl.Int("status") bodyFl := fl.String("body") accessLog := fl.Bool("access-log") debug := fl.Bool("debug") arg := fl.Arg(0) if fl.NArg() > 1 { return caddy.ExitCodeFailedStartup, fmt.Errorf("too many unflagged arguments") } // prefer status and body from explicit flags statusCode, body := statusCodeFl, bodyFl // figure out if status code was explicitly specified; this lets // us set a non-zero value as the default but is a little hacky statusCodeFlagSpecified := slices.Contains(os.Args, "--status") // try to determine what kind of parameter the unnamed argument is if arg != "" { // specifying body and status flags makes the argument redundant/unused if bodyFl != "" && statusCodeFlagSpecified { return caddy.ExitCodeFailedStartup, fmt.Errorf("unflagged argument \"%s\" is overridden by flags", arg) } // if a valid 3-digit number, treat as status code; otherwise body if argInt, err := strconv.Atoi(arg); err == nil && !statusCodeFlagSpecified { if argInt >= 100 && argInt <= 999 { statusCode = argInt } } else if body == "" { body = arg } } // if we still need a body, see if stdin is being piped if body == "" { stdinInfo, err := os.Stdin.Stat() if err != nil { return caddy.ExitCodeFailedStartup, err } if stdinInfo.Mode()&os.ModeNamedPipe != 0 { bodyBytes, err := io.ReadAll(os.Stdin) if err != nil { return caddy.ExitCodeFailedStartup, err } body = string(bodyBytes) } } // build headers map headers, err := fl.GetStringArray("header") if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("invalid header flag: %v", err) } hdr := make(http.Header) for i, h := range headers { key, val, found := strings.Cut(h, ":") key, val = strings.TrimSpace(key), strings.TrimSpace(val) if !found || key == "" || val == "" { return caddy.ExitCodeFailedStartup, fmt.Errorf("header %d: invalid format \"%s\" (expecting \"Field: value\")", i, h) } hdr.Set(key, val) } // build each HTTP server httpApp := App{Servers: make(map[string]*Server)} // expand listen address, if more than one port listenAddr, err := caddy.ParseNetworkAddress(listen) if err != nil { return caddy.ExitCodeFailedStartup, err } if !listenAddr.IsUnixNetwork() && !listenAddr.IsFdNetwork() { listenAddrs := make([]string, 0, listenAddr.PortRangeSize()) for offset := uint(0); offset < listenAddr.PortRangeSize(); offset++ { listenAddrs = append(listenAddrs, listenAddr.JoinHostPort(offset)) } for i, addr := range listenAddrs { server, err := buildHTTPServer(i, listenAddr.StartPort+uint(i), addr, statusCode, hdr, body, accessLog) if err != nil { return caddy.ExitCodeFailedStartup, err } // save server httpApp.Servers[fmt.Sprintf("static%d", i)] = server } } else { server, err := buildHTTPServer(0, 0, listen, statusCode, hdr, body, accessLog) if err != nil { return caddy.ExitCodeFailedStartup, err } // save server httpApp.Servers[fmt.Sprintf("static%d", 0)] = server } // finish building the config var false bool cfg := &caddy.Config{ Admin: &caddy.AdminConfig{ Disabled: true, Config: &caddy.ConfigSettings{ Persist: &false, }, }, AppsRaw: caddy.ModuleMap{ "http": caddyconfig.JSON(httpApp, nil), }, } if debug { cfg.Logging = &caddy.Logging{ Logs: map[string]*caddy.CustomLog{ "default": {BaseLog: caddy.BaseLog{Level: zap.DebugLevel.CapitalString()}}, }, } } // run it! err = caddy.Run(cfg) if err != nil { return caddy.ExitCodeFailedStartup, err } // to print listener addresses, get the active HTTP app loadedHTTPApp, err := caddy.ActiveContext().App("http") if err != nil { return caddy.ExitCodeFailedStartup, err } // print each listener address for _, srv := range loadedHTTPApp.(*App).Servers { for _, ln := range srv.listeners { fmt.Printf("Server address: %s\n", ln.Addr()) } } select {} } // Interface guards var ( _ MiddlewareHandler = (*StaticResponse)(nil) _ caddyfile.Unmarshaler = (*StaticResponse)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/logging.go
modules/caddyhttp/logging.go
// Copyright 2015 Matthew Holt and The Caddy 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 caddyhttp import ( "context" "encoding/json" "errors" "log/slog" "net" "net/http" "strings" "sync" "go.uber.org/zap" "go.uber.org/zap/exp/zapslog" "go.uber.org/zap/zapcore" "github.com/caddyserver/caddy/v2" ) func init() { caddy.RegisterSlogHandlerFactory(func(handler slog.Handler, core zapcore.Core, moduleID string) slog.Handler { return &extraFieldsSlogHandler{defaultHandler: handler, core: core, moduleID: moduleID} }) } // ServerLogConfig describes a server's logging configuration. If // enabled without customization, all requests to this server are // logged to the default logger; logger destinations may be // customized per-request-host. type ServerLogConfig struct { // The default logger name for all logs emitted by this server for // hostnames that are not in the logger_names map. DefaultLoggerName string `json:"default_logger_name,omitempty"` // LoggerNames maps request hostnames to one or more custom logger // names. For example, a mapping of `"example.com": ["example"]` would // cause access logs from requests with a Host of example.com to be // emitted by a logger named "http.log.access.example". If there are // multiple logger names, then the log will be emitted to all of them. // If the logger name is an empty, the default logger is used, i.e. // the logger "http.log.access". // // Keys must be hostnames (without ports), and may contain wildcards // to match subdomains. The value is an array of logger names. // // For backwards compatibility, if the value is a string, it is treated // as a single-element array. LoggerNames map[string]StringArray `json:"logger_names,omitempty"` // By default, all requests to this server will be logged if // access logging is enabled. This field lists the request // hosts for which access logging should be disabled. SkipHosts []string `json:"skip_hosts,omitempty"` // If true, requests to any host not appearing in the // logger_names map will not be logged. SkipUnmappedHosts bool `json:"skip_unmapped_hosts,omitempty"` // If true, credentials that are otherwise omitted, will be logged. // The definition of credentials is defined by https://fetch.spec.whatwg.org/#credentials, // and this includes some request and response headers, i.e `Cookie`, // `Set-Cookie`, `Authorization`, and `Proxy-Authorization`. ShouldLogCredentials bool `json:"should_log_credentials,omitempty"` // Log each individual handler that is invoked. // Requires that the log emit at DEBUG level. // // NOTE: This may log the configuration of your // HTTP handler modules; do not enable this in // insecure contexts when there is sensitive // data in the configuration. // // EXPERIMENTAL: Subject to change or removal. Trace bool `json:"trace,omitempty"` } // wrapLogger wraps logger in one or more logger named // according to user preferences for the given host. func (slc ServerLogConfig) wrapLogger(logger *zap.Logger, req *http.Request) []*zap.Logger { // using the `log_name` directive or the `access_logger_names` variable, // the logger names can be overridden for the current request if names := GetVar(req.Context(), AccessLoggerNameVarKey); names != nil { if namesSlice, ok := names.([]any); ok { loggers := make([]*zap.Logger, 0, len(namesSlice)) for _, loggerName := range namesSlice { // no name, use the default logger if loggerName == "" { loggers = append(loggers, logger) continue } // make a logger with the given name loggers = append(loggers, logger.Named(loggerName.(string))) } return loggers } } // get the hostname from the request, with the port number stripped host, _, err := net.SplitHostPort(req.Host) if err != nil { host = req.Host } // get the logger names for this host from the config hosts := slc.getLoggerHosts(host) // make a list of named loggers, or the default logger loggers := make([]*zap.Logger, 0, len(hosts)) for _, loggerName := range hosts { // no name, use the default logger if loggerName == "" { loggers = append(loggers, logger) continue } // make a logger with the given name loggers = append(loggers, logger.Named(loggerName)) } return loggers } func (slc ServerLogConfig) getLoggerHosts(host string) []string { // try the exact hostname first if hosts, ok := slc.LoggerNames[host]; ok { return hosts } // try matching wildcard domains if other non-specific loggers exist labels := strings.Split(host, ".") for i := range labels { if labels[i] == "" { continue } labels[i] = "*" wildcardHost := strings.Join(labels, ".") if hosts, ok := slc.LoggerNames[wildcardHost]; ok { return hosts } } return []string{slc.DefaultLoggerName} } func (slc *ServerLogConfig) clone() *ServerLogConfig { clone := &ServerLogConfig{ DefaultLoggerName: slc.DefaultLoggerName, LoggerNames: make(map[string]StringArray), SkipHosts: append([]string{}, slc.SkipHosts...), SkipUnmappedHosts: slc.SkipUnmappedHosts, ShouldLogCredentials: slc.ShouldLogCredentials, } for k, v := range slc.LoggerNames { clone.LoggerNames[k] = append([]string{}, v...) } return clone } // StringArray is a slices of strings, but also accepts // a single string as a value when JSON unmarshaling, // converting it to a slice of one string. type StringArray []string // UnmarshalJSON satisfies json.Unmarshaler. func (sa *StringArray) UnmarshalJSON(b []byte) error { var jsonObj any err := json.Unmarshal(b, &jsonObj) if err != nil { return err } switch obj := jsonObj.(type) { case string: *sa = StringArray([]string{obj}) return nil case []any: s := make([]string, 0, len(obj)) for _, v := range obj { value, ok := v.(string) if !ok { return errors.New("unsupported type") } s = append(s, value) } *sa = StringArray(s) return nil } return errors.New("unsupported type") } // errLogValues inspects err and returns the status code // to use, the error log message, and any extra fields. // If err is a HandlerError, the returned values will // have richer information. func errLogValues(err error) (status int, msg string, fields func() []zapcore.Field) { var handlerErr HandlerError if errors.As(err, &handlerErr) { status = handlerErr.StatusCode if handlerErr.Err == nil { msg = err.Error() } else { msg = handlerErr.Err.Error() } fields = func() []zapcore.Field { return []zapcore.Field{ zap.Int("status", handlerErr.StatusCode), zap.String("err_id", handlerErr.ID), zap.String("err_trace", handlerErr.Trace), } } return status, msg, fields } fields = func() []zapcore.Field { return []zapcore.Field{ zap.Error(err), } } status = http.StatusInternalServerError msg = err.Error() return status, msg, fields } // ExtraLogFields is a list of extra fields to log with every request. type ExtraLogFields struct { fields []zapcore.Field handlers sync.Map } // Add adds a field to the list of extra fields to log. func (e *ExtraLogFields) Add(field zap.Field) { e.handlers.Clear() e.fields = append(e.fields, field) } // Set sets a field in the list of extra fields to log. // If the field already exists, it is replaced. func (e *ExtraLogFields) Set(field zap.Field) { e.handlers.Clear() for i := range e.fields { if e.fields[i].Key == field.Key { e.fields[i] = field return } } e.fields = append(e.fields, field) } func (e *ExtraLogFields) getSloggerHandler(handler *extraFieldsSlogHandler) (h slog.Handler) { if existing, ok := e.handlers.Load(handler); ok { return existing.(slog.Handler) } if handler.moduleID == "" { h = zapslog.NewHandler(handler.core.With(e.fields)) } else { h = zapslog.NewHandler(handler.core.With(e.fields), zapslog.WithName(handler.moduleID)) } if handler.group != "" { h = h.WithGroup(handler.group) } if handler.attrs != nil { h = h.WithAttrs(handler.attrs) } e.handlers.Store(handler, h) return h } const ( // Variable name used to indicate that this request // should be omitted from the access logs LogSkipVar string = "log_skip" // For adding additional fields to the access logs ExtraLogFieldsCtxKey caddy.CtxKey = "extra_log_fields" // Variable name used to indicate the logger to be used AccessLoggerNameVarKey string = "access_logger_names" ) type extraFieldsSlogHandler struct { defaultHandler slog.Handler core zapcore.Core moduleID string group string attrs []slog.Attr } func (e *extraFieldsSlogHandler) Enabled(ctx context.Context, level slog.Level) bool { return e.defaultHandler.Enabled(ctx, level) } func (e *extraFieldsSlogHandler) Handle(ctx context.Context, record slog.Record) error { if elf, ok := ctx.Value(ExtraLogFieldsCtxKey).(*ExtraLogFields); ok { return elf.getSloggerHandler(e).Handle(ctx, record) } return e.defaultHandler.Handle(ctx, record) } func (e *extraFieldsSlogHandler) WithAttrs(attrs []slog.Attr) slog.Handler { return &extraFieldsSlogHandler{ e.defaultHandler.WithAttrs(attrs), e.core, e.moduleID, e.group, append(e.attrs, attrs...), } } func (e *extraFieldsSlogHandler) WithGroup(name string) slog.Handler { return &extraFieldsSlogHandler{ e.defaultHandler.WithGroup(name), e.core, e.moduleID, name, e.attrs, } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/caddyhttp_test.go
modules/caddyhttp/caddyhttp_test.go
package caddyhttp import ( "net/url" "path/filepath" "runtime" "testing" ) func TestSanitizedPathJoin(t *testing.T) { // For reference: // %2e = . // %2f = / // %5c = \ for i, tc := range []struct { inputRoot string inputPath string expect string expectWindows string }{ { inputPath: "", expect: ".", }, { inputPath: "/", expect: ".", }, { // fileserver.MatchFile passes an inputPath of "//" for some try_files values. // See https://github.com/caddyserver/caddy/issues/6352 inputPath: "//", expect: filepath.FromSlash("./"), }, { inputPath: "/foo", expect: "foo", }, { inputPath: "/foo/", expect: filepath.FromSlash("foo/"), }, { inputPath: "/foo/bar", expect: filepath.FromSlash("foo/bar"), }, { inputRoot: "/a", inputPath: "/foo/bar", expect: filepath.FromSlash("/a/foo/bar"), }, { inputPath: "/foo/../bar", expect: "bar", }, { inputRoot: "/a/b", inputPath: "/foo/../bar", expect: filepath.FromSlash("/a/b/bar"), }, { inputRoot: "/a/b", inputPath: "/..%2fbar", expect: filepath.FromSlash("/a/b/bar"), }, { inputRoot: "/a/b", inputPath: "/%2e%2e%2fbar", expect: filepath.FromSlash("/a/b/bar"), }, { // inputPath fails the IsLocal test so only the root is returned, // but with a trailing slash since one was included in inputPath inputRoot: "/a/b", inputPath: "/%2e%2e%2f%2e%2e%2f", expect: filepath.FromSlash("/a/b/"), }, { inputRoot: "/a/b", inputPath: "/foo%2fbar", expect: filepath.FromSlash("/a/b/foo/bar"), }, { inputRoot: "/a/b", inputPath: "/foo%252fbar", expect: filepath.FromSlash("/a/b/foo%2fbar"), }, { inputRoot: "C:\\www", inputPath: "/foo/bar", expect: filepath.Join("C:\\www", "foo", "bar"), }, { inputRoot: "C:\\www", inputPath: "/D:\\foo\\bar", expect: filepath.Join("C:\\www", "D:\\foo\\bar"), expectWindows: "C:\\www", // inputPath fails IsLocal on Windows }, { inputRoot: `C:\www`, inputPath: `/..\windows\win.ini`, expect: `C:\www/..\windows\win.ini`, expectWindows: `C:\www`, }, { inputRoot: `C:\www`, inputPath: `/..\..\..\..\..\..\..\..\..\..\windows\win.ini`, expect: `C:\www/..\..\..\..\..\..\..\..\..\..\windows\win.ini`, expectWindows: `C:\www`, }, { inputRoot: `C:\www`, inputPath: `/..%5cwindows%5cwin.ini`, expect: `C:\www/..\windows\win.ini`, expectWindows: `C:\www`, }, { inputRoot: `C:\www`, inputPath: `/..%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5cwindows%5cwin.ini`, expect: `C:\www/..\..\..\..\..\..\..\..\..\..\windows\win.ini`, expectWindows: `C:\www`, }, { // https://github.com/golang/go/issues/56336#issuecomment-1416214885 inputRoot: "root", inputPath: "/a/b/../../c", expect: filepath.FromSlash("root/c"), }, } { // we don't *need* to use an actual parsed URL, but it // adds some authenticity to the tests since real-world // values will be coming in from URLs; thus, the test // corpus can contain paths as encoded by clients, which // more closely emulates the actual attack vector u, err := url.Parse("http://test:9999" + tc.inputPath) if err != nil { t.Fatalf("Test %d: invalid URL: %v", i, err) } actual := SanitizedPathJoin(tc.inputRoot, u.Path) if runtime.GOOS == "windows" && tc.expectWindows != "" { tc.expect = tc.expectWindows } if actual != tc.expect { t.Errorf("Test %d: SanitizedPathJoin('%s', '%s') => '%s' (expected '%s')", i, tc.inputRoot, tc.inputPath, actual, tc.expect) } } } func TestCleanPath(t *testing.T) { for i, tc := range []struct { input string mergeSlashes bool expect string }{ { input: "/foo", expect: "/foo", }, { input: "/foo/", expect: "/foo/", }, { input: "//foo", expect: "//foo", }, { input: "//foo", mergeSlashes: true, expect: "/foo", }, { input: "/foo//bar/", mergeSlashes: true, expect: "/foo/bar/", }, { input: "/foo/./.././bar", expect: "/bar", }, { input: "/foo//./..//./bar", expect: "/foo//bar", }, { input: "/foo///./..//./bar", expect: "/foo///bar", }, { input: "/foo///./..//.", expect: "/foo//", }, { input: "/foo//./bar", expect: "/foo//bar", }, } { actual := CleanPath(tc.input, tc.mergeSlashes) if actual != tc.expect { t.Errorf("Test %d [input='%s' mergeSlashes=%t]: Got '%s', expected '%s'", i, tc.input, tc.mergeSlashes, actual, tc.expect) } } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/metrics.go
modules/caddyhttp/metrics.go
package caddyhttp import ( "context" "errors" "net/http" "strings" "sync" "time" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/internal/metrics" ) // Metrics configures metrics observations. // EXPERIMENTAL and subject to change or removal. // // Example configuration: // // { // "apps": { // "http": { // "metrics": { // "per_host": true, // "allow_catch_all_hosts": false // }, // "servers": { // "srv0": { // "routes": [{ // "match": [{"host": ["example.com", "www.example.com"]}], // "handle": [{"handler": "static_response", "body": "Hello"}] // }] // } // } // } // } // } // // In this configuration: // - Requests to example.com and www.example.com get individual host labels // - All other hosts (e.g., attacker.com) are aggregated under "_other" label // - This prevents unlimited cardinality from arbitrary Host headers type Metrics struct { // Enable per-host metrics. Enabling this option may // incur high-memory consumption, depending on the number of hosts // managed by Caddy. // // CARDINALITY PROTECTION: To prevent unbounded cardinality attacks, // only explicitly configured hosts (via host matchers) are allowed // by default. Other hosts are aggregated under the "_other" label. // See AllowCatchAllHosts to change this behavior. PerHost bool `json:"per_host,omitempty"` // Allow metrics for catch-all hosts (hosts without explicit configuration). // When false (default), only hosts explicitly configured via host matchers // will get individual metrics labels. All other hosts will be aggregated // under the "_other" label to prevent cardinality explosion. // // This is automatically enabled for HTTPS servers (since certificates provide // some protection against unbounded cardinality), but disabled for HTTP servers // by default to prevent cardinality attacks from arbitrary Host headers. // // Set to true to allow all hosts to get individual metrics (NOT RECOMMENDED // for production environments exposed to the internet). AllowCatchAllHosts bool `json:"allow_catch_all_hosts,omitempty"` init sync.Once httpMetrics *httpMetrics allowedHosts map[string]struct{} hasHTTPSServer bool } type httpMetrics struct { requestInFlight *prometheus.GaugeVec requestCount *prometheus.CounterVec requestErrors *prometheus.CounterVec requestDuration *prometheus.HistogramVec requestSize *prometheus.HistogramVec responseSize *prometheus.HistogramVec responseDuration *prometheus.HistogramVec } func initHTTPMetrics(ctx caddy.Context, metrics *Metrics) { const ns, sub = "caddy", "http" registry := ctx.GetMetricsRegistry() basicLabels := []string{"server", "handler"} if metrics.PerHost { basicLabels = append(basicLabels, "host") } metrics.httpMetrics.requestInFlight = promauto.With(registry).NewGaugeVec(prometheus.GaugeOpts{ Namespace: ns, Subsystem: sub, Name: "requests_in_flight", Help: "Number of requests currently handled by this server.", }, basicLabels) metrics.httpMetrics.requestErrors = promauto.With(registry).NewCounterVec(prometheus.CounterOpts{ Namespace: ns, Subsystem: sub, Name: "request_errors_total", Help: "Number of requests resulting in middleware errors.", }, basicLabels) metrics.httpMetrics.requestCount = promauto.With(registry).NewCounterVec(prometheus.CounterOpts{ Namespace: ns, Subsystem: sub, Name: "requests_total", Help: "Counter of HTTP(S) requests made.", }, basicLabels) // TODO: allow these to be customized in the config durationBuckets := prometheus.DefBuckets sizeBuckets := prometheus.ExponentialBuckets(256, 4, 8) httpLabels := []string{"server", "handler", "code", "method"} if metrics.PerHost { httpLabels = append(httpLabels, "host") } metrics.httpMetrics.requestDuration = promauto.With(registry).NewHistogramVec(prometheus.HistogramOpts{ Namespace: ns, Subsystem: sub, Name: "request_duration_seconds", Help: "Histogram of round-trip request durations.", Buckets: durationBuckets, }, httpLabels) metrics.httpMetrics.requestSize = promauto.With(registry).NewHistogramVec(prometheus.HistogramOpts{ Namespace: ns, Subsystem: sub, Name: "request_size_bytes", Help: "Total size of the request. Includes body", Buckets: sizeBuckets, }, httpLabels) metrics.httpMetrics.responseSize = promauto.With(registry).NewHistogramVec(prometheus.HistogramOpts{ Namespace: ns, Subsystem: sub, Name: "response_size_bytes", Help: "Size of the returned response.", Buckets: sizeBuckets, }, httpLabels) metrics.httpMetrics.responseDuration = promauto.With(registry).NewHistogramVec(prometheus.HistogramOpts{ Namespace: ns, Subsystem: sub, Name: "response_duration_seconds", Help: "Histogram of times to first byte in response bodies.", Buckets: durationBuckets, }, httpLabels) } // scanConfigForHosts scans the HTTP app configuration to build a set of allowed hosts // for metrics collection, similar to how auto-HTTPS scans for domain names. func (m *Metrics) scanConfigForHosts(app *App) { if !m.PerHost { return } m.allowedHosts = make(map[string]struct{}) m.hasHTTPSServer = false for _, srv := range app.Servers { // Check if this server has TLS enabled serverHasTLS := len(srv.TLSConnPolicies) > 0 if serverHasTLS { m.hasHTTPSServer = true } // Collect hosts from route matchers for _, route := range srv.Routes { for _, matcherSet := range route.MatcherSets { for _, matcher := range matcherSet { if hm, ok := matcher.(*MatchHost); ok { for _, host := range *hm { // Only allow non-fuzzy hosts to prevent unbounded cardinality if !hm.fuzzy(host) { m.allowedHosts[strings.ToLower(host)] = struct{}{} } } } } } } } } // shouldAllowHostMetrics determines if metrics should be collected for the given host. // This implements the cardinality protection by only allowing metrics for: // 1. Explicitly configured hosts // 2. Catch-all requests on HTTPS servers (if AllowCatchAllHosts is true or auto-enabled) // 3. Catch-all requests on HTTP servers only if explicitly allowed func (m *Metrics) shouldAllowHostMetrics(host string, isHTTPS bool) bool { if !m.PerHost { return true // host won't be used in labels anyway } normalizedHost := strings.ToLower(host) // Always allow explicitly configured hosts if _, exists := m.allowedHosts[normalizedHost]; exists { return true } // For catch-all requests (not in allowed hosts) allowCatchAll := m.AllowCatchAllHosts || (isHTTPS && m.hasHTTPSServer) return allowCatchAll } // serverNameFromContext extracts the current server name from the context. // Returns "UNKNOWN" if none is available (should probably never happen). func serverNameFromContext(ctx context.Context) string { srv, ok := ctx.Value(ServerCtxKey).(*Server) if !ok || srv == nil || srv.name == "" { return "UNKNOWN" } return srv.name } type metricsInstrumentedHandler struct { handler string mh MiddlewareHandler metrics *Metrics } func newMetricsInstrumentedHandler(ctx caddy.Context, handler string, mh MiddlewareHandler, metrics *Metrics) *metricsInstrumentedHandler { metrics.init.Do(func() { initHTTPMetrics(ctx, metrics) }) return &metricsInstrumentedHandler{handler, mh, metrics} } func (h *metricsInstrumentedHandler) ServeHTTP(w http.ResponseWriter, r *http.Request, next Handler) error { server := serverNameFromContext(r.Context()) labels := prometheus.Labels{"server": server, "handler": h.handler} method := metrics.SanitizeMethod(r.Method) // the "code" value is set later, but initialized here to eliminate the possibility // of a panic statusLabels := prometheus.Labels{"server": server, "handler": h.handler, "method": method, "code": ""} // Determine if this is an HTTPS request isHTTPS := r.TLS != nil if h.metrics.PerHost { // Apply cardinality protection for host metrics if h.metrics.shouldAllowHostMetrics(r.Host, isHTTPS) { labels["host"] = strings.ToLower(r.Host) statusLabels["host"] = strings.ToLower(r.Host) } else { // Use a catch-all label for unallowed hosts to prevent cardinality explosion labels["host"] = "_other" statusLabels["host"] = "_other" } } inFlight := h.metrics.httpMetrics.requestInFlight.With(labels) inFlight.Inc() defer inFlight.Dec() start := time.Now() // This is a _bit_ of a hack - it depends on the ShouldBufferFunc always // being called when the headers are written. // Effectively the same behaviour as promhttp.InstrumentHandlerTimeToWriteHeader. writeHeaderRecorder := ShouldBufferFunc(func(status int, header http.Header) bool { statusLabels["code"] = metrics.SanitizeCode(status) ttfb := time.Since(start).Seconds() h.metrics.httpMetrics.responseDuration.With(statusLabels).Observe(ttfb) return false }) wrec := NewResponseRecorder(w, nil, writeHeaderRecorder) err := h.mh.ServeHTTP(wrec, r, next) dur := time.Since(start).Seconds() h.metrics.httpMetrics.requestCount.With(labels).Inc() observeRequest := func(status int) { // If the code hasn't been set yet, and we didn't encounter an error, we're // probably falling through with an empty handler. if statusLabels["code"] == "" { // we still sanitize it, even though it's likely to be 0. A 200 is // returned on fallthrough so we want to reflect that. statusLabels["code"] = metrics.SanitizeCode(status) } h.metrics.httpMetrics.requestDuration.With(statusLabels).Observe(dur) h.metrics.httpMetrics.requestSize.With(statusLabels).Observe(float64(computeApproximateRequestSize(r))) h.metrics.httpMetrics.responseSize.With(statusLabels).Observe(float64(wrec.Size())) } if err != nil { var handlerErr HandlerError if errors.As(err, &handlerErr) { observeRequest(handlerErr.StatusCode) } h.metrics.httpMetrics.requestErrors.With(labels).Inc() return err } observeRequest(wrec.Status()) return nil } // taken from https://github.com/prometheus/client_golang/blob/6007b2b5cae01203111de55f753e76d8dac1f529/prometheus/promhttp/instrument_server.go#L298 func computeApproximateRequestSize(r *http.Request) int { s := 0 if r.URL != nil { s += len(r.URL.String()) } s += len(r.Method) s += len(r.Proto) for name, values := range r.Header { s += len(name) for _, value := range values { s += len(value) } } s += len(r.Host) // N.B. r.Form and r.MultipartForm are assumed to be included in r.URL. if r.ContentLength != -1 { s += int(r.ContentLength) } return s }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/replacer.go
modules/caddyhttp/replacer.go
// Copyright 2015 Matthew Holt and The Caddy 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 caddyhttp import ( "bytes" "context" "crypto/ecdsa" "crypto/ed25519" "crypto/rsa" "crypto/sha256" "crypto/tls" "crypto/x509" "encoding/asn1" "encoding/base64" "encoding/pem" "fmt" "io" "net" "net/http" "net/netip" "net/textproto" "net/url" "path" "strconv" "strings" "time" "github.com/google/uuid" "go.uber.org/zap" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddytls" ) // NewTestReplacer creates a replacer for an http.Request // for use in tests that are not in this package func NewTestReplacer(req *http.Request) *caddy.Replacer { repl := caddy.NewReplacer() ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl) *req = *req.WithContext(ctx) addHTTPVarsToReplacer(repl, req, nil) return repl } func addHTTPVarsToReplacer(repl *caddy.Replacer, req *http.Request, w http.ResponseWriter) { SetVar(req.Context(), "start_time", time.Now()) SetVar(req.Context(), "uuid", new(requestID)) httpVars := func(key string) (any, bool) { if req != nil { // query string parameters if strings.HasPrefix(key, reqURIQueryReplPrefix) { vals := req.URL.Query()[key[len(reqURIQueryReplPrefix):]] // always return true, since the query param might // be present only in some requests return strings.Join(vals, ","), true } // request header fields if strings.HasPrefix(key, reqHeaderReplPrefix) { field := key[len(reqHeaderReplPrefix):] vals := req.Header[textproto.CanonicalMIMEHeaderKey(field)] // always return true, since the header field might // be present only in some requests return strings.Join(vals, ","), true } // cookies if strings.HasPrefix(key, reqCookieReplPrefix) { name := key[len(reqCookieReplPrefix):] for _, cookie := range req.Cookies() { if strings.EqualFold(name, cookie.Name) { // always return true, since the cookie might // be present only in some requests return cookie.Value, true } } } // http.request.tls.* if strings.HasPrefix(key, reqTLSReplPrefix) { return getReqTLSReplacement(req, key) } switch key { case "http.request.method": return req.Method, true case "http.request.scheme": if req.TLS != nil { return "https", true } return "http", true case "http.request.proto": return req.Proto, true case "http.request.host": host, _, err := net.SplitHostPort(req.Host) if err != nil { return req.Host, true // OK; there probably was no port } return host, true case "http.request.port": _, port, _ := net.SplitHostPort(req.Host) if portNum, err := strconv.Atoi(port); err == nil { return portNum, true } return port, true case "http.request.hostport": return req.Host, true case "http.request.local": localAddr, _ := req.Context().Value(http.LocalAddrContextKey).(net.Addr) return localAddr.String(), true case "http.request.local.host": localAddr, _ := req.Context().Value(http.LocalAddrContextKey).(net.Addr) host, _, err := net.SplitHostPort(localAddr.String()) if err != nil { // localAddr is host:port for tcp and udp sockets and /unix/socket.path // for unix sockets. net.SplitHostPort only operates on tcp and udp sockets, // not unix sockets and will fail with the latter. // We assume when net.SplitHostPort fails, localAddr is a unix socket and thus // already "split" and save to return. return localAddr, true } return host, true case "http.request.local.port": localAddr, _ := req.Context().Value(http.LocalAddrContextKey).(net.Addr) _, port, _ := net.SplitHostPort(localAddr.String()) if portNum, err := strconv.Atoi(port); err == nil { return portNum, true } return port, true case "http.request.remote": if req.TLS != nil && !req.TLS.HandshakeComplete { // without a complete handshake (QUIC "early data") we can't trust the remote IP address to not be spoofed return nil, true } return req.RemoteAddr, true case "http.request.remote.host": if req.TLS != nil && !req.TLS.HandshakeComplete { // without a complete handshake (QUIC "early data") we can't trust the remote IP address to not be spoofed return nil, true } host, _, err := net.SplitHostPort(req.RemoteAddr) if err != nil { // req.RemoteAddr is host:port for tcp and udp sockets and /unix/socket.path // for unix sockets. net.SplitHostPort only operates on tcp and udp sockets, // not unix sockets and will fail with the latter. // We assume when net.SplitHostPort fails, req.RemoteAddr is a unix socket // and thus already "split" and save to return. return req.RemoteAddr, true } return host, true case "http.request.remote.port": _, port, _ := net.SplitHostPort(req.RemoteAddr) if portNum, err := strconv.Atoi(port); err == nil { return portNum, true } return port, true // current URI, including any internal rewrites case "http.request.uri": return req.URL.RequestURI(), true case "http.request.uri_escaped": return url.QueryEscape(req.URL.RequestURI()), true case "http.request.uri.path": return req.URL.Path, true case "http.request.uri.path_escaped": return url.QueryEscape(req.URL.Path), true case "http.request.uri.path.file": _, file := path.Split(req.URL.Path) return file, true case "http.request.uri.path.dir": dir, _ := path.Split(req.URL.Path) return dir, true case "http.request.uri.path.file.base": return strings.TrimSuffix(path.Base(req.URL.Path), path.Ext(req.URL.Path)), true case "http.request.uri.path.file.ext": return path.Ext(req.URL.Path), true case "http.request.uri.query": return req.URL.RawQuery, true case "http.request.uri.query_escaped": return url.QueryEscape(req.URL.RawQuery), true case "http.request.uri.prefixed_query": if req.URL.RawQuery == "" { return "", true } return "?" + req.URL.RawQuery, true case "http.request.duration": start := GetVar(req.Context(), "start_time").(time.Time) return time.Since(start), true case "http.request.duration_ms": start := GetVar(req.Context(), "start_time").(time.Time) return time.Since(start).Seconds() * 1e3, true // multiply seconds to preserve decimal (see #4666) case "http.request.uuid": // fetch the UUID for this request id := GetVar(req.Context(), "uuid").(*requestID) // set it to this request's access log extra := req.Context().Value(ExtraLogFieldsCtxKey).(*ExtraLogFields) extra.Set(zap.String("uuid", id.String())) return id.String(), true case "http.request.body": if req.Body == nil { return "", true } // normally net/http will close the body for us, but since we // are replacing it with a fake one, we have to ensure we close // the real body ourselves when we're done defer req.Body.Close() // read the request body into a buffer (can't pool because we // don't know its lifetime and would have to make a copy anyway) buf := new(bytes.Buffer) _, _ = io.Copy(buf, req.Body) // can't handle error, so just ignore it req.Body = io.NopCloser(buf) // replace real body with buffered data return buf.String(), true case "http.request.body_base64": if req.Body == nil { return "", true } // normally net/http will close the body for us, but since we // are replacing it with a fake one, we have to ensure we close // the real body ourselves when we're done defer req.Body.Close() // read the request body into a buffer (can't pool because we // don't know its lifetime and would have to make a copy anyway) buf := new(bytes.Buffer) _, _ = io.Copy(buf, req.Body) // can't handle error, so just ignore it req.Body = io.NopCloser(buf) // replace real body with buffered data return base64.StdEncoding.EncodeToString(buf.Bytes()), true // original request, before any internal changes case "http.request.orig_method": or, _ := req.Context().Value(OriginalRequestCtxKey).(http.Request) return or.Method, true case "http.request.orig_uri": or, _ := req.Context().Value(OriginalRequestCtxKey).(http.Request) return or.RequestURI, true case "http.request.orig_uri.path": or, _ := req.Context().Value(OriginalRequestCtxKey).(http.Request) return or.URL.Path, true case "http.request.orig_uri.path.file": or, _ := req.Context().Value(OriginalRequestCtxKey).(http.Request) _, file := path.Split(or.URL.Path) return file, true case "http.request.orig_uri.path.dir": or, _ := req.Context().Value(OriginalRequestCtxKey).(http.Request) dir, _ := path.Split(or.URL.Path) return dir, true case "http.request.orig_uri.query": or, _ := req.Context().Value(OriginalRequestCtxKey).(http.Request) return or.URL.RawQuery, true case "http.request.orig_uri.prefixed_query": or, _ := req.Context().Value(OriginalRequestCtxKey).(http.Request) if or.URL.RawQuery == "" { return "", true } return "?" + or.URL.RawQuery, true } // remote IP range/prefix (e.g. keep top 24 bits of 1.2.3.4 => "1.2.3.0/24") // syntax: "/V4,V6" where V4 = IPv4 bits, and V6 = IPv6 bits; if no comma, then same bit length used for both // (EXPERIMENTAL) if strings.HasPrefix(key, "http.request.remote.host/") { host, _, err := net.SplitHostPort(req.RemoteAddr) if err != nil { host = req.RemoteAddr // assume no port, I guess? } addr, err := netip.ParseAddr(host) if err != nil { return host, true // not an IP address } // extract the bits from the end of the placeholder (start after "/") then split on "," bitsBoth := key[strings.Index(key, "/")+1:] ipv4BitsStr, ipv6BitsStr, cutOK := strings.Cut(bitsBoth, ",") bitsStr := ipv4BitsStr if addr.Is6() && cutOK { bitsStr = ipv6BitsStr } // convert to integer then compute prefix bits, err := strconv.Atoi(bitsStr) if err != nil { return "", true } prefix, err := addr.Prefix(bits) if err != nil { return "", true } return prefix.String(), true } // hostname labels (case insensitive, so normalize to lowercase) if strings.HasPrefix(key, reqHostLabelsReplPrefix) { idxStr := key[len(reqHostLabelsReplPrefix):] idx, err := strconv.Atoi(idxStr) if err != nil || idx < 0 { return "", false } reqHost, _, err := net.SplitHostPort(req.Host) if err != nil { reqHost = req.Host // OK; assume there was no port } hostLabels := strings.Split(reqHost, ".") if idx >= len(hostLabels) { return "", true } return strings.ToLower(hostLabels[len(hostLabels)-idx-1]), true } // path parts if strings.HasPrefix(key, reqURIPathReplPrefix) { idxStr := key[len(reqURIPathReplPrefix):] idx, err := strconv.Atoi(idxStr) if err != nil { return "", false } pathParts := strings.Split(req.URL.Path, "/") if len(pathParts) > 0 && pathParts[0] == "" { pathParts = pathParts[1:] } if idx < 0 { return "", false } if idx >= len(pathParts) { return "", true } return pathParts[idx], true } // orig uri path parts if strings.HasPrefix(key, reqOrigURIPathReplPrefix) { idxStr := key[len(reqOrigURIPathReplPrefix):] idx, err := strconv.Atoi(idxStr) if err != nil { return "", false } or, _ := req.Context().Value(OriginalRequestCtxKey).(http.Request) pathParts := strings.Split(or.URL.Path, "/") if len(pathParts) > 0 && pathParts[0] == "" { pathParts = pathParts[1:] } if idx < 0 { return "", false } if idx >= len(pathParts) { return "", true } return pathParts[idx], true } // middleware variables if strings.HasPrefix(key, varsReplPrefix) { varName := key[len(varsReplPrefix):] raw := GetVar(req.Context(), varName) // variables can be dynamic, so always return true // even when it may not be set; treat as empty then return raw, true } } if w != nil { // response header fields if strings.HasPrefix(key, respHeaderReplPrefix) { field := key[len(respHeaderReplPrefix):] vals := w.Header()[textproto.CanonicalMIMEHeaderKey(field)] // always return true, since the header field might // be present only in some responses return strings.Join(vals, ","), true } } switch key { case "http.shutting_down": server := req.Context().Value(ServerCtxKey).(*Server) server.shutdownAtMu.RLock() defer server.shutdownAtMu.RUnlock() return !server.shutdownAt.IsZero(), true case "http.time_until_shutdown": server := req.Context().Value(ServerCtxKey).(*Server) server.shutdownAtMu.RLock() defer server.shutdownAtMu.RUnlock() if server.shutdownAt.IsZero() { return nil, true } return time.Until(server.shutdownAt), true } return nil, false } repl.Map(httpVars) } func getReqTLSReplacement(req *http.Request, key string) (any, bool) { if req == nil || req.TLS == nil { return nil, false } if len(key) < len(reqTLSReplPrefix) { return nil, false } field := strings.ToLower(key[len(reqTLSReplPrefix):]) if strings.HasPrefix(field, "client.") { cert := getTLSPeerCert(req.TLS) if cert == nil { return nil, false } // subject alternate names (SANs) if strings.HasPrefix(field, "client.san.") { field = field[len("client.san."):] var fieldName string var fieldValue any switch { case strings.HasPrefix(field, "dns_names"): fieldName = "dns_names" fieldValue = cert.DNSNames case strings.HasPrefix(field, "emails"): fieldName = "emails" fieldValue = cert.EmailAddresses case strings.HasPrefix(field, "ips"): fieldName = "ips" fieldValue = cert.IPAddresses case strings.HasPrefix(field, "uris"): fieldName = "uris" fieldValue = cert.URIs default: return nil, false } field = field[len(fieldName):] // if no index was specified, return the whole list if field == "" { return fieldValue, true } if len(field) < 2 || field[0] != '.' { return nil, false } field = field[1:] // trim '.' between field name and index // get the numeric index idx, err := strconv.Atoi(field) if err != nil || idx < 0 { return nil, false } // access the indexed element and return it switch v := fieldValue.(type) { case []string: if idx >= len(v) { return nil, true } return v[idx], true case []net.IP: if idx >= len(v) { return nil, true } return v[idx], true case []*url.URL: if idx >= len(v) { return nil, true } return v[idx], true } } switch field { case "client.fingerprint": return fmt.Sprintf("%x", sha256.Sum256(cert.Raw)), true case "client.public_key", "client.public_key_sha256": if cert.PublicKey == nil { return nil, true } pubKeyBytes, err := marshalPublicKey(cert.PublicKey) if err != nil { return nil, true } if strings.HasSuffix(field, "_sha256") { return fmt.Sprintf("%x", sha256.Sum256(pubKeyBytes)), true } return fmt.Sprintf("%x", pubKeyBytes), true case "client.issuer": return cert.Issuer, true case "client.serial": return cert.SerialNumber, true case "client.subject": return cert.Subject, true case "client.certificate_pem": block := pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw} return pem.EncodeToMemory(&block), true case "client.certificate_der_base64": return base64.StdEncoding.EncodeToString(cert.Raw), true default: return nil, false } } switch field { case "version": return caddytls.ProtocolName(req.TLS.Version), true case "cipher_suite": return tls.CipherSuiteName(req.TLS.CipherSuite), true case "resumed": return req.TLS.DidResume, true case "proto": return req.TLS.NegotiatedProtocol, true case "proto_mutual": // req.TLS.NegotiatedProtocolIsMutual is deprecated - it's always true. return true, true case "server_name": return req.TLS.ServerName, true case "ech": return req.TLS.ECHAccepted, true } return nil, false } // marshalPublicKey returns the byte encoding of pubKey. func marshalPublicKey(pubKey any) ([]byte, error) { switch key := pubKey.(type) { case *rsa.PublicKey: return asn1.Marshal(key) case *ecdsa.PublicKey: e, err := key.ECDH() if err != nil { return nil, err } return e.Bytes(), nil case ed25519.PublicKey: return key, nil } return nil, fmt.Errorf("unrecognized public key type: %T", pubKey) } // getTLSPeerCert retrieves the first peer certificate from a TLS session. // Returns nil if no peer cert is in use. func getTLSPeerCert(cs *tls.ConnectionState) *x509.Certificate { if len(cs.PeerCertificates) == 0 { return nil } return cs.PeerCertificates[0] } type requestID struct { value string } // Lazy generates UUID string or return cached value if present func (rid *requestID) String() string { if rid.value == "" { if id, err := uuid.NewRandom(); err == nil { rid.value = id.String() } } return rid.value } const ( reqCookieReplPrefix = "http.request.cookie." reqHeaderReplPrefix = "http.request.header." reqHostLabelsReplPrefix = "http.request.host.labels." reqTLSReplPrefix = "http.request.tls." reqURIPathReplPrefix = "http.request.uri.path." reqURIQueryReplPrefix = "http.request.uri.query." respHeaderReplPrefix = "http.response.header." varsReplPrefix = "http.vars." reqOrigURIPathReplPrefix = "http.request.orig_uri.path." )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/caddyhttp.go
modules/caddyhttp/caddyhttp.go
// Copyright 2015 Matthew Holt and The Caddy 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 caddyhttp import ( "bytes" "encoding/json" "io" "net" "net/http" "path" "path/filepath" "strconv" "strings" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func init() { caddy.RegisterModule(tlsPlaceholderWrapper{}) } // RequestMatcher is a type that can match to a request. // A route matcher MUST NOT modify the request, with the // only exception being its context. // // Deprecated: Matchers should now implement RequestMatcherWithError. // You may remove any interface guards for RequestMatcher // but keep your Match() methods for backwards compatibility. type RequestMatcher interface { Match(*http.Request) bool } // RequestMatcherWithError is like RequestMatcher but can return an error. // An error during matching will abort the request middleware chain and // invoke the error middleware chain. // // This will eventually replace RequestMatcher. Matcher modules // should implement both interfaces, and once all modules have // been updated to use RequestMatcherWithError, the RequestMatcher // interface may eventually be dropped. type RequestMatcherWithError interface { MatchWithError(*http.Request) (bool, error) } // Handler is like http.Handler except ServeHTTP may return an error. // // If any handler encounters an error, it should be returned for proper // handling. Return values should be propagated down the middleware chain // by returning it unchanged. Returned errors should not be re-wrapped // if they are already HandlerError values. type Handler interface { ServeHTTP(http.ResponseWriter, *http.Request) error } // HandlerFunc is a convenience type like http.HandlerFunc. type HandlerFunc func(http.ResponseWriter, *http.Request) error // ServeHTTP implements the Handler interface. func (f HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) error { return f(w, r) } // Middleware chains one Handler to the next by being passed // the next Handler in the chain. type Middleware func(Handler) Handler // MiddlewareHandler is like Handler except it takes as a third // argument the next handler in the chain. The next handler will // never be nil, but may be a no-op handler if this is the last // handler in the chain. Handlers which act as middleware should // call the next handler's ServeHTTP method so as to propagate // the request down the chain properly. Handlers which act as // responders (content origins) need not invoke the next handler, // since the last handler in the chain should be the first to // write the response. type MiddlewareHandler interface { ServeHTTP(http.ResponseWriter, *http.Request, Handler) error } // emptyHandler is used as a no-op handler. var emptyHandler Handler = HandlerFunc(func(_ http.ResponseWriter, req *http.Request) error { SetVar(req.Context(), "unhandled", true) return nil }) // An implicit suffix middleware that, if reached, sets the StatusCode to the // error stored in the ErrorCtxKey. This is to prevent situations where the // Error chain does not actually handle the error (for instance, it matches only // on some errors). See #3053 var errorEmptyHandler Handler = HandlerFunc(func(w http.ResponseWriter, r *http.Request) error { httpError := r.Context().Value(ErrorCtxKey) if handlerError, ok := httpError.(HandlerError); ok { w.WriteHeader(handlerError.StatusCode) } else { w.WriteHeader(http.StatusInternalServerError) } return nil }) // ResponseHandler pairs a response matcher with custom handling // logic. Either the status code can be changed to something else // while using the original response body, or, if a status code // is not set, it can execute a custom route list; this is useful // for executing handler routes based on the properties of an HTTP // response that has not been written out to the client yet. // // To use this type, provision it at module load time, then when // ready to use, match the response against its matcher; if it // matches (or doesn't have a matcher), change the status code on // the response if configured; otherwise invoke the routes by // calling `rh.Routes.Compile(next).ServeHTTP(rw, req)` (or similar). type ResponseHandler struct { // The response matcher for this handler. If empty/nil, // it always matches. Match *ResponseMatcher `json:"match,omitempty"` // To write the original response body but with a different // status code, set this field to the desired status code. // If set, this takes priority over routes. StatusCode WeakString `json:"status_code,omitempty"` // The list of HTTP routes to execute if no status code is // specified. If evaluated, the original response body // will not be written. Routes RouteList `json:"routes,omitempty"` } // Provision sets up the routes in rh. func (rh *ResponseHandler) Provision(ctx caddy.Context) error { if rh.Routes != nil { err := rh.Routes.Provision(ctx) if err != nil { return err } } return nil } // WeakString is a type that unmarshals any JSON value // as a string literal, with the following exceptions: // // 1. actual string values are decoded as strings; and // 2. null is decoded as empty string; // // and provides methods for getting the value as various // primitive types. However, using this type removes any // type safety as far as deserializing JSON is concerned. type WeakString string // UnmarshalJSON satisfies json.Unmarshaler according to // this type's documentation. func (ws *WeakString) UnmarshalJSON(b []byte) error { if len(b) == 0 { return io.EOF } if b[0] == byte('"') && b[len(b)-1] == byte('"') { var s string err := json.Unmarshal(b, &s) if err != nil { return err } *ws = WeakString(s) return nil } if bytes.Equal(b, []byte("null")) { return nil } *ws = WeakString(b) return nil } // MarshalJSON marshals was a boolean if true or false, // a number if an integer, or a string otherwise. func (ws WeakString) MarshalJSON() ([]byte, error) { if ws == "true" { return []byte("true"), nil } if ws == "false" { return []byte("false"), nil } if num, err := strconv.Atoi(string(ws)); err == nil { return json.Marshal(num) } return json.Marshal(string(ws)) } // Int returns ws as an integer. If ws is not an // integer, 0 is returned. func (ws WeakString) Int() int { num, _ := strconv.Atoi(string(ws)) return num } // Float64 returns ws as a float64. If ws is not a // float value, the zero value is returned. func (ws WeakString) Float64() float64 { num, _ := strconv.ParseFloat(string(ws), 64) return num } // Bool returns ws as a boolean. If ws is not a // boolean, false is returned. func (ws WeakString) Bool() bool { return string(ws) == "true" } // String returns ws as a string. func (ws WeakString) String() string { return string(ws) } // StatusCodeMatches returns true if a real HTTP status code matches // the configured status code, which may be either a real HTTP status // code or an integer representing a class of codes (e.g. 4 for all // 4xx statuses). func StatusCodeMatches(actual, configured int) bool { if actual == configured { return true } if configured < 100 && actual >= configured*100 && actual < (configured+1)*100 { return true } return false } // SanitizedPathJoin performs filepath.Join(root, reqPath) that // is safe against directory traversal attacks. It uses logic // similar to that in the Go standard library, specifically // in the implementation of http.Dir. The root is assumed to // be a trusted path, but reqPath is not; and the output will // never be outside of root. The resulting path can be used // with the local file system. If root is empty, the current // directory is assumed. If the cleaned request path is deemed // not local according to lexical processing (i.e. ignoring links), // it will be rejected as unsafe and only the root will be returned. func SanitizedPathJoin(root, reqPath string) string { if root == "" { root = "." } relPath := path.Clean("/" + reqPath)[1:] // clean path and trim the leading / if relPath != "" && !filepath.IsLocal(relPath) { // path is unsafe (see https://github.com/golang/go/issues/56336#issuecomment-1416214885) return root } path := filepath.Join(root, filepath.FromSlash(relPath)) // filepath.Join also cleans the path, and cleaning strips // the trailing slash, so we need to re-add it afterwards. // if the length is 1, then it's a path to the root, // and that should return ".", so we don't append the separator. if strings.HasSuffix(reqPath, "/") && len(reqPath) > 1 { path += separator } return path } // CleanPath cleans path p according to path.Clean(), but only // merges repeated slashes if collapseSlashes is true, and always // preserves trailing slashes. func CleanPath(p string, collapseSlashes bool) string { if collapseSlashes { return cleanPath(p) } // insert an invalid/impossible URI character into each two consecutive // slashes to expand empty path segments; then clean the path as usual, // and then remove the remaining temporary characters. const tmpCh = 0xff var sb strings.Builder for i, ch := range p { if ch == '/' && i > 0 && p[i-1] == '/' { sb.WriteByte(tmpCh) } sb.WriteRune(ch) } halfCleaned := cleanPath(sb.String()) halfCleaned = strings.ReplaceAll(halfCleaned, string([]byte{tmpCh}), "") return halfCleaned } // cleanPath does path.Clean(p) but preserves any trailing slash. func cleanPath(p string) string { cleaned := path.Clean(p) if cleaned != "/" && strings.HasSuffix(p, "/") { cleaned = cleaned + "/" } return cleaned } // tlsPlaceholderWrapper is a no-op listener wrapper that marks // where the TLS listener should be in a chain of listener wrappers. // It should only be used if another listener wrapper must be placed // in front of the TLS handshake. type tlsPlaceholderWrapper struct{} func (tlsPlaceholderWrapper) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "caddy.listeners.tls", New: func() caddy.Module { return new(tlsPlaceholderWrapper) }, } } func (tlsPlaceholderWrapper) WrapListener(ln net.Listener) net.Listener { return ln } func (tlsPlaceholderWrapper) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { return nil } const ( // DefaultHTTPPort is the default port for HTTP. DefaultHTTPPort = 80 // DefaultHTTPSPort is the default port for HTTPS. DefaultHTTPSPort = 443 ) const separator = string(filepath.Separator) // Interface guard var ( _ caddy.ListenerWrapper = (*tlsPlaceholderWrapper)(nil) _ caddyfile.Unmarshaler = (*tlsPlaceholderWrapper)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/responsewriter.go
modules/caddyhttp/responsewriter.go
// Copyright 2015 Matthew Holt and The Caddy 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 caddyhttp import ( "bufio" "bytes" "fmt" "io" "net" "net/http" ) // ResponseWriterWrapper wraps an underlying ResponseWriter and // promotes its Pusher method as well. To use this type, embed // a pointer to it within your own struct type that implements // the http.ResponseWriter interface, then call methods on the // embedded value. type ResponseWriterWrapper struct { http.ResponseWriter } // Push implements http.Pusher. It simply calls the underlying // ResponseWriter's Push method if there is one, or returns // ErrNotImplemented otherwise. func (rww *ResponseWriterWrapper) Push(target string, opts *http.PushOptions) error { if pusher, ok := rww.ResponseWriter.(http.Pusher); ok { return pusher.Push(target, opts) } return ErrNotImplemented } // ReadFrom implements io.ReaderFrom. It retries to use io.ReaderFrom if available, // then fallback to io.Copy. // see: https://github.com/caddyserver/caddy/issues/6546 func (rww *ResponseWriterWrapper) ReadFrom(r io.Reader) (n int64, err error) { if rf, ok := rww.ResponseWriter.(io.ReaderFrom); ok { return rf.ReadFrom(r) } return io.Copy(rww.ResponseWriter, r) } // Unwrap returns the underlying ResponseWriter, necessary for // http.ResponseController to work correctly. func (rww *ResponseWriterWrapper) Unwrap() http.ResponseWriter { return rww.ResponseWriter } // ErrNotImplemented is returned when an underlying // ResponseWriter does not implement the required method. var ErrNotImplemented = fmt.Errorf("method not implemented") type responseRecorder struct { *ResponseWriterWrapper statusCode int buf *bytes.Buffer shouldBuffer ShouldBufferFunc size int wroteHeader bool stream bool readSize *int } // NewResponseRecorder returns a new ResponseRecorder that can be // used instead of a standard http.ResponseWriter. The recorder is // useful for middlewares which need to buffer a response and // potentially process its entire body before actually writing the // response to the underlying writer. Of course, buffering the entire // body has a memory overhead, but sometimes there is no way to avoid // buffering the whole response, hence the existence of this type. // Still, if at all practical, handlers should strive to stream // responses by wrapping Write and WriteHeader methods instead of // buffering whole response bodies. // // Buffering is actually optional. The shouldBuffer function will // be called just before the headers are written. If it returns // true, the headers and body will be buffered by this recorder // and not written to the underlying writer; if false, the headers // will be written immediately and the body will be streamed out // directly to the underlying writer. If shouldBuffer is nil, // the response will never be buffered and will always be streamed // directly to the writer. // // You can know if shouldBuffer returned true by calling Buffered(). // // The provided buffer buf should be obtained from a pool for best // performance (see the sync.Pool type). // // Proper usage of a recorder looks like this: // // rec := caddyhttp.NewResponseRecorder(w, buf, shouldBuffer) // err := next.ServeHTTP(rec, req) // if err != nil { // return err // } // if !rec.Buffered() { // return nil // } // // process the buffered response here // // The header map is not buffered; i.e. the ResponseRecorder's Header() // method returns the same header map of the underlying ResponseWriter. // This is a crucial design decision to allow HTTP trailers to be // flushed properly (https://github.com/caddyserver/caddy/issues/3236). // // Once you are ready to write the response, there are two ways you can // do it. The easier way is to have the recorder do it: // // rec.WriteResponse() // // This writes the recorded response headers as well as the buffered body. // Or, you may wish to do it yourself, especially if you manipulated the // buffered body. First you will need to write the headers with the // recorded status code, then write the body (this example writes the // recorder's body buffer, but you might have your own body to write // instead): // // w.WriteHeader(rec.Status()) // io.Copy(w, rec.Buffer()) // // As a special case, 1xx responses are not buffered nor recorded // because they are not the final response; they are passed through // directly to the underlying ResponseWriter. func NewResponseRecorder(w http.ResponseWriter, buf *bytes.Buffer, shouldBuffer ShouldBufferFunc) ResponseRecorder { return &responseRecorder{ ResponseWriterWrapper: &ResponseWriterWrapper{ResponseWriter: w}, buf: buf, shouldBuffer: shouldBuffer, } } // WriteHeader writes the headers with statusCode to the wrapped // ResponseWriter unless the response is to be buffered instead. // 1xx responses are never buffered. func (rr *responseRecorder) WriteHeader(statusCode int) { if rr.wroteHeader { return } // save statusCode always, in case HTTP middleware upgrades websocket // connections by manually setting headers and writing status 101 rr.statusCode = statusCode // decide whether we should buffer the response if rr.shouldBuffer == nil { rr.stream = true } else { rr.stream = !rr.shouldBuffer(rr.statusCode, rr.ResponseWriterWrapper.Header()) } // 1xx responses aren't final; just informational if statusCode < 100 || statusCode > 199 { rr.wroteHeader = true } // if informational or not buffered, immediately write header if rr.stream || (100 <= statusCode && statusCode <= 199) { rr.ResponseWriterWrapper.WriteHeader(statusCode) } } func (rr *responseRecorder) Write(data []byte) (int, error) { rr.WriteHeader(http.StatusOK) var n int var err error if rr.stream { n, err = rr.ResponseWriterWrapper.Write(data) } else { n, err = rr.buf.Write(data) } rr.size += n return n, err } func (rr *responseRecorder) ReadFrom(r io.Reader) (int64, error) { rr.WriteHeader(http.StatusOK) var n int64 var err error if rr.stream { n, err = rr.ResponseWriterWrapper.ReadFrom(r) } else { n, err = rr.buf.ReadFrom(r) } rr.size += int(n) return n, err } // Status returns the status code that was written, if any. func (rr *responseRecorder) Status() int { return rr.statusCode } // Size returns the number of bytes written, // not including the response headers. func (rr *responseRecorder) Size() int { return rr.size } // Buffer returns the body buffer that rr was created with. // You should still have your original pointer, though. func (rr *responseRecorder) Buffer() *bytes.Buffer { return rr.buf } // Buffered returns whether rr has decided to buffer the response. func (rr *responseRecorder) Buffered() bool { return !rr.stream } func (rr *responseRecorder) WriteResponse() error { if rr.statusCode == 0 { // could happen if no handlers actually wrote anything, // and this prevents a panic; status must be > 0 rr.WriteHeader(http.StatusOK) } if rr.stream { return nil } rr.ResponseWriterWrapper.WriteHeader(rr.statusCode) _, err := io.Copy(rr.ResponseWriterWrapper, rr.buf) return err } // FlushError will suppress actual flushing if the response is buffered. See: // https://github.com/caddyserver/caddy/issues/6144 func (rr *responseRecorder) FlushError() error { if rr.stream { //nolint:bodyclose return http.NewResponseController(rr.ResponseWriterWrapper).Flush() } return nil } // Private interface so it can only be used in this package // #TODO: maybe export it later func (rr *responseRecorder) setReadSize(size *int) { rr.readSize = size } func (rr *responseRecorder) Hijack() (net.Conn, *bufio.ReadWriter, error) { //nolint:bodyclose conn, brw, err := http.NewResponseController(rr.ResponseWriterWrapper).Hijack() if err != nil { return nil, nil, err } // Per http documentation, returned bufio.Writer is empty, but bufio.Read maybe not conn = &hijackedConn{conn, rr} brw.Writer.Reset(conn) buffered := brw.Reader.Buffered() if buffered != 0 { conn.(*hijackedConn).updateReadSize(buffered) data, _ := brw.Peek(buffered) brw.Reader.Reset(io.MultiReader(bytes.NewReader(data), conn)) // peek to make buffered data appear, as Reset will make it 0 _, _ = brw.Peek(buffered) } else { brw.Reader.Reset(conn) } return conn, brw, nil } // used to track the size of hijacked response writers type hijackedConn struct { net.Conn rr *responseRecorder } func (hc *hijackedConn) updateReadSize(n int) { if hc.rr.readSize != nil { *hc.rr.readSize += n } } func (hc *hijackedConn) Read(p []byte) (int, error) { n, err := hc.Conn.Read(p) hc.updateReadSize(n) return n, err } func (hc *hijackedConn) WriteTo(w io.Writer) (int64, error) { n, err := io.Copy(w, hc.Conn) hc.updateReadSize(int(n)) return n, err } func (hc *hijackedConn) Write(p []byte) (int, error) { n, err := hc.Conn.Write(p) hc.rr.size += n return n, err } func (hc *hijackedConn) ReadFrom(r io.Reader) (int64, error) { n, err := io.Copy(hc.Conn, r) hc.rr.size += int(n) return n, err } // ResponseRecorder is a http.ResponseWriter that records // responses instead of writing them to the client. See // docs for NewResponseRecorder for proper usage. type ResponseRecorder interface { http.ResponseWriter Status() int Buffer() *bytes.Buffer Buffered() bool Size() int WriteResponse() error } // ShouldBufferFunc is a function that returns true if the // response should be buffered, given the pending HTTP status // code and response headers. type ShouldBufferFunc func(status int, header http.Header) bool // Interface guards var ( _ http.ResponseWriter = (*ResponseWriterWrapper)(nil) _ ResponseRecorder = (*responseRecorder)(nil) // Implementing ReaderFrom can be such a significant // optimization that it should probably be required! // see PR #5022 (25%-50% speedup) _ io.ReaderFrom = (*ResponseWriterWrapper)(nil) _ io.ReaderFrom = (*responseRecorder)(nil) _ io.ReaderFrom = (*hijackedConn)(nil) _ io.WriterTo = (*hijackedConn)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/matchers.go
modules/caddyhttp/matchers.go
// Copyright 2015 Matthew Holt and The Caddy 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 caddyhttp import ( "encoding/json" "errors" "fmt" "net" "net/http" "net/textproto" "net/url" "path" "regexp" "runtime" "slices" "sort" "strconv" "strings" "github.com/google/cel-go/cel" "github.com/google/cel-go/common/types" "github.com/google/cel-go/common/types/ref" "golang.org/x/net/idna" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) type ( // MatchHost matches requests by the Host value (case-insensitive). // // When used in a top-level HTTP route, // [qualifying domain names](/docs/automatic-https#hostname-requirements) // may trigger [automatic HTTPS](/docs/automatic-https), which automatically // provisions and renews certificates for you. Before doing this, you // should ensure that DNS records for these domains are properly configured, // especially A/AAAA pointed at your server. // // Automatic HTTPS can be // [customized or disabled](/docs/modules/http#servers/automatic_https). // // Wildcards (`*`) may be used to represent exactly one label of the // hostname, in accordance with RFC 1034 (because host matchers are also // used for automatic HTTPS which influences TLS certificates). Thus, // a host of `*` matches hosts like `localhost` or `internal` but not // `example.com`. To catch all hosts, omit the host matcher entirely. // // The wildcard can be useful for matching all subdomains, for example: // `*.example.com` matches `foo.example.com` but not `foo.bar.example.com`. // // Duplicate entries will return an error. MatchHost []string // MatchPath case-insensitively matches requests by the URI's path. Path // matching is exact, not prefix-based, giving you more control and clarity // over matching. Wildcards (`*`) may be used: // // - At the end only, for a prefix match (`/prefix/*`) // - At the beginning only, for a suffix match (`*.suffix`) // - On both sides only, for a substring match (`*/contains/*`) // - In the middle, for a globular match (`/accounts/*/info`) // // Slashes are significant; i.e. `/foo*` matches `/foo`, `/foo/`, `/foo/bar`, // and `/foobar`; but `/foo/*` does not match `/foo` or `/foobar`. Valid // paths start with a slash `/`. // // Because there are, in general, multiple possible escaped forms of any // path, path matchers operate in unescaped space; that is, path matchers // should be written in their unescaped form to prevent ambiguities and // possible security issues, as all request paths will be normalized to // their unescaped forms before matcher evaluation. // // However, escape sequences in a match pattern are supported; they are // compared with the request's raw/escaped path for those bytes only. // In other words, a matcher of `/foo%2Fbar` will match a request path // of precisely `/foo%2Fbar`, but not `/foo/bar`. It follows that matching // the literal percent sign (%) in normalized space can be done using the // escaped form, `%25`. // // Even though wildcards (`*`) operate in the normalized space, the special // escaped wildcard (`%*`), which is not a valid escape sequence, may be // used in place of a span that should NOT be decoded; that is, `/bands/%*` // will match `/bands/AC%2fDC` whereas `/bands/*` will not. // // Even though path matching is done in normalized space, the special // wildcard `%*` may be used in place of a span that should NOT be decoded; // that is, `/bands/%*/` will match `/bands/AC%2fDC/` whereas `/bands/*/` // will not. // // This matcher is fast, so it does not support regular expressions or // capture groups. For slower but more powerful matching, use the // path_regexp matcher. (Note that due to the special treatment of // escape sequences in matcher patterns, they may perform slightly slower // in high-traffic environments.) MatchPath []string // MatchPathRE matches requests by a regular expression on the URI's path. // Path matching is performed in the unescaped (decoded) form of the path. // // Upon a match, it adds placeholders to the request: `{http.regexp.name.capture_group}` // where `name` is the regular expression's name, and `capture_group` is either // the named or positional capture group from the expression itself. If no name // is given, then the placeholder omits the name: `{http.regexp.capture_group}` // (potentially leading to collisions). MatchPathRE struct{ MatchRegexp } // MatchMethod matches requests by the method. MatchMethod []string // MatchQuery matches requests by the URI's query string. It takes a JSON object // keyed by the query keys, with an array of string values to match for that key. // Query key matches are exact, but wildcards may be used for value matches. Both // keys and values may be placeholders. // // An example of the structure to match `?key=value&topic=api&query=something` is: // // ```json // { // "key": ["value"], // "topic": ["api"], // "query": ["*"] // } // ``` // // Invalid query strings, including those with bad escapings or illegal characters // like semicolons, will fail to parse and thus fail to match. // // **NOTE:** Notice that query string values are arrays, not singular values. This is // because repeated keys are valid in query strings, and each one may have a // different value. This matcher will match for a key if any one of its configured // values is assigned in the query string. Backend applications relying on query // strings MUST take into consideration that query string values are arrays and can // have multiple values. MatchQuery url.Values // MatchHeader matches requests by header fields. The key is the field // name and the array is the list of field values. It performs fast, // exact string comparisons of the field values. Fast prefix, suffix, // and substring matches can also be done by suffixing, prefixing, or // surrounding the value with the wildcard `*` character, respectively. // If a list is null, the header must not exist. If the list is empty, // the field must simply exist, regardless of its value. // // **NOTE:** Notice that header values are arrays, not singular values. This is // because repeated fields are valid in headers, and each one may have a // different value. This matcher will match for a field if any one of its configured // values matches in the header. Backend applications relying on headers MUST take // into consideration that header field values are arrays and can have multiple // values. MatchHeader http.Header // MatchHeaderRE matches requests by a regular expression on header fields. // // Upon a match, it adds placeholders to the request: `{http.regexp.name.capture_group}` // where `name` is the regular expression's name, and `capture_group` is either // the named or positional capture group from the expression itself. If no name // is given, then the placeholder omits the name: `{http.regexp.capture_group}` // (potentially leading to collisions). MatchHeaderRE map[string]*MatchRegexp // MatchProtocol matches requests by protocol. Recognized values are // "http", "https", and "grpc" for broad protocol matches, or specific // HTTP versions can be specified like so: "http/1", "http/1.1", // "http/2", "http/3", or minimum versions: "http/2+", etc. MatchProtocol string // MatchTLS matches HTTP requests based on the underlying // TLS connection state. If this matcher is specified but // the request did not come over TLS, it will never match. // If this matcher is specified but is empty and the request // did come in over TLS, it will always match. MatchTLS struct { // Matches if the TLS handshake has completed. QUIC 0-RTT early // data may arrive before the handshake completes. Generally, it // is unsafe to replay these requests if they are not idempotent; // additionally, the remote IP of early data packets can more // easily be spoofed. It is conventional to respond with HTTP 425 // Too Early if the request cannot risk being processed in this // state. HandshakeComplete *bool `json:"handshake_complete,omitempty"` } // MatchNot matches requests by negating the results of its matcher // sets. A single "not" matcher takes one or more matcher sets. Each // matcher set is OR'ed; in other words, if any matcher set returns // true, the final result of the "not" matcher is false. Individual // matchers within a set work the same (i.e. different matchers in // the same set are AND'ed). // // NOTE: The generated docs which describe the structure of this // module are wrong because of how this type unmarshals JSON in a // custom way. The correct structure is: // // ```json // [ // {}, // {} // ] // ``` // // where each of the array elements is a matcher set, i.e. an // object keyed by matcher name. MatchNot struct { MatcherSetsRaw []caddy.ModuleMap `json:"-" caddy:"namespace=http.matchers"` MatcherSets []MatcherSet `json:"-"` } ) func init() { caddy.RegisterModule(MatchHost{}) caddy.RegisterModule(MatchPath{}) caddy.RegisterModule(MatchPathRE{}) caddy.RegisterModule(MatchMethod{}) caddy.RegisterModule(MatchQuery{}) caddy.RegisterModule(MatchHeader{}) caddy.RegisterModule(MatchHeaderRE{}) caddy.RegisterModule(new(MatchProtocol)) caddy.RegisterModule(MatchTLS{}) caddy.RegisterModule(MatchNot{}) } // CaddyModule returns the Caddy module information. func (MatchHost) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.matchers.host", New: func() caddy.Module { return new(MatchHost) }, } } // UnmarshalCaddyfile implements caddyfile.Unmarshaler. func (m *MatchHost) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { // iterate to merge multiple matchers into one for d.Next() { *m = append(*m, d.RemainingArgs()...) if d.NextBlock(0) { return d.Err("malformed host matcher: blocks are not supported") } } return nil } // Provision sets up and validates m, including making it more efficient for large lists. func (m MatchHost) Provision(_ caddy.Context) error { // check for duplicates; they are nonsensical and reduce efficiency // (we could just remove them, but the user should know their config is erroneous) seen := make(map[string]int, len(m)) for i, host := range m { asciiHost, err := idna.ToASCII(host) if err != nil { return fmt.Errorf("converting hostname '%s' to ASCII: %v", host, err) } if asciiHost != host { m[i] = asciiHost } normalizedHost := strings.ToLower(asciiHost) if firstI, ok := seen[normalizedHost]; ok { return fmt.Errorf("host at index %d is repeated at index %d: %s", firstI, i, host) } seen[normalizedHost] = i } if m.large() { // sort the slice lexicographically, grouping "fuzzy" entries (wildcards and placeholders) // at the front of the list; this allows us to use binary search for exact matches, which // we have seen from experience is the most common kind of value in large lists; and any // other kinds of values (wildcards and placeholders) are grouped in front so the linear // search should find a match fairly quickly sort.Slice(m, func(i, j int) bool { iInexact, jInexact := m.fuzzy(m[i]), m.fuzzy(m[j]) if iInexact && !jInexact { return true } if !iInexact && jInexact { return false } return m[i] < m[j] }) } return nil } // Match returns true if r matches m. func (m MatchHost) Match(r *http.Request) bool { match, _ := m.MatchWithError(r) return match } // MatchWithError returns true if r matches m. func (m MatchHost) MatchWithError(r *http.Request) (bool, error) { reqHost, _, err := net.SplitHostPort(r.Host) if err != nil { // OK; probably didn't have a port reqHost = r.Host // make sure we strip the brackets from IPv6 addresses reqHost = strings.TrimPrefix(reqHost, "[") reqHost = strings.TrimSuffix(reqHost, "]") } if m.large() { // fast path: locate exact match using binary search (about 100-1000x faster for large lists) pos := sort.Search(len(m), func(i int) bool { if m.fuzzy(m[i]) { return false } return m[i] >= reqHost }) if pos < len(m) && m[pos] == reqHost { return true, nil } } repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) outer: for _, host := range m { // fast path: if matcher is large, we already know we don't have an exact // match, so we're only looking for fuzzy match now, which should be at the // front of the list; if we have reached a value that is not fuzzy, there // will be no match and we can short-circuit for efficiency if m.large() && !m.fuzzy(host) { break } host = repl.ReplaceAll(host, "") if strings.Contains(host, "*") { patternParts := strings.Split(host, ".") incomingParts := strings.Split(reqHost, ".") if len(patternParts) != len(incomingParts) { continue } for i := range patternParts { if patternParts[i] == "*" { continue } if !strings.EqualFold(patternParts[i], incomingParts[i]) { continue outer } } return true, nil } else if strings.EqualFold(reqHost, host) { return true, nil } } return false, nil } // CELLibrary produces options that expose this matcher for use in CEL // expression matchers. // // Example: // // expression host('localhost') func (MatchHost) CELLibrary(ctx caddy.Context) (cel.Library, error) { return CELMatcherImpl( "host", "host_match_request_list", []*cel.Type{cel.ListType(cel.StringType)}, func(data ref.Val) (RequestMatcherWithError, error) { refStringList := stringSliceType strList, err := data.ConvertToNative(refStringList) if err != nil { return nil, err } matcher := MatchHost(strList.([]string)) err = matcher.Provision(ctx) return matcher, err }, ) } // fuzzy returns true if the given hostname h is not a specific // hostname, e.g. has placeholders or wildcards. func (MatchHost) fuzzy(h string) bool { return strings.ContainsAny(h, "{*") } // large returns true if m is considered to be large. Optimizing // the matcher for smaller lists has diminishing returns. // See related benchmark function in test file to conduct experiments. func (m MatchHost) large() bool { return len(m) > 100 } // CaddyModule returns the Caddy module information. func (MatchPath) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.matchers.path", New: func() caddy.Module { return new(MatchPath) }, } } // Provision lower-cases the paths in m to ensure case-insensitive matching. func (m MatchPath) Provision(_ caddy.Context) error { for i := range m { if m[i] == "*" && i > 0 { // will always match, so just put it first m[0] = m[i] break } m[i] = strings.ToLower(m[i]) } return nil } // Match returns true if r matches m. func (m MatchPath) Match(r *http.Request) bool { match, _ := m.MatchWithError(r) return match } // MatchWithError returns true if r matches m. func (m MatchPath) MatchWithError(r *http.Request) (bool, error) { // Even though RFC 9110 says that path matching is case-sensitive // (https://www.rfc-editor.org/rfc/rfc9110.html#section-4.2.3), // we do case-insensitive matching to mitigate security issues // related to differences between operating systems, applications, // etc; if case-sensitive matching is needed, the regex matcher // can be used instead. reqPath := strings.ToLower(r.URL.Path) // See #2917; Windows ignores trailing dots and spaces // when accessing files (sigh), potentially causing a // security risk (cry) if PHP files end up being served // as static files, exposing the source code, instead of // being matched by *.php to be treated as PHP scripts. if runtime.GOOS == "windows" { // issue #5613 reqPath = strings.TrimRight(reqPath, ". ") } repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) for _, matchPattern := range m { matchPattern = repl.ReplaceAll(matchPattern, "") // special case: whole path is wildcard; this is unnecessary // as it matches all requests, which is the same as no matcher if matchPattern == "*" { return true, nil } // Clean the path, merge doubled slashes, etc. // This ensures maliciously crafted requests can't bypass // the path matcher. See #4407. Good security posture // requires that we should do all we can to reduce any // funny-looking paths into "normalized" forms such that // weird variants can't sneak by. // // How we clean the path depends on the kind of pattern: // we either merge slashes or we don't. If the pattern // has double slashes, we preserve them in the path. // // TODO: Despite the fact that the *vast* majority of path // matchers have only 1 pattern, a possible optimization is // to remember the cleaned form of the path for future // iterations; it's just that the way we clean depends on // the kind of pattern. mergeSlashes := !strings.Contains(matchPattern, "//") // if '%' appears in the match pattern, we interpret that to mean // the intent is to compare that part of the path in raw/escaped // space; i.e. "%40"=="%40", not "@", and "%2F"=="%2F", not "/" if strings.Contains(matchPattern, "%") { reqPathForPattern := CleanPath(r.URL.EscapedPath(), mergeSlashes) if m.matchPatternWithEscapeSequence(reqPathForPattern, matchPattern) { return true, nil } // doing prefix/suffix/substring matches doesn't make sense continue } reqPathForPattern := CleanPath(reqPath, mergeSlashes) // for substring, prefix, and suffix matching, only perform those // special, fast matches if they are the only wildcards in the pattern; // otherwise we assume a globular match if any * appears in the middle // special case: first and last characters are wildcard, // treat it as a fast substring match if strings.Count(matchPattern, "*") == 2 && strings.HasPrefix(matchPattern, "*") && strings.HasSuffix(matchPattern, "*") { if strings.Contains(reqPathForPattern, matchPattern[1:len(matchPattern)-1]) { return true, nil } continue } // only perform prefix/suffix match if it is the only wildcard... // I think that is more correct most of the time if strings.Count(matchPattern, "*") == 1 { // special case: first character is a wildcard, // treat it as a fast suffix match if strings.HasPrefix(matchPattern, "*") { if strings.HasSuffix(reqPathForPattern, matchPattern[1:]) { return true, nil } continue } // special case: last character is a wildcard, // treat it as a fast prefix match if strings.HasSuffix(matchPattern, "*") { if strings.HasPrefix(reqPathForPattern, matchPattern[:len(matchPattern)-1]) { return true, nil } continue } } // at last, use globular matching, which also is exact matching // if there are no glob/wildcard chars; we ignore the error here // because we can't handle it anyway matches, _ := path.Match(matchPattern, reqPathForPattern) if matches { return true, nil } } return false, nil } func (MatchPath) matchPatternWithEscapeSequence(escapedPath, matchPath string) bool { // We would just compare the pattern against r.URL.Path, // but the pattern contains %, indicating that we should // compare at least some part of the path in raw/escaped // space, not normalized space; so we build the string we // will compare against by adding the normalized parts // of the path, then switching to the escaped parts where // the pattern hints to us wherever % is present. var sb strings.Builder // iterate the pattern and escaped path in lock-step; // increment iPattern every time we consume a char from the pattern, // increment iPath every time we consume a char from the path; // iPattern and iPath are our cursors/iterator positions for each string var iPattern, iPath int for { if iPattern >= len(matchPath) || iPath >= len(escapedPath) { break } // get the next character from the request path pathCh := string(escapedPath[iPath]) var escapedPathCh string // normalize (decode) escape sequences if pathCh == "%" && len(escapedPath) >= iPath+3 { // hold onto this in case we find out the intent is to match in escaped space here; // we lowercase it even though technically the spec says: "For consistency, URI // producers and normalizers should use uppercase hexadecimal digits for all percent- // encodings" (RFC 3986 section 2.1) - we lowercased the matcher pattern earlier in // provisioning so we do the same here to gain case-insensitivity in equivalence; // besides, this string is never shown visibly escapedPathCh = strings.ToLower(escapedPath[iPath : iPath+3]) var err error pathCh, err = url.PathUnescape(escapedPathCh) if err != nil { // should be impossible unless EscapedPath() is giving us an invalid sequence! return false } iPath += 2 // escape sequence is 2 bytes longer than normal char } // now get the next character from the pattern normalize := true switch matchPath[iPattern] { case '%': // escape sequence // if not a wildcard ("%*"), compare literally; consume next two bytes of pattern if len(matchPath) >= iPattern+3 && matchPath[iPattern+1] != '*' { sb.WriteString(escapedPathCh) iPath++ iPattern += 2 break } // escaped wildcard sequence; consume next byte only ('*') iPattern++ normalize = false fallthrough case '*': // wildcard, so consume until next matching character remaining := escapedPath[iPath:] until := len(escapedPath) - iPath // go until end of string... if iPattern < len(matchPath)-1 { // ...unless the * is not at the end nextCh := matchPath[iPattern+1] until = strings.IndexByte(remaining, nextCh) if until == -1 { // terminating char of wildcard span not found, so definitely no match return false } } if until == 0 { // empty span; nothing to add on this iteration break } next := remaining[:until] if normalize { var err error next, err = url.PathUnescape(next) if err != nil { return false // should be impossible anyway } } sb.WriteString(next) iPath += until default: sb.WriteString(pathCh) iPath++ } iPattern++ } // we can now treat rawpath globs (%*) as regular globs (*) matchPath = strings.ReplaceAll(matchPath, "%*", "*") // ignore error here because we can't handle it anyway= matches, _ := path.Match(matchPath, sb.String()) return matches } // CELLibrary produces options that expose this matcher for use in CEL // expression matchers. // // Example: // // expression path('*substring*', '*suffix') func (MatchPath) CELLibrary(ctx caddy.Context) (cel.Library, error) { return CELMatcherImpl( // name of the macro, this is the function name that users see when writing expressions. "path", // name of the function that the macro will be rewritten to call. "path_match_request_list", // internal data type of the MatchPath value. []*cel.Type{cel.ListType(cel.StringType)}, // function to convert a constant list of strings to a MatchPath instance. func(data ref.Val) (RequestMatcherWithError, error) { refStringList := stringSliceType strList, err := data.ConvertToNative(refStringList) if err != nil { return nil, err } matcher := MatchPath(strList.([]string)) err = matcher.Provision(ctx) return matcher, err }, ) } // UnmarshalCaddyfile implements caddyfile.Unmarshaler. func (m *MatchPath) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { // iterate to merge multiple matchers into one for d.Next() { *m = append(*m, d.RemainingArgs()...) if d.NextBlock(0) { return d.Err("malformed path matcher: blocks are not supported") } } return nil } // CaddyModule returns the Caddy module information. func (MatchPathRE) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.matchers.path_regexp", New: func() caddy.Module { return new(MatchPathRE) }, } } // Match returns true if r matches m. func (m MatchPathRE) Match(r *http.Request) bool { match, _ := m.MatchWithError(r) return match } // MatchWithError returns true if r matches m. func (m MatchPathRE) MatchWithError(r *http.Request) (bool, error) { repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) // Clean the path, merges doubled slashes, etc. // This ensures maliciously crafted requests can't bypass // the path matcher. See #4407 cleanedPath := cleanPath(r.URL.Path) return m.MatchRegexp.Match(cleanedPath, repl), nil } // CELLibrary produces options that expose this matcher for use in CEL // expression matchers. // // Example: // // expression path_regexp('^/bar') func (MatchPathRE) CELLibrary(ctx caddy.Context) (cel.Library, error) { unnamedPattern, err := CELMatcherImpl( "path_regexp", "path_regexp_request_string", []*cel.Type{cel.StringType}, func(data ref.Val) (RequestMatcherWithError, error) { pattern := data.(types.String) matcher := MatchPathRE{MatchRegexp{ Name: ctx.Value(MatcherNameCtxKey).(string), Pattern: string(pattern), }} err := matcher.Provision(ctx) return matcher, err }, ) if err != nil { return nil, err } namedPattern, err := CELMatcherImpl( "path_regexp", "path_regexp_request_string_string", []*cel.Type{cel.StringType, cel.StringType}, func(data ref.Val) (RequestMatcherWithError, error) { refStringList := stringSliceType params, err := data.ConvertToNative(refStringList) if err != nil { return nil, err } strParams := params.([]string) name := strParams[0] if name == "" { name = ctx.Value(MatcherNameCtxKey).(string) } matcher := MatchPathRE{MatchRegexp{ Name: name, Pattern: strParams[1], }} err = matcher.Provision(ctx) return matcher, err }, ) if err != nil { return nil, err } envOpts := append(unnamedPattern.CompileOptions(), namedPattern.CompileOptions()...) prgOpts := append(unnamedPattern.ProgramOptions(), namedPattern.ProgramOptions()...) return NewMatcherCELLibrary(envOpts, prgOpts), nil } // CaddyModule returns the Caddy module information. func (MatchMethod) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.matchers.method", New: func() caddy.Module { return new(MatchMethod) }, } } // UnmarshalCaddyfile implements caddyfile.Unmarshaler. func (m *MatchMethod) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { // iterate to merge multiple matchers into one for d.Next() { *m = append(*m, d.RemainingArgs()...) if d.NextBlock(0) { return d.Err("malformed method matcher: blocks are not supported") } } return nil } // Match returns true if r matches m. func (m MatchMethod) Match(r *http.Request) bool { match, _ := m.MatchWithError(r) return match } // MatchWithError returns true if r matches m. func (m MatchMethod) MatchWithError(r *http.Request) (bool, error) { return slices.Contains(m, r.Method), nil } // CELLibrary produces options that expose this matcher for use in CEL // expression matchers. // // Example: // // expression method('PUT', 'POST') func (MatchMethod) CELLibrary(_ caddy.Context) (cel.Library, error) { return CELMatcherImpl( "method", "method_request_list", []*cel.Type{cel.ListType(cel.StringType)}, func(data ref.Val) (RequestMatcherWithError, error) { refStringList := stringSliceType strList, err := data.ConvertToNative(refStringList) if err != nil { return nil, err } return MatchMethod(strList.([]string)), nil }, ) } // CaddyModule returns the Caddy module information. func (MatchQuery) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.matchers.query", New: func() caddy.Module { return new(MatchQuery) }, } } // UnmarshalCaddyfile implements caddyfile.Unmarshaler. func (m *MatchQuery) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { if *m == nil { *m = make(map[string][]string) } // iterate to merge multiple matchers into one for d.Next() { for _, query := range d.RemainingArgs() { if query == "" { continue } before, after, found := strings.Cut(query, "=") if !found { return d.Errf("malformed query matcher token: %s; must be in param=val format", d.Val()) } url.Values(*m).Add(before, after) } if d.NextBlock(0) { return d.Err("malformed query matcher: blocks are not supported") } } return nil } // Match returns true if r matches m. An empty m matches an empty query string. func (m MatchQuery) Match(r *http.Request) bool { match, _ := m.MatchWithError(r) return match } // MatchWithError returns true if r matches m. // An empty m matches an empty query string. func (m MatchQuery) MatchWithError(r *http.Request) (bool, error) { // If no query keys are configured, this only // matches an empty query string. if len(m) == 0 { return len(r.URL.Query()) == 0, nil } repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) // parse query string just once, for efficiency parsed, err := url.ParseQuery(r.URL.RawQuery) if err != nil { // Illegal query string. Likely bad escape sequence or unescaped literals. // Note that semicolons in query string have a controversial history. Summaries: // - https://github.com/golang/go/issues/50034 // - https://github.com/golang/go/issues/25192 // Despite the URL WHATWG spec mandating the use of & separators for query strings, // every URL parser implementation is different, and Filippo Valsorda rightly wrote: // "Relying on parser alignment for security is doomed." Overall conclusion is that // splitting on & and rejecting ; in key=value pairs is safer than accepting raw ;. // We regard the Go team's decision as sound and thus reject malformed query strings. return false, nil } // Count the amount of matched keys, to ensure we AND // between all configured query keys; all keys must // match at least one value. matchedKeys := 0 for param, vals := range m { param = repl.ReplaceAll(param, "") paramVal, found := parsed[param] if !found { return false, nil } for _, v := range vals { v = repl.ReplaceAll(v, "") if slices.Contains(paramVal, v) || v == "*" { matchedKeys++ break } } } return matchedKeys == len(m), nil } // CELLibrary produces options that expose this matcher for use in CEL // expression matchers. // // Example: // // expression query({'sort': 'asc'}) || query({'foo': ['*bar*', 'baz']}) func (MatchQuery) CELLibrary(_ caddy.Context) (cel.Library, error) { return CELMatcherImpl( "query", "query_matcher_request_map", []*cel.Type{CELTypeJSON}, func(data ref.Val) (RequestMatcherWithError, error) { mapStrListStr, err := CELValueToMapStrList(data) if err != nil { return nil, err } return MatchQuery(url.Values(mapStrListStr)), nil }, ) } // CaddyModule returns the Caddy module information. func (MatchHeader) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.matchers.header", New: func() caddy.Module { return new(MatchHeader) }, } } // UnmarshalCaddyfile implements caddyfile.Unmarshaler. func (m *MatchHeader) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { if *m == nil { *m = make(map[string][]string) } // iterate to merge multiple matchers into one for d.Next() { var field, val string if !d.Args(&field) { return d.Errf("malformed header matcher: expected field") } if strings.HasPrefix(field, "!") { if len(field) == 1 { return d.Errf("malformed header matcher: must have field name following ! character") } field = field[1:] headers := *m headers[field] = nil m = &headers if d.NextArg() { return d.Errf("malformed header matcher: null matching headers cannot have a field value") } } else { if !d.NextArg() { return d.Errf("malformed header matcher: expected both field and value") } // If multiple header matchers with the same header field are defined, // we want to add the existing to the list of headers (will be OR'ed) val = d.Val() http.Header(*m).Add(field, val) } if d.NextBlock(0) { return d.Err("malformed header matcher: blocks are not supported") } } return nil }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
true
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/server_test.go
modules/caddyhttp/server_test.go
package caddyhttp import ( "bytes" "context" "io" "net/http" "net/http/httptest" "net/netip" "testing" "time" "github.com/stretchr/testify/assert" "go.uber.org/zap" "go.uber.org/zap/zapcore" ) type writeFunc func(p []byte) (int, error) type nopSyncer writeFunc func (n nopSyncer) Write(p []byte) (int, error) { return n(p) } func (n nopSyncer) Sync() error { return nil } // testLogger returns a logger and a buffer to which the logger writes. The // buffer can be read for asserting log output. func testLogger(wf writeFunc) *zap.Logger { ws := nopSyncer(wf) encoderCfg := zapcore.EncoderConfig{ MessageKey: "msg", LevelKey: "level", NameKey: "logger", EncodeLevel: zapcore.LowercaseLevelEncoder, EncodeTime: zapcore.ISO8601TimeEncoder, EncodeDuration: zapcore.StringDurationEncoder, } core := zapcore.NewCore(zapcore.NewJSONEncoder(encoderCfg), ws, zap.DebugLevel) return zap.New(core) } func TestServer_LogRequest(t *testing.T) { s := &Server{} ctx := context.Background() ctx = context.WithValue(ctx, ExtraLogFieldsCtxKey, new(ExtraLogFields)) req := httptest.NewRequest(http.MethodGet, "/", nil).WithContext(ctx) rec := httptest.NewRecorder() wrec := NewResponseRecorder(rec, nil, nil) duration := 50 * time.Millisecond repl := NewTestReplacer(req) bodyReader := &lengthReader{Source: req.Body} shouldLogCredentials := false buf := bytes.Buffer{} accLog := testLogger(buf.Write) s.logRequest(accLog, req, wrec, &duration, repl, bodyReader, shouldLogCredentials) assert.JSONEq(t, `{ "msg":"handled request", "level":"info", "bytes_read":0, "duration":"50ms", "resp_headers": {}, "size":0, "status":0, "user_id":"" }`, buf.String()) } func TestServer_LogRequest_WithTrace(t *testing.T) { s := &Server{} extra := new(ExtraLogFields) ctx := context.WithValue(context.Background(), ExtraLogFieldsCtxKey, extra) extra.Add(zap.String("traceID", "1234567890abcdef")) extra.Add(zap.String("spanID", "12345678")) req := httptest.NewRequest(http.MethodGet, "/", nil).WithContext(ctx) rec := httptest.NewRecorder() wrec := NewResponseRecorder(rec, nil, nil) duration := 50 * time.Millisecond repl := NewTestReplacer(req) bodyReader := &lengthReader{Source: req.Body} shouldLogCredentials := false buf := bytes.Buffer{} accLog := testLogger(buf.Write) s.logRequest(accLog, req, wrec, &duration, repl, bodyReader, shouldLogCredentials) assert.JSONEq(t, `{ "msg":"handled request", "level":"info", "bytes_read":0, "duration":"50ms", "resp_headers": {}, "size":0, "status":0, "user_id":"", "traceID":"1234567890abcdef", "spanID":"12345678" }`, buf.String()) } func BenchmarkServer_LogRequest(b *testing.B) { s := &Server{} extra := new(ExtraLogFields) ctx := context.WithValue(context.Background(), ExtraLogFieldsCtxKey, extra) req := httptest.NewRequest(http.MethodGet, "/", nil).WithContext(ctx) rec := httptest.NewRecorder() wrec := NewResponseRecorder(rec, nil, nil) duration := 50 * time.Millisecond repl := NewTestReplacer(req) bodyReader := &lengthReader{Source: req.Body} buf := io.Discard accLog := testLogger(buf.Write) for b.Loop() { s.logRequest(accLog, req, wrec, &duration, repl, bodyReader, false) } } func BenchmarkServer_LogRequest_NopLogger(b *testing.B) { s := &Server{} extra := new(ExtraLogFields) ctx := context.WithValue(context.Background(), ExtraLogFieldsCtxKey, extra) req := httptest.NewRequest(http.MethodGet, "/", nil).WithContext(ctx) rec := httptest.NewRecorder() wrec := NewResponseRecorder(rec, nil, nil) duration := 50 * time.Millisecond repl := NewTestReplacer(req) bodyReader := &lengthReader{Source: req.Body} accLog := zap.NewNop() for b.Loop() { s.logRequest(accLog, req, wrec, &duration, repl, bodyReader, false) } } func BenchmarkServer_LogRequest_WithTrace(b *testing.B) { s := &Server{} extra := new(ExtraLogFields) ctx := context.WithValue(context.Background(), ExtraLogFieldsCtxKey, extra) extra.Add(zap.String("traceID", "1234567890abcdef")) extra.Add(zap.String("spanID", "12345678")) req := httptest.NewRequest(http.MethodGet, "/", nil).WithContext(ctx) rec := httptest.NewRecorder() wrec := NewResponseRecorder(rec, nil, nil) duration := 50 * time.Millisecond repl := NewTestReplacer(req) bodyReader := &lengthReader{Source: req.Body} buf := io.Discard accLog := testLogger(buf.Write) for b.Loop() { s.logRequest(accLog, req, wrec, &duration, repl, bodyReader, false) } } func TestServer_TrustedRealClientIP_NoTrustedHeaders(t *testing.T) { req := httptest.NewRequest("GET", "/", nil) req.RemoteAddr = "192.0.2.1:12345" ip := trustedRealClientIP(req, []string{}, "192.0.2.1") assert.Equal(t, ip, "192.0.2.1") } func TestServer_TrustedRealClientIP_OneTrustedHeaderEmpty(t *testing.T) { req := httptest.NewRequest("GET", "/", nil) req.RemoteAddr = "192.0.2.1:12345" ip := trustedRealClientIP(req, []string{"X-Forwarded-For"}, "192.0.2.1") assert.Equal(t, ip, "192.0.2.1") } func TestServer_TrustedRealClientIP_OneTrustedHeaderInvalid(t *testing.T) { req := httptest.NewRequest("GET", "/", nil) req.RemoteAddr = "192.0.2.1:12345" req.Header.Set("X-Forwarded-For", "not, an, ip") ip := trustedRealClientIP(req, []string{"X-Forwarded-For"}, "192.0.2.1") assert.Equal(t, ip, "192.0.2.1") } func TestServer_TrustedRealClientIP_OneTrustedHeaderValid(t *testing.T) { req := httptest.NewRequest("GET", "/", nil) req.RemoteAddr = "192.0.2.1:12345" req.Header.Set("X-Forwarded-For", "10.0.0.1") ip := trustedRealClientIP(req, []string{"X-Forwarded-For"}, "192.0.2.1") assert.Equal(t, ip, "10.0.0.1") } func TestServer_TrustedRealClientIP_OneTrustedHeaderValidArray(t *testing.T) { req := httptest.NewRequest("GET", "/", nil) req.RemoteAddr = "192.0.2.1:12345" req.Header.Set("X-Forwarded-For", "1.1.1.1, 2.2.2.2, 3.3.3.3") ip := trustedRealClientIP(req, []string{"X-Forwarded-For"}, "192.0.2.1") assert.Equal(t, ip, "1.1.1.1") } func TestServer_TrustedRealClientIP_IncludesPort(t *testing.T) { req := httptest.NewRequest("GET", "/", nil) req.RemoteAddr = "192.0.2.1:12345" req.Header.Set("X-Forwarded-For", "1.1.1.1:1234") ip := trustedRealClientIP(req, []string{"X-Forwarded-For"}, "192.0.2.1") assert.Equal(t, ip, "1.1.1.1") } func TestServer_TrustedRealClientIP_SkipsInvalidIps(t *testing.T) { req := httptest.NewRequest("GET", "/", nil) req.RemoteAddr = "192.0.2.1:12345" req.Header.Set("X-Forwarded-For", "not an ip, bad bad, 10.0.0.1") ip := trustedRealClientIP(req, []string{"X-Forwarded-For"}, "192.0.2.1") assert.Equal(t, ip, "10.0.0.1") } func TestServer_TrustedRealClientIP_MultipleTrustedHeaderValidArray(t *testing.T) { req := httptest.NewRequest("GET", "/", nil) req.RemoteAddr = "192.0.2.1:12345" req.Header.Set("Real-Client-IP", "1.1.1.1, 2.2.2.2, 3.3.3.3") req.Header.Set("X-Forwarded-For", "3.3.3.3, 4.4.4.4") ip1 := trustedRealClientIP(req, []string{"X-Forwarded-For", "Real-Client-IP"}, "192.0.2.1") ip2 := trustedRealClientIP(req, []string{"Real-Client-IP", "X-Forwarded-For"}, "192.0.2.1") ip3 := trustedRealClientIP(req, []string{"Missing-Header-IP", "Real-Client-IP", "X-Forwarded-For"}, "192.0.2.1") assert.Equal(t, ip1, "3.3.3.3") assert.Equal(t, ip2, "1.1.1.1") assert.Equal(t, ip3, "1.1.1.1") } func TestServer_DetermineTrustedProxy_NoConfig(t *testing.T) { server := &Server{} req := httptest.NewRequest("GET", "/", nil) req.RemoteAddr = "192.0.2.1:12345" trusted, clientIP := determineTrustedProxy(req, server) assert.False(t, trusted) assert.Equal(t, clientIP, "192.0.2.1") } func TestServer_DetermineTrustedProxy_NoConfigIpv6(t *testing.T) { server := &Server{} req := httptest.NewRequest("GET", "/", nil) req.RemoteAddr = "[::1]:12345" trusted, clientIP := determineTrustedProxy(req, server) assert.False(t, trusted) assert.Equal(t, clientIP, "::1") } func TestServer_DetermineTrustedProxy_NoConfigIpv6Zones(t *testing.T) { server := &Server{} req := httptest.NewRequest("GET", "/", nil) req.RemoteAddr = "[::1%eth2]:12345" trusted, clientIP := determineTrustedProxy(req, server) assert.False(t, trusted) assert.Equal(t, clientIP, "::1") } func TestServer_DetermineTrustedProxy_TrustedLoopback(t *testing.T) { loopbackPrefix, _ := netip.ParsePrefix("127.0.0.1/8") server := &Server{ trustedProxies: &StaticIPRange{ ranges: []netip.Prefix{loopbackPrefix}, }, ClientIPHeaders: []string{"X-Forwarded-For"}, } req := httptest.NewRequest("GET", "/", nil) req.RemoteAddr = "127.0.0.1:12345" req.Header.Set("X-Forwarded-For", "31.40.0.10") trusted, clientIP := determineTrustedProxy(req, server) assert.True(t, trusted) assert.Equal(t, clientIP, "31.40.0.10") } func TestServer_DetermineTrustedProxy_UnixSocket(t *testing.T) { server := &Server{ ClientIPHeaders: []string{"X-Forwarded-For"}, TrustedProxiesUnix: true, } req := httptest.NewRequest("GET", "/", nil) req.RemoteAddr = "@" req.Header.Set("X-Forwarded-For", "2.2.2.2, 3.3.3.3") trusted, clientIP := determineTrustedProxy(req, server) assert.True(t, trusted) assert.Equal(t, "2.2.2.2", clientIP) } func TestServer_DetermineTrustedProxy_UnixSocketStrict(t *testing.T) { server := &Server{ ClientIPHeaders: []string{"X-Forwarded-For"}, TrustedProxiesUnix: true, TrustedProxiesStrict: 1, } req := httptest.NewRequest("GET", "/", nil) req.RemoteAddr = "@" req.Header.Set("X-Forwarded-For", "2.2.2.2, 3.3.3.3") trusted, clientIP := determineTrustedProxy(req, server) assert.True(t, trusted) assert.Equal(t, "3.3.3.3", clientIP) } func TestServer_DetermineTrustedProxy_UntrustedPrefix(t *testing.T) { loopbackPrefix, _ := netip.ParsePrefix("127.0.0.1/8") server := &Server{ trustedProxies: &StaticIPRange{ ranges: []netip.Prefix{loopbackPrefix}, }, ClientIPHeaders: []string{"X-Forwarded-For"}, } req := httptest.NewRequest("GET", "/", nil) req.RemoteAddr = "10.0.0.1:12345" req.Header.Set("X-Forwarded-For", "31.40.0.10") trusted, clientIP := determineTrustedProxy(req, server) assert.False(t, trusted) assert.Equal(t, clientIP, "10.0.0.1") } func TestServer_DetermineTrustedProxy_MultipleTrustedPrefixes(t *testing.T) { loopbackPrefix, _ := netip.ParsePrefix("127.0.0.1/8") localPrivatePrefix, _ := netip.ParsePrefix("10.0.0.0/8") server := &Server{ trustedProxies: &StaticIPRange{ ranges: []netip.Prefix{loopbackPrefix, localPrivatePrefix}, }, ClientIPHeaders: []string{"X-Forwarded-For"}, } req := httptest.NewRequest("GET", "/", nil) req.RemoteAddr = "10.0.0.1:12345" req.Header.Set("X-Forwarded-For", "31.40.0.10") trusted, clientIP := determineTrustedProxy(req, server) assert.True(t, trusted) assert.Equal(t, clientIP, "31.40.0.10") } func TestServer_DetermineTrustedProxy_MultipleTrustedClientHeaders(t *testing.T) { loopbackPrefix, _ := netip.ParsePrefix("127.0.0.1/8") localPrivatePrefix, _ := netip.ParsePrefix("10.0.0.0/8") server := &Server{ trustedProxies: &StaticIPRange{ ranges: []netip.Prefix{loopbackPrefix, localPrivatePrefix}, }, ClientIPHeaders: []string{"CF-Connecting-IP", "X-Forwarded-For"}, } req := httptest.NewRequest("GET", "/", nil) req.RemoteAddr = "10.0.0.1:12345" req.Header.Set("CF-Connecting-IP", "1.1.1.1, 2.2.2.2") req.Header.Set("X-Forwarded-For", "3.3.3.3, 4.4.4.4") trusted, clientIP := determineTrustedProxy(req, server) assert.True(t, trusted) assert.Equal(t, clientIP, "1.1.1.1") } func TestServer_DetermineTrustedProxy_MatchLeftMostValidIp(t *testing.T) { localPrivatePrefix, _ := netip.ParsePrefix("10.0.0.0/8") server := &Server{ trustedProxies: &StaticIPRange{ ranges: []netip.Prefix{localPrivatePrefix}, }, ClientIPHeaders: []string{"X-Forwarded-For"}, } req := httptest.NewRequest("GET", "/", nil) req.RemoteAddr = "10.0.0.1:12345" req.Header.Set("X-Forwarded-For", "30.30.30.30, 45.54.45.54, 10.0.0.1") trusted, clientIP := determineTrustedProxy(req, server) assert.True(t, trusted) assert.Equal(t, clientIP, "30.30.30.30") } func TestServer_DetermineTrustedProxy_MatchRightMostUntrusted(t *testing.T) { localPrivatePrefix, _ := netip.ParsePrefix("10.0.0.0/8") server := &Server{ trustedProxies: &StaticIPRange{ ranges: []netip.Prefix{localPrivatePrefix}, }, ClientIPHeaders: []string{"X-Forwarded-For"}, TrustedProxiesStrict: 1, } req := httptest.NewRequest("GET", "/", nil) req.RemoteAddr = "10.0.0.1:12345" req.Header.Set("X-Forwarded-For", "30.30.30.30, 45.54.45.54, 10.0.0.1") trusted, clientIP := determineTrustedProxy(req, server) assert.True(t, trusted) assert.Equal(t, clientIP, "45.54.45.54") } func TestServer_DetermineTrustedProxy_MatchRightMostUntrustedSkippingEmpty(t *testing.T) { localPrivatePrefix, _ := netip.ParsePrefix("10.0.0.0/8") server := &Server{ trustedProxies: &StaticIPRange{ ranges: []netip.Prefix{localPrivatePrefix}, }, ClientIPHeaders: []string{"Missing-Header", "CF-Connecting-IP", "X-Forwarded-For"}, TrustedProxiesStrict: 1, } req := httptest.NewRequest("GET", "/", nil) req.RemoteAddr = "10.0.0.1:12345" req.Header.Set("CF-Connecting-IP", "not a real IP") req.Header.Set("X-Forwarded-For", "30.30.30.30, bad, 45.54.45.54, not real") trusted, clientIP := determineTrustedProxy(req, server) assert.True(t, trusted) assert.Equal(t, clientIP, "45.54.45.54") } func TestServer_DetermineTrustedProxy_MatchRightMostUntrustedSkippingTrusted(t *testing.T) { localPrivatePrefix, _ := netip.ParsePrefix("10.0.0.0/8") server := &Server{ trustedProxies: &StaticIPRange{ ranges: []netip.Prefix{localPrivatePrefix}, }, ClientIPHeaders: []string{"CF-Connecting-IP", "X-Forwarded-For"}, TrustedProxiesStrict: 1, } req := httptest.NewRequest("GET", "/", nil) req.RemoteAddr = "10.0.0.1:12345" req.Header.Set("CF-Connecting-IP", "10.0.0.1, 10.0.0.2, 10.0.0.3") req.Header.Set("X-Forwarded-For", "30.30.30.30, 45.54.45.54, 10.0.0.4") trusted, clientIP := determineTrustedProxy(req, server) assert.True(t, trusted) assert.Equal(t, clientIP, "45.54.45.54") } func TestServer_DetermineTrustedProxy_MatchRightMostUntrustedFirst(t *testing.T) { localPrivatePrefix, _ := netip.ParsePrefix("10.0.0.0/8") server := &Server{ trustedProxies: &StaticIPRange{ ranges: []netip.Prefix{localPrivatePrefix}, }, ClientIPHeaders: []string{"CF-Connecting-IP", "X-Forwarded-For"}, TrustedProxiesStrict: 1, } req := httptest.NewRequest("GET", "/", nil) req.RemoteAddr = "10.0.0.1:12345" req.Header.Set("CF-Connecting-IP", "10.0.0.1, 90.100.110.120, 10.0.0.2, 10.0.0.3") req.Header.Set("X-Forwarded-For", "30.30.30.30, 45.54.45.54, 10.0.0.4") trusted, clientIP := determineTrustedProxy(req, server) assert.True(t, trusted) assert.Equal(t, clientIP, "90.100.110.120") }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/errors.go
modules/caddyhttp/errors.go
// Copyright 2015 Matthew Holt and The Caddy 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 caddyhttp import ( "errors" "fmt" weakrand "math/rand" "path" "runtime" "strings" "github.com/caddyserver/caddy/v2" ) // Error is a convenient way for a Handler to populate the // essential fields of a HandlerError. If err is itself a // HandlerError, then any essential fields that are not // set will be populated. func Error(statusCode int, err error) HandlerError { const idLen = 9 var he HandlerError if errors.As(err, &he) { if he.ID == "" { he.ID = randString(idLen, true) } if he.Trace == "" { he.Trace = trace() } if he.StatusCode == 0 { he.StatusCode = statusCode } return he } return HandlerError{ ID: randString(idLen, true), StatusCode: statusCode, Err: err, Trace: trace(), } } // HandlerError is a serializable representation of // an error from within an HTTP handler. type HandlerError struct { Err error // the original error value and message StatusCode int // the HTTP status code to associate with this error ID string // generated; for identifying this error in logs Trace string // produced from call stack } func (e HandlerError) Error() string { var s string if e.ID != "" { s += fmt.Sprintf("{id=%s}", e.ID) } if e.Trace != "" { s += " " + e.Trace } if e.StatusCode != 0 { s += fmt.Sprintf(": HTTP %d", e.StatusCode) } if e.Err != nil { s += ": " + e.Err.Error() } return strings.TrimSpace(s) } // Unwrap returns the underlying error value. See the `errors` package for info. func (e HandlerError) Unwrap() error { return e.Err } // randString returns a string of n random characters. // It is not even remotely secure OR a proper distribution. // But it's good enough for some things. It excludes certain // confusing characters like I, l, 1, 0, O, etc. If sameCase // is true, then uppercase letters are excluded. func randString(n int, sameCase bool) string { if n <= 0 { return "" } dict := []byte("abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRTUVWXY23456789") if sameCase { dict = []byte("abcdefghijkmnpqrstuvwxyz0123456789") } b := make([]byte, n) for i := range b { //nolint:gosec b[i] = dict[weakrand.Int63()%int64(len(dict))] } return string(b) } func trace() string { if pc, file, line, ok := runtime.Caller(2); ok { filename := path.Base(file) pkgAndFuncName := path.Base(runtime.FuncForPC(pc).Name()) return fmt.Sprintf("%s (%s:%d)", pkgAndFuncName, filename, line) } return "" } // ErrorCtxKey is the context key to use when storing // an error (for use with context.Context). const ErrorCtxKey = caddy.CtxKey("handler_chain_error")
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/staticresp_test.go
modules/caddyhttp/staticresp_test.go
// Copyright 2015 Matthew Holt and The Caddy 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 caddyhttp import ( "context" "io" "net/http" "net/http/httptest" "strconv" "testing" "github.com/caddyserver/caddy/v2" ) func TestStaticResponseHandler(t *testing.T) { r := fakeRequest() w := httptest.NewRecorder() s := StaticResponse{ StatusCode: WeakString(strconv.Itoa(http.StatusNotFound)), Headers: http.Header{ "X-Test": []string{"Testing"}, }, Body: "Text", Close: true, } err := s.ServeHTTP(w, r, nil) if err != nil { t.Errorf("did not expect an error, but got: %v", err) } resp := w.Result() respBody, _ := io.ReadAll(resp.Body) if resp.StatusCode != http.StatusNotFound { t.Errorf("expected status %d but got %d", http.StatusNotFound, resp.StatusCode) } if resp.Header.Get("X-Test") != "Testing" { t.Errorf("expected x-test header to be 'testing' but was '%s'", resp.Header.Get("X-Test")) } if string(respBody) != "Text" { t.Errorf("expected body to be 'test' but was '%s'", respBody) } } func fakeRequest() *http.Request { r, _ := http.NewRequest("GET", "/", nil) repl := caddy.NewReplacer() ctx := context.WithValue(r.Context(), caddy.ReplacerCtxKey, repl) r = r.WithContext(ctx) return r }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/celmatcher_test.go
modules/caddyhttp/celmatcher_test.go
// Copyright 2015 Matthew Holt and The Caddy 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 caddyhttp import ( "context" "crypto/tls" "crypto/x509" "encoding/pem" "net/http" "net/http/httptest" "testing" "github.com/caddyserver/caddy/v2" ) var ( clientCert = []byte(`-----BEGIN CERTIFICATE----- MIIB9jCCAV+gAwIBAgIBAjANBgkqhkiG9w0BAQsFADAYMRYwFAYDVQQDDA1DYWRk eSBUZXN0IENBMB4XDTE4MDcyNDIxMzUwNVoXDTI4MDcyMTIxMzUwNVowHTEbMBkG A1UEAwwSY2xpZW50LmxvY2FsZG9tYWluMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCB iQKBgQDFDEpzF0ew68teT3xDzcUxVFaTII+jXH1ftHXxxP4BEYBU4q90qzeKFneF z83I0nC0WAQ45ZwHfhLMYHFzHPdxr6+jkvKPASf0J2v2HDJuTM1bHBbik5Ls5eq+ fVZDP8o/VHKSBKxNs8Goc2NTsr5b07QTIpkRStQK+RJALk4x9QIDAQABo0swSTAJ BgNVHRMEAjAAMAsGA1UdDwQEAwIHgDAaBgNVHREEEzARgglsb2NhbGhvc3SHBH8A AAEwEwYDVR0lBAwwCgYIKwYBBQUHAwIwDQYJKoZIhvcNAQELBQADgYEANSjz2Sk+ eqp31wM9il1n+guTNyxJd+FzVAH+hCZE5K+tCgVDdVFUlDEHHbS/wqb2PSIoouLV 3Q9fgDkiUod+uIK0IynzIKvw+Cjg+3nx6NQ0IM0zo8c7v398RzB4apbXKZyeeqUH 9fNwfEi+OoXR6s+upSKobCmLGLGi9Na5s5g= -----END CERTIFICATE-----`) matcherTests = []struct { name string expression *MatchExpression urlTarget string httpMethod string httpHeader *http.Header wantErr bool wantResult bool clientCertificate []byte }{ { name: "boolean matches succeed for placeholder http.request.tls.client.subject", expression: &MatchExpression{ Expr: "{http.request.tls.client.subject} == 'CN=client.localdomain'", }, clientCertificate: clientCert, urlTarget: "https://example.com/foo", wantResult: true, }, { name: "header matches (MatchHeader)", expression: &MatchExpression{ Expr: `header({'Field': 'foo'})`, }, urlTarget: "https://example.com/foo", httpHeader: &http.Header{"Field": []string{"foo", "bar"}}, wantResult: true, }, { name: "header matches an escaped placeholder value (MatchHeader)", expression: &MatchExpression{ Expr: `header({'Field': '\\\{foobar}'})`, }, urlTarget: "https://example.com/foo", httpHeader: &http.Header{"Field": []string{"{foobar}"}}, wantResult: true, }, { name: "header matches an placeholder replaced during the header matcher (MatchHeader)", expression: &MatchExpression{ Expr: `header({'Field': '\{http.request.uri.path}'})`, }, urlTarget: "https://example.com/foo", httpHeader: &http.Header{"Field": []string{"/foo"}}, wantResult: true, }, { name: "header error, invalid escape sequence (MatchHeader)", expression: &MatchExpression{ Expr: `header({'Field': '\\{foobar}'})`, }, wantErr: true, }, { name: "header error, needs to be JSON syntax with field as key (MatchHeader)", expression: &MatchExpression{ Expr: `header('foo')`, }, wantErr: true, }, { name: "header_regexp matches (MatchHeaderRE)", expression: &MatchExpression{ Expr: `header_regexp('Field', 'fo{2}')`, }, urlTarget: "https://example.com/foo", httpHeader: &http.Header{"Field": []string{"foo", "bar"}}, wantResult: true, }, { name: "header_regexp matches with name (MatchHeaderRE)", expression: &MatchExpression{ Expr: `header_regexp('foo', 'Field', 'fo{2}')`, }, urlTarget: "https://example.com/foo", httpHeader: &http.Header{"Field": []string{"foo", "bar"}}, wantResult: true, }, { name: "header_regexp does not match (MatchHeaderRE)", expression: &MatchExpression{ Expr: `header_regexp('foo', 'Nope', 'fo{2}')`, }, urlTarget: "https://example.com/foo", httpHeader: &http.Header{"Field": []string{"foo", "bar"}}, wantResult: false, }, { name: "header_regexp error (MatchHeaderRE)", expression: &MatchExpression{ Expr: `header_regexp('foo')`, }, wantErr: true, }, { name: "host matches localhost (MatchHost)", expression: &MatchExpression{ Expr: `host('localhost')`, }, urlTarget: "http://localhost", wantResult: true, }, { name: "host matches (MatchHost)", expression: &MatchExpression{ Expr: `host('*.example.com')`, }, urlTarget: "https://foo.example.com", wantResult: true, }, { name: "host does not match (MatchHost)", expression: &MatchExpression{ Expr: `host('example.net', '*.example.com')`, }, urlTarget: "https://foo.example.org", wantResult: false, }, { name: "host error (MatchHost)", expression: &MatchExpression{ Expr: `host(80)`, }, wantErr: true, }, { name: "method does not match (MatchMethod)", expression: &MatchExpression{ Expr: `method('PUT')`, }, urlTarget: "https://foo.example.com", httpMethod: "GET", wantResult: false, }, { name: "method matches (MatchMethod)", expression: &MatchExpression{ Expr: `method('DELETE', 'PUT', 'POST')`, }, urlTarget: "https://foo.example.com", httpMethod: "PUT", wantResult: true, }, { name: "method error not enough arguments (MatchMethod)", expression: &MatchExpression{ Expr: `method()`, }, wantErr: true, }, { name: "path matches substring (MatchPath)", expression: &MatchExpression{ Expr: `path('*substring*')`, }, urlTarget: "https://example.com/foo/substring/bar.txt", wantResult: true, }, { name: "path does not match (MatchPath)", expression: &MatchExpression{ Expr: `path('/foo')`, }, urlTarget: "https://example.com/foo/bar", wantResult: false, }, { name: "path matches end url fragment (MatchPath)", expression: &MatchExpression{ Expr: `path('/foo')`, }, urlTarget: "https://example.com/FOO", wantResult: true, }, { name: "path matches end fragment with substring prefix (MatchPath)", expression: &MatchExpression{ Expr: `path('/foo*')`, }, urlTarget: "https://example.com/FOOOOO", wantResult: true, }, { name: "path matches one of multiple (MatchPath)", expression: &MatchExpression{ Expr: `path('/foo', '/foo/*', '/bar', '/bar/*', '/baz', '/baz*')`, }, urlTarget: "https://example.com/foo", wantResult: true, }, { name: "path_regexp with empty regex matches empty path (MatchPathRE)", expression: &MatchExpression{ Expr: `path_regexp('')`, }, urlTarget: "https://example.com/", wantResult: true, }, { name: "path_regexp with slash regex matches empty path (MatchPathRE)", expression: &MatchExpression{ Expr: `path_regexp('/')`, }, urlTarget: "https://example.com/", wantResult: true, }, { name: "path_regexp matches end url fragment (MatchPathRE)", expression: &MatchExpression{ Expr: `path_regexp('^/foo')`, }, urlTarget: "https://example.com/foo/", wantResult: true, }, { name: "path_regexp does not match fragment at end (MatchPathRE)", expression: &MatchExpression{ Expr: `path_regexp('bar_at_start', '^/bar')`, }, urlTarget: "https://example.com/foo/bar", wantResult: false, }, { name: "protocol matches (MatchProtocol)", expression: &MatchExpression{ Expr: `protocol('HTTPs')`, }, urlTarget: "https://example.com", wantResult: true, }, { name: "protocol does not match (MatchProtocol)", expression: &MatchExpression{ Expr: `protocol('grpc')`, }, urlTarget: "https://example.com", wantResult: false, }, { name: "protocol invocation error no args (MatchProtocol)", expression: &MatchExpression{ Expr: `protocol()`, }, wantErr: true, }, { name: "protocol invocation error too many args (MatchProtocol)", expression: &MatchExpression{ Expr: `protocol('grpc', 'https')`, }, wantErr: true, }, { name: "protocol invocation error wrong arg type (MatchProtocol)", expression: &MatchExpression{ Expr: `protocol(true)`, }, wantErr: true, }, { name: "query does not match against a specific value (MatchQuery)", expression: &MatchExpression{ Expr: `query({"debug": "1"})`, }, urlTarget: "https://example.com/foo", wantResult: false, }, { name: "query matches against a specific value (MatchQuery)", expression: &MatchExpression{ Expr: `query({"debug": "1"})`, }, urlTarget: "https://example.com/foo/?debug=1", wantResult: true, }, { name: "query matches against multiple values (MatchQuery)", expression: &MatchExpression{ Expr: `query({"debug": ["0", "1", {http.request.uri.query.debug}+"1"]})`, }, urlTarget: "https://example.com/foo/?debug=1", wantResult: true, }, { name: "query matches against a wildcard (MatchQuery)", expression: &MatchExpression{ Expr: `query({"debug": ["*"]})`, }, urlTarget: "https://example.com/foo/?debug=something", wantResult: true, }, { name: "query matches against a placeholder value (MatchQuery)", expression: &MatchExpression{ Expr: `query({"debug": {http.request.uri.query.debug}})`, }, urlTarget: "https://example.com/foo/?debug=1", wantResult: true, }, { name: "query error bad map key type (MatchQuery)", expression: &MatchExpression{ Expr: `query({1: "1"})`, }, wantErr: true, }, { name: "query error typed struct instead of map (MatchQuery)", expression: &MatchExpression{ Expr: `query(Message{field: "1"})`, }, wantErr: true, }, { name: "query error bad map value type (MatchQuery)", expression: &MatchExpression{ Expr: `query({"debug": 1})`, }, wantErr: true, }, { name: "query error no args (MatchQuery)", expression: &MatchExpression{ Expr: `query()`, }, wantErr: true, }, { name: "remote_ip error no args (MatchRemoteIP)", expression: &MatchExpression{ Expr: `remote_ip()`, }, wantErr: true, }, { name: "remote_ip single IP match (MatchRemoteIP)", expression: &MatchExpression{ Expr: `remote_ip('192.0.2.1')`, }, urlTarget: "https://example.com/foo", wantResult: true, }, { name: "vars value (VarsMatcher)", expression: &MatchExpression{ Expr: `vars({'foo': 'bar'})`, }, urlTarget: "https://example.com/foo", wantResult: true, }, { name: "vars matches placeholder, needs escape (VarsMatcher)", expression: &MatchExpression{ Expr: `vars({'\{http.request.uri.path}': '/foo'})`, }, urlTarget: "https://example.com/foo", wantResult: true, }, { name: "vars error wrong syntax (VarsMatcher)", expression: &MatchExpression{ Expr: `vars('foo', 'bar')`, }, wantErr: true, }, { name: "vars error no args (VarsMatcher)", expression: &MatchExpression{ Expr: `vars()`, }, wantErr: true, }, { name: "vars_regexp value (MatchVarsRE)", expression: &MatchExpression{ Expr: `vars_regexp('foo', 'ba?r')`, }, urlTarget: "https://example.com/foo", wantResult: true, }, { name: "vars_regexp value with name (MatchVarsRE)", expression: &MatchExpression{ Expr: `vars_regexp('name', 'foo', 'ba?r')`, }, urlTarget: "https://example.com/foo", wantResult: true, }, { name: "vars_regexp matches placeholder, needs escape (MatchVarsRE)", expression: &MatchExpression{ Expr: `vars_regexp('\{http.request.uri.path}', '/fo?o')`, }, urlTarget: "https://example.com/foo", wantResult: true, }, { name: "vars_regexp error no args (MatchVarsRE)", expression: &MatchExpression{ Expr: `vars_regexp()`, }, wantErr: true, }, } ) func TestMatchExpressionMatch(t *testing.T) { for _, tst := range matcherTests { tc := tst t.Run(tc.name, func(t *testing.T) { caddyCtx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()}) defer cancel() err := tc.expression.Provision(caddyCtx) if err != nil { if !tc.wantErr { t.Errorf("MatchExpression.Provision() error = %v, wantErr %v", err, tc.wantErr) } return } req := httptest.NewRequest(tc.httpMethod, tc.urlTarget, nil) if tc.httpHeader != nil { req.Header = *tc.httpHeader } repl := caddy.NewReplacer() ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl) ctx = context.WithValue(ctx, VarsCtxKey, map[string]any{ "foo": "bar", }) req = req.WithContext(ctx) addHTTPVarsToReplacer(repl, req, httptest.NewRecorder()) if tc.clientCertificate != nil { block, _ := pem.Decode(clientCert) if block == nil { t.Fatalf("failed to decode PEM certificate") } cert, err := x509.ParseCertificate(block.Bytes) if err != nil { t.Fatalf("failed to decode PEM certificate: %v", err) } req.TLS = &tls.ConnectionState{ PeerCertificates: []*x509.Certificate{cert}, } } matches, err := tc.expression.MatchWithError(req) if err != nil { t.Errorf("MatchExpression.Match() error = %v", err) } if matches != tc.wantResult { t.Errorf("MatchExpression.Match() expected to return '%t', for expression : '%s'", tc.wantResult, tc.expression.Expr) } }) } } func BenchmarkMatchExpressionMatch(b *testing.B) { for _, tst := range matcherTests { tc := tst if tc.wantErr { continue } b.Run(tst.name, func(b *testing.B) { tc.expression.Provision(caddy.Context{}) req := httptest.NewRequest(tc.httpMethod, tc.urlTarget, nil) if tc.httpHeader != nil { req.Header = *tc.httpHeader } repl := caddy.NewReplacer() ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl) ctx = context.WithValue(ctx, VarsCtxKey, map[string]any{ "foo": "bar", }) req = req.WithContext(ctx) addHTTPVarsToReplacer(repl, req, httptest.NewRecorder()) if tc.clientCertificate != nil { block, _ := pem.Decode(clientCert) if block == nil { b.Fatalf("failed to decode PEM certificate") } cert, err := x509.ParseCertificate(block.Bytes) if err != nil { b.Fatalf("failed to decode PEM certificate: %v", err) } req.TLS = &tls.ConnectionState{ PeerCertificates: []*x509.Certificate{cert}, } } b.ResetTimer() for b.Loop() { tc.expression.MatchWithError(req) } }) } } func TestMatchExpressionProvision(t *testing.T) { tests := []struct { name string expression *MatchExpression wantErr bool }{ { name: "boolean matches succeed", expression: &MatchExpression{ Expr: "{http.request.uri.query} != ''", }, wantErr: false, }, { name: "reject expressions with non-boolean results", expression: &MatchExpression{ Expr: "{http.request.uri.query}", }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()}) defer cancel() if err := tt.expression.Provision(ctx); (err != nil) != tt.wantErr { t.Errorf("MatchExpression.Provision() error = %v, wantErr %v", err, tt.wantErr) } }) } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/staticerror.go
modules/caddyhttp/staticerror.go
// Copyright 2015 Matthew Holt and The Caddy 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 caddyhttp import ( "fmt" "net/http" "strconv" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func init() { caddy.RegisterModule(StaticError{}) } // StaticError implements a simple handler that returns an error. // This handler returns an error value, but does not write a response. // This is useful when you want the server to act as if an error // occurred; for example, to invoke your custom error handling logic. // // Since this handler does not write a response, the error information // is for use by the server to know how to handle the error. type StaticError struct { // The error message. Optional. Default is no error message. Error string `json:"error,omitempty"` // The recommended HTTP status code. Can be either an integer or a // string if placeholders are needed. Optional. Default is 500. StatusCode WeakString `json:"status_code,omitempty"` } // CaddyModule returns the Caddy module information. func (StaticError) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.handlers.error", New: func() caddy.Module { return new(StaticError) }, } } // UnmarshalCaddyfile sets up the handler from Caddyfile tokens. Syntax: // // error [<matcher>] <status>|<message> [<status>] { // message <text> // } // // If there is just one argument (other than the matcher), it is considered // to be a status code if it's a valid positive integer of 3 digits. func (e *StaticError) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume directive name args := d.RemainingArgs() switch len(args) { case 1: if len(args[0]) == 3 { if num, err := strconv.Atoi(args[0]); err == nil && num > 0 { e.StatusCode = WeakString(args[0]) break } } e.Error = args[0] case 2: e.Error = args[0] e.StatusCode = WeakString(args[1]) default: return d.ArgErr() } for d.NextBlock(0) { switch d.Val() { case "message": if e.Error != "" { return d.Err("message already specified") } if !d.AllArgs(&e.Error) { return d.ArgErr() } default: return d.Errf("unrecognized subdirective '%s'", d.Val()) } } return nil } func (e StaticError) ServeHTTP(w http.ResponseWriter, r *http.Request, _ Handler) error { repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) statusCode := http.StatusInternalServerError if codeStr := e.StatusCode.String(); codeStr != "" { intVal, err := strconv.Atoi(repl.ReplaceAll(codeStr, "")) if err != nil { return Error(http.StatusInternalServerError, err) } statusCode = intVal } return Error(statusCode, fmt.Errorf("%s", repl.ReplaceKnown(e.Error, ""))) } // Interface guard var ( _ MiddlewareHandler = (*StaticError)(nil) _ caddyfile.Unmarshaler = (*StaticError)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/ip_matchers.go
modules/caddyhttp/ip_matchers.go
// Copyright 2015 Matthew Holt and The Caddy 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 caddyhttp import ( "errors" "fmt" "net" "net/http" "net/netip" "strings" "github.com/google/cel-go/cel" "github.com/google/cel-go/common/types/ref" "go.uber.org/zap" "go.uber.org/zap/zapcore" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/internal" ) // MatchRemoteIP matches requests by the remote IP address, // i.e. the IP address of the direct connection to Caddy. type MatchRemoteIP struct { // The IPs or CIDR ranges to match. Ranges []string `json:"ranges,omitempty"` // cidrs and zones vars should aligned always in the same // length and indexes for matching later cidrs []*netip.Prefix zones []string logger *zap.Logger } // MatchClientIP matches requests by the client IP address, // i.e. the resolved address, considering trusted proxies. type MatchClientIP struct { // The IPs or CIDR ranges to match. Ranges []string `json:"ranges,omitempty"` // cidrs and zones vars should aligned always in the same // length and indexes for matching later cidrs []*netip.Prefix zones []string logger *zap.Logger } func init() { caddy.RegisterModule(MatchRemoteIP{}) caddy.RegisterModule(MatchClientIP{}) } // CaddyModule returns the Caddy module information. func (MatchRemoteIP) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.matchers.remote_ip", New: func() caddy.Module { return new(MatchRemoteIP) }, } } // UnmarshalCaddyfile implements caddyfile.Unmarshaler. func (m *MatchRemoteIP) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { // iterate to merge multiple matchers into one for d.Next() { for d.NextArg() { if d.Val() == "forwarded" { return d.Err("the 'forwarded' option is no longer supported; use the 'client_ip' matcher instead") } if d.Val() == "private_ranges" { m.Ranges = append(m.Ranges, internal.PrivateRangesCIDR()...) continue } m.Ranges = append(m.Ranges, d.Val()) } if d.NextBlock(0) { return d.Err("malformed remote_ip matcher: blocks are not supported") } } return nil } // CELLibrary produces options that expose this matcher for use in CEL // expression matchers. // // Example: // // expression remote_ip('192.168.0.0/16', '172.16.0.0/12', '10.0.0.0/8') func (MatchRemoteIP) CELLibrary(ctx caddy.Context) (cel.Library, error) { return CELMatcherImpl( // name of the macro, this is the function name that users see when writing expressions. "remote_ip", // name of the function that the macro will be rewritten to call. "remote_ip_match_request_list", // internal data type of the MatchPath value. []*cel.Type{cel.ListType(cel.StringType)}, // function to convert a constant list of strings to a MatchPath instance. func(data ref.Val) (RequestMatcherWithError, error) { refStringList := stringSliceType strList, err := data.ConvertToNative(refStringList) if err != nil { return nil, err } m := MatchRemoteIP{} for _, input := range strList.([]string) { if input == "forwarded" { return nil, errors.New("the 'forwarded' option is no longer supported; use the 'client_ip' matcher instead") } m.Ranges = append(m.Ranges, input) } err = m.Provision(ctx) return m, err }, ) } // Provision parses m's IP ranges, either from IP or CIDR expressions. func (m *MatchRemoteIP) Provision(ctx caddy.Context) error { m.logger = ctx.Logger() cidrs, zones, err := provisionCidrsZonesFromRanges(m.Ranges) if err != nil { return err } m.cidrs = cidrs m.zones = zones return nil } // Match returns true if r matches m. func (m MatchRemoteIP) Match(r *http.Request) bool { match, err := m.MatchWithError(r) if err != nil { SetVar(r.Context(), MatcherErrorVarKey, err) } return match } // MatchWithError returns true if r matches m. func (m MatchRemoteIP) MatchWithError(r *http.Request) (bool, error) { // if handshake is not finished, we infer 0-RTT that has // not verified remote IP; could be spoofed, so we throw // HTTP 425 status to tell the client to try again after // the handshake is complete if r.TLS != nil && !r.TLS.HandshakeComplete { return false, Error(http.StatusTooEarly, fmt.Errorf("TLS handshake not complete, remote IP cannot be verified")) } address := r.RemoteAddr clientIP, zoneID, err := parseIPZoneFromString(address) if err != nil { if c := m.logger.Check(zapcore.ErrorLevel, "getting remote "); c != nil { c.Write(zap.Error(err)) } return false, nil } matches, zoneFilter := matchIPByCidrZones(clientIP, zoneID, m.cidrs, m.zones) if !matches && !zoneFilter { if c := m.logger.Check(zapcore.DebugLevel, "zone ID from remote IP did not match"); c != nil { c.Write(zap.String("zone", zoneID)) } } return matches, nil } // CaddyModule returns the Caddy module information. func (MatchClientIP) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.matchers.client_ip", New: func() caddy.Module { return new(MatchClientIP) }, } } // UnmarshalCaddyfile implements caddyfile.Unmarshaler. func (m *MatchClientIP) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { // iterate to merge multiple matchers into one for d.Next() { for d.NextArg() { if d.Val() == "private_ranges" { m.Ranges = append(m.Ranges, internal.PrivateRangesCIDR()...) continue } m.Ranges = append(m.Ranges, d.Val()) } if d.NextBlock(0) { return d.Err("malformed client_ip matcher: blocks are not supported") } } return nil } // CELLibrary produces options that expose this matcher for use in CEL // expression matchers. // // Example: // // expression client_ip('192.168.0.0/16', '172.16.0.0/12', '10.0.0.0/8') func (MatchClientIP) CELLibrary(ctx caddy.Context) (cel.Library, error) { return CELMatcherImpl( // name of the macro, this is the function name that users see when writing expressions. "client_ip", // name of the function that the macro will be rewritten to call. "client_ip_match_request_list", // internal data type of the MatchPath value. []*cel.Type{cel.ListType(cel.StringType)}, // function to convert a constant list of strings to a MatchPath instance. func(data ref.Val) (RequestMatcherWithError, error) { refStringList := stringSliceType strList, err := data.ConvertToNative(refStringList) if err != nil { return nil, err } m := MatchClientIP{ Ranges: strList.([]string), } err = m.Provision(ctx) return m, err }, ) } // Provision parses m's IP ranges, either from IP or CIDR expressions. func (m *MatchClientIP) Provision(ctx caddy.Context) error { m.logger = ctx.Logger() cidrs, zones, err := provisionCidrsZonesFromRanges(m.Ranges) if err != nil { return err } m.cidrs = cidrs m.zones = zones return nil } // Match returns true if r matches m. func (m MatchClientIP) Match(r *http.Request) bool { match, err := m.MatchWithError(r) if err != nil { SetVar(r.Context(), MatcherErrorVarKey, err) } return match } // MatchWithError returns true if r matches m. func (m MatchClientIP) MatchWithError(r *http.Request) (bool, error) { // if handshake is not finished, we infer 0-RTT that has // not verified remote IP; could be spoofed, so we throw // HTTP 425 status to tell the client to try again after // the handshake is complete if r.TLS != nil && !r.TLS.HandshakeComplete { return false, Error(http.StatusTooEarly, fmt.Errorf("TLS handshake not complete, remote IP cannot be verified")) } address := GetVar(r.Context(), ClientIPVarKey).(string) clientIP, zoneID, err := parseIPZoneFromString(address) if err != nil { m.logger.Error("getting client IP", zap.Error(err)) return false, nil } matches, zoneFilter := matchIPByCidrZones(clientIP, zoneID, m.cidrs, m.zones) if !matches && !zoneFilter { m.logger.Debug("zone ID from client IP did not match", zap.String("zone", zoneID)) } return matches, nil } func provisionCidrsZonesFromRanges(ranges []string) ([]*netip.Prefix, []string, error) { cidrs := []*netip.Prefix{} zones := []string{} repl := caddy.NewReplacer() for _, str := range ranges { str = repl.ReplaceAll(str, "") // Exclude the zone_id from the IP if strings.Contains(str, "%") { split := strings.Split(str, "%") str = split[0] // write zone identifiers in m.zones for matching later zones = append(zones, split[1]) } else { zones = append(zones, "") } if strings.Contains(str, "/") { ipNet, err := netip.ParsePrefix(str) if err != nil { return nil, nil, fmt.Errorf("parsing CIDR expression '%s': %v", str, err) } cidrs = append(cidrs, &ipNet) } else { ipAddr, err := netip.ParseAddr(str) if err != nil { return nil, nil, fmt.Errorf("invalid IP address: '%s': %v", str, err) } ipNew := netip.PrefixFrom(ipAddr, ipAddr.BitLen()) cidrs = append(cidrs, &ipNew) } } return cidrs, zones, nil } func parseIPZoneFromString(address string) (netip.Addr, string, error) { ipStr, _, err := net.SplitHostPort(address) if err != nil { ipStr = address // OK; probably didn't have a port } // Some IPv6-Addresses can contain zone identifiers at the end, // which are separated with "%" zoneID := "" if strings.Contains(ipStr, "%") { split := strings.Split(ipStr, "%") ipStr = split[0] zoneID = split[1] } ipAddr, err := netip.ParseAddr(ipStr) if err != nil { return netip.IPv4Unspecified(), "", err } return ipAddr, zoneID, nil } func matchIPByCidrZones(clientIP netip.Addr, zoneID string, cidrs []*netip.Prefix, zones []string) (bool, bool) { zoneFilter := true for i, ipRange := range cidrs { if ipRange.Contains(clientIP) { // Check if there are zone filters assigned and if they match. if zones[i] == "" || zoneID == zones[i] { return true, false } zoneFilter = false } } return false, zoneFilter } // Interface guards var ( _ RequestMatcherWithError = (*MatchRemoteIP)(nil) _ caddy.Provisioner = (*MatchRemoteIP)(nil) _ caddyfile.Unmarshaler = (*MatchRemoteIP)(nil) _ CELLibraryProducer = (*MatchRemoteIP)(nil) _ RequestMatcherWithError = (*MatchClientIP)(nil) _ caddy.Provisioner = (*MatchClientIP)(nil) _ caddyfile.Unmarshaler = (*MatchClientIP)(nil) _ CELLibraryProducer = (*MatchClientIP)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/marshalers.go
modules/caddyhttp/marshalers.go
// Copyright 2015 Matthew Holt and The Caddy 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 caddyhttp import ( "crypto/tls" "net" "net/http" "strings" "go.uber.org/zap/zapcore" ) // LoggableHTTPRequest makes an HTTP request loggable with zap.Object(). type LoggableHTTPRequest struct { *http.Request ShouldLogCredentials bool } // MarshalLogObject satisfies the zapcore.ObjectMarshaler interface. func (r LoggableHTTPRequest) MarshalLogObject(enc zapcore.ObjectEncoder) error { ip, port, err := net.SplitHostPort(r.RemoteAddr) if err != nil { ip = r.RemoteAddr port = "" } enc.AddString("remote_ip", ip) enc.AddString("remote_port", port) if ip, ok := GetVar(r.Context(), ClientIPVarKey).(string); ok { enc.AddString("client_ip", ip) } enc.AddString("proto", r.Proto) enc.AddString("method", r.Method) enc.AddString("host", r.Host) enc.AddString("uri", r.RequestURI) enc.AddObject("headers", LoggableHTTPHeader{ Header: r.Header, ShouldLogCredentials: r.ShouldLogCredentials, }) if r.TransferEncoding != nil { enc.AddArray("transfer_encoding", LoggableStringArray(r.TransferEncoding)) } if r.TLS != nil { enc.AddObject("tls", LoggableTLSConnState(*r.TLS)) } return nil } // LoggableHTTPHeader makes an HTTP header loggable with zap.Object(). // Headers with potentially sensitive information (Cookie, Set-Cookie, // Authorization, and Proxy-Authorization) are logged with empty values. type LoggableHTTPHeader struct { http.Header ShouldLogCredentials bool } // MarshalLogObject satisfies the zapcore.ObjectMarshaler interface. func (h LoggableHTTPHeader) MarshalLogObject(enc zapcore.ObjectEncoder) error { if h.Header == nil { return nil } for key, val := range h.Header { if !h.ShouldLogCredentials { switch strings.ToLower(key) { case "cookie", "set-cookie", "authorization", "proxy-authorization": val = []string{"REDACTED"} // see #5669. I still think ▒▒▒▒ would be cool. } } enc.AddArray(key, LoggableStringArray(val)) } return nil } // LoggableStringArray makes a slice of strings marshalable for logging. type LoggableStringArray []string // MarshalLogArray satisfies the zapcore.ArrayMarshaler interface. func (sa LoggableStringArray) MarshalLogArray(enc zapcore.ArrayEncoder) error { if sa == nil { return nil } for _, s := range sa { enc.AppendString(s) } return nil } // LoggableTLSConnState makes a TLS connection state loggable with zap.Object(). type LoggableTLSConnState tls.ConnectionState // MarshalLogObject satisfies the zapcore.ObjectMarshaler interface. func (t LoggableTLSConnState) MarshalLogObject(enc zapcore.ObjectEncoder) error { enc.AddBool("resumed", t.DidResume) enc.AddUint16("version", t.Version) enc.AddUint16("cipher_suite", t.CipherSuite) enc.AddString("proto", t.NegotiatedProtocol) enc.AddString("server_name", t.ServerName) enc.AddBool("ech", t.ECHAccepted) if len(t.PeerCertificates) > 0 { enc.AddString("client_common_name", t.PeerCertificates[0].Subject.CommonName) enc.AddString("client_serial", t.PeerCertificates[0].SerialNumber.String()) } return nil } // Interface guards var ( _ zapcore.ObjectMarshaler = (*LoggableHTTPRequest)(nil) _ zapcore.ObjectMarshaler = (*LoggableHTTPHeader)(nil) _ zapcore.ArrayMarshaler = (*LoggableStringArray)(nil) _ zapcore.ObjectMarshaler = (*LoggableTLSConnState)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/responsematchers_test.go
modules/caddyhttp/responsematchers_test.go
// Copyright 2015 Matthew Holt and The Caddy 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 caddyhttp import ( "net/http" "testing" ) func TestResponseMatcher(t *testing.T) { for i, tc := range []struct { require ResponseMatcher status int hdr http.Header // make sure these are canonical cased (std lib will do that in a real request) expect bool }{ { require: ResponseMatcher{}, status: 200, expect: true, }, { require: ResponseMatcher{ StatusCode: []int{200}, }, status: 200, expect: true, }, { require: ResponseMatcher{ StatusCode: []int{2}, }, status: 200, expect: true, }, { require: ResponseMatcher{ StatusCode: []int{201}, }, status: 200, expect: false, }, { require: ResponseMatcher{ StatusCode: []int{2}, }, status: 301, expect: false, }, { require: ResponseMatcher{ StatusCode: []int{3}, }, status: 301, expect: true, }, { require: ResponseMatcher{ StatusCode: []int{3}, }, status: 399, expect: true, }, { require: ResponseMatcher{ StatusCode: []int{3}, }, status: 400, expect: false, }, { require: ResponseMatcher{ StatusCode: []int{3, 4}, }, status: 400, expect: true, }, { require: ResponseMatcher{ StatusCode: []int{3, 401}, }, status: 401, expect: true, }, { require: ResponseMatcher{ Headers: http.Header{ "Foo": []string{"bar"}, }, }, hdr: http.Header{"Foo": []string{"bar"}}, expect: true, }, { require: ResponseMatcher{ Headers: http.Header{ "Foo2": []string{"bar"}, }, }, hdr: http.Header{"Foo": []string{"bar"}}, expect: false, }, { require: ResponseMatcher{ Headers: http.Header{ "Foo": []string{"bar", "baz"}, }, }, hdr: http.Header{"Foo": []string{"baz"}}, expect: true, }, { require: ResponseMatcher{ Headers: http.Header{ "Foo": []string{"bar"}, "Foo2": []string{"baz"}, }, }, hdr: http.Header{"Foo": []string{"baz"}}, expect: false, }, { require: ResponseMatcher{ Headers: http.Header{ "Foo": []string{"bar"}, "Foo2": []string{"baz"}, }, }, hdr: http.Header{"Foo": []string{"bar"}, "Foo2": []string{"baz"}}, expect: true, }, { require: ResponseMatcher{ Headers: http.Header{ "Foo": []string{"foo*"}, }, }, hdr: http.Header{"Foo": []string{"foobar"}}, expect: true, }, { require: ResponseMatcher{ Headers: http.Header{ "Foo": []string{"foo*"}, }, }, hdr: http.Header{"Foo": []string{"foobar"}}, expect: true, }, } { actual := tc.require.Match(tc.status, tc.hdr) if actual != tc.expect { t.Errorf("Test %d %v: Expected %t, got %t for HTTP %d %v", i, tc.require, tc.expect, actual, tc.status, tc.hdr) continue } } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/server.go
modules/caddyhttp/server.go
// Copyright 2015 Matthew Holt and The Caddy 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 caddyhttp import ( "context" "crypto/tls" "encoding/json" "fmt" "io" "net" "net/http" "net/netip" "net/url" "runtime" "slices" "strings" "sync" "time" "github.com/caddyserver/certmagic" "github.com/quic-go/quic-go" "github.com/quic-go/quic-go/http3" h3qlog "github.com/quic-go/quic-go/http3/qlog" "go.uber.org/zap" "go.uber.org/zap/zapcore" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyevents" "github.com/caddyserver/caddy/v2/modules/caddytls" ) // Server describes an HTTP server. type Server struct { // Socket addresses to which to bind listeners. Accepts // [network addresses](/docs/conventions#network-addresses) // that may include port ranges. Listener addresses must // be unique; they cannot be repeated across all defined // servers. Listen []string `json:"listen,omitempty"` // A list of listener wrapper modules, which can modify the behavior // of the base listener. They are applied in the given order. ListenerWrappersRaw []json.RawMessage `json:"listener_wrappers,omitempty" caddy:"namespace=caddy.listeners inline_key=wrapper"` // A list of packet conn wrapper modules, which can modify the behavior // of the base packet conn. They are applied in the given order. PacketConnWrappersRaw []json.RawMessage `json:"packet_conn_wrappers,omitempty" caddy:"namespace=caddy.packetconns inline_key=wrapper"` // How long to allow a read from a client's upload. Setting this // to a short, non-zero value can mitigate slowloris attacks, but // may also affect legitimately slow clients. ReadTimeout caddy.Duration `json:"read_timeout,omitempty"` // ReadHeaderTimeout is like ReadTimeout but for request headers. // Default is 1 minute. ReadHeaderTimeout caddy.Duration `json:"read_header_timeout,omitempty"` // WriteTimeout is how long to allow a write to a client. Note // that setting this to a small value when serving large files // may negatively affect legitimately slow clients. WriteTimeout caddy.Duration `json:"write_timeout,omitempty"` // IdleTimeout is the maximum time to wait for the next request // when keep-alives are enabled. If zero, a default timeout of // 5m is applied to help avoid resource exhaustion. IdleTimeout caddy.Duration `json:"idle_timeout,omitempty"` // KeepAliveInterval is the interval at which TCP keepalive packets // are sent to keep the connection alive at the TCP layer when no other // data is being transmitted. // If zero, the default is 15s. // If negative, keepalive packets are not sent and other keepalive parameters // are ignored. KeepAliveInterval caddy.Duration `json:"keepalive_interval,omitempty"` // KeepAliveIdle is the time that the connection must be idle before // the first TCP keep-alive probe is sent when no other data is being // transmitted. // If zero, the default is 15s. // If negative, underlying socket value is unchanged. KeepAliveIdle caddy.Duration `json:"keepalive_idle,omitempty"` // KeepAliveCount is the maximum number of TCP keep-alive probes that // should be sent before dropping a connection. // If zero, the default is 9. // If negative, underlying socket value is unchanged. KeepAliveCount int `json:"keepalive_count,omitempty"` // MaxHeaderBytes is the maximum size to parse from a client's // HTTP request headers. MaxHeaderBytes int `json:"max_header_bytes,omitempty"` // Enable full-duplex communication for HTTP/1 requests. // Only has an effect if Caddy was built with Go 1.21 or later. // // For HTTP/1 requests, the Go HTTP server by default consumes any // unread portion of the request body before beginning to write the // response, preventing handlers from concurrently reading from the // request and writing the response. Enabling this option disables // this behavior and permits handlers to continue to read from the // request while concurrently writing the response. // // For HTTP/2 requests, the Go HTTP server always permits concurrent // reads and responses, so this option has no effect. // // Test thoroughly with your HTTP clients, as some older clients may // not support full-duplex HTTP/1 which can cause them to deadlock. // See https://github.com/golang/go/issues/57786 for more info. // // TODO: This is an EXPERIMENTAL feature. Subject to change or removal. EnableFullDuplex bool `json:"enable_full_duplex,omitempty"` // Routes describes how this server will handle requests. // Routes are executed sequentially. First a route's matchers // are evaluated, then its grouping. If it matches and has // not been mutually-excluded by its grouping, then its // handlers are executed sequentially. The sequence of invoked // handlers comprises a compiled middleware chain that flows // from each matching route and its handlers to the next. // // By default, all unrouted requests receive a 200 OK response // to indicate the server is working. Routes RouteList `json:"routes,omitempty"` // Errors is how this server will handle errors returned from any // of the handlers in the primary routes. If the primary handler // chain returns an error, the error along with its recommended // status code are bubbled back up to the HTTP server which // executes a separate error route, specified using this property. // The error routes work exactly like the normal routes. Errors *HTTPErrorConfig `json:"errors,omitempty"` // NamedRoutes describes a mapping of reusable routes that can be // invoked by their name. This can be used to optimize memory usage // when the same route is needed for many subroutes, by having // the handlers and matchers be only provisioned once, but used from // many places. These routes are not executed unless they are invoked // from another route. // // EXPERIMENTAL: Subject to change or removal. NamedRoutes map[string]*Route `json:"named_routes,omitempty"` // How to handle TLS connections. At least one policy is // required to enable HTTPS on this server if automatic // HTTPS is disabled or does not apply. TLSConnPolicies caddytls.ConnectionPolicies `json:"tls_connection_policies,omitempty"` // AutoHTTPS configures or disables automatic HTTPS within this server. // HTTPS is enabled automatically and by default when qualifying names // are present in a Host matcher and/or when the server is listening // only on the HTTPS port. AutoHTTPS *AutoHTTPSConfig `json:"automatic_https,omitempty"` // If true, will require that a request's Host header match // the value of the ServerName sent by the client's TLS // ClientHello; often a necessary safeguard when using TLS // client authentication. StrictSNIHost *bool `json:"strict_sni_host,omitempty"` // A module which provides a source of IP ranges, from which // requests should be trusted. By default, no proxies are // trusted. // // On its own, this configuration will not do anything, // but it can be used as a default set of ranges for // handlers or matchers in routes to pick up, instead // of needing to configure each of them. See the // `reverse_proxy` handler for example, which uses this // to trust sensitive incoming `X-Forwarded-*` headers. TrustedProxiesRaw json.RawMessage `json:"trusted_proxies,omitempty" caddy:"namespace=http.ip_sources inline_key=source"` // The headers from which the client IP address could be // read from. These will be considered in order, with the // first good value being used as the client IP. // By default, only `X-Forwarded-For` is considered. // // This depends on `trusted_proxies` being configured and // the request being validated as coming from a trusted // proxy, otherwise the client IP will be set to the direct // remote IP address. ClientIPHeaders []string `json:"client_ip_headers,omitempty"` // If greater than zero, enables strict ClientIPHeaders // (default X-Forwarded-For) parsing. If enabled, the // ClientIPHeaders will be parsed from right to left, and // the first value that is both valid and doesn't match the // trusted proxy list will be used as client IP. If zero, // the ClientIPHeaders will be parsed from left to right, // and the first value that is a valid IP address will be // used as client IP. // // This depends on `trusted_proxies` being configured. // This option is disabled by default. TrustedProxiesStrict int `json:"trusted_proxies_strict,omitempty"` // If greater than zero, enables trusting socket connections // (e.g. Unix domain sockets) as coming from a trusted // proxy. // // This option is disabled by default. TrustedProxiesUnix bool `json:"trusted_proxies_unix,omitempty"` // Enables access logging and configures how access logs are handled // in this server. To minimally enable access logs, simply set this // to a non-null, empty struct. Logs *ServerLogConfig `json:"logs,omitempty"` // Protocols specifies which HTTP protocols to enable. // Supported values are: // // - `h1` (HTTP/1.1) // - `h2` (HTTP/2) // - `h2c` (cleartext HTTP/2) // - `h3` (HTTP/3) // // If enabling `h2` or `h2c`, `h1` must also be enabled; // this is due to current limitations in the Go standard // library. // // HTTP/2 operates only over TLS (HTTPS). HTTP/3 opens // a UDP socket to serve QUIC connections. // // H2C operates over plain TCP if the client supports it; // however, because this is not implemented by the Go // standard library, other server options are not compatible // and will not be applied to H2C requests. Do not enable this // only to achieve maximum client compatibility. In practice, // very few clients implement H2C, and even fewer require it. // Enabling H2C can be useful for serving/proxying gRPC // if encryption is not possible or desired. // // We recommend for most users to simply let Caddy use the // default settings. // // Default: `[h1 h2 h3]` Protocols []string `json:"protocols,omitempty"` // ListenProtocols overrides Protocols for each parallel address in Listen. // A nil value or element indicates that Protocols will be used instead. ListenProtocols [][]string `json:"listen_protocols,omitempty"` // If set, metrics observations will be enabled. // This setting is EXPERIMENTAL and subject to change. // DEPRECATED: Use the app-level `metrics` field. Metrics *Metrics `json:"metrics,omitempty"` name string primaryHandlerChain Handler errorHandlerChain Handler listenerWrappers []caddy.ListenerWrapper packetConnWrappers []caddy.PacketConnWrapper listeners []net.Listener quicListeners []http3.QUICListener // http3 now leave the quic.Listener management to us tlsApp *caddytls.TLS events *caddyevents.App logger *zap.Logger accessLogger *zap.Logger errorLogger *zap.Logger traceLogger *zap.Logger ctx caddy.Context server *http.Server h3server *http3.Server addresses []caddy.NetworkAddress trustedProxies IPRangeSource shutdownAt time.Time shutdownAtMu *sync.RWMutex // registered callback functions connStateFuncs []func(net.Conn, http.ConnState) connContextFuncs []func(ctx context.Context, c net.Conn) context.Context onShutdownFuncs []func() onStopFuncs []func(context.Context) error // TODO: Experimental (Nov. 2023) } var ( ServerHeader = "Caddy" serverHeader = []string{ServerHeader} ) // ServeHTTP is the entry point for all HTTP requests. func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { // If there are listener wrappers that process tls connections but don't return a *tls.Conn, this field will be nil. if r.TLS == nil { if tlsConnStateFunc, ok := r.Context().Value(tlsConnectionStateFuncCtxKey).(func() *tls.ConnectionState); ok { r.TLS = tlsConnStateFunc() } } h := w.Header() h["Server"] = serverHeader // advertise HTTP/3, if enabled if s.h3server != nil && r.ProtoMajor < 3 { if err := s.h3server.SetQUICHeaders(h); err != nil { if c := s.logger.Check(zapcore.ErrorLevel, "setting HTTP/3 Alt-Svc header"); c != nil { c.Write(zap.Error(err)) } } } // reject very long methods; probably a mistake or an attack if len(r.Method) > 32 { if s.shouldLogRequest(r) { if c := s.accessLogger.Check(zapcore.DebugLevel, "rejecting request with long method"); c != nil { c.Write( zap.String("method_trunc", r.Method[:32]), zap.String("remote_addr", r.RemoteAddr), ) } } w.WriteHeader(http.StatusMethodNotAllowed) return } repl := caddy.NewReplacer() r = PrepareRequest(r, repl, w, s) // enable full-duplex for HTTP/1, ensuring the entire // request body gets consumed before writing the response if s.EnableFullDuplex && r.ProtoMajor == 1 { if err := http.NewResponseController(w).EnableFullDuplex(); err != nil { //nolint:bodyclose if c := s.logger.Check(zapcore.WarnLevel, "failed to enable full duplex"); c != nil { c.Write(zap.Error(err)) } } } // clone the request for logging purposes before // it enters any handler chain; this is necessary // to capture the original request in case it gets // modified during handling // cloning the request and using .WithLazy is considerably faster // than using .With, which will JSON encode the request immediately shouldLogCredentials := s.Logs != nil && s.Logs.ShouldLogCredentials loggableReq := zap.Object("request", LoggableHTTPRequest{ Request: r.Clone(r.Context()), ShouldLogCredentials: shouldLogCredentials, }) errLog := s.errorLogger.WithLazy(loggableReq) var duration time.Duration if s.shouldLogRequest(r) { wrec := NewResponseRecorder(w, nil, nil) w = wrec // wrap the request body in a LengthReader // so we can track the number of bytes read from it var bodyReader *lengthReader if r.Body != nil { bodyReader = &lengthReader{Source: r.Body} r.Body = bodyReader // should always be true, private interface can only be referenced in the same package if setReadSizer, ok := wrec.(interface{ setReadSize(*int) }); ok { setReadSizer.setReadSize(&bodyReader.Length) } } // capture the original version of the request accLog := s.accessLogger.With(loggableReq) defer s.logRequest(accLog, r, wrec, &duration, repl, bodyReader, shouldLogCredentials) } start := time.Now() // guarantee ACME HTTP challenges; handle them // separately from any user-defined handlers if s.tlsApp.HandleHTTPChallenge(w, r) { duration = time.Since(start) return } // execute the primary handler chain err := s.primaryHandlerChain.ServeHTTP(w, r) duration = time.Since(start) // if no errors, we're done! if err == nil { return } // restore original request before invoking error handler chain (issue #3717) // TODO: this does not restore original headers, if modified (for efficiency) origReq := r.Context().Value(OriginalRequestCtxKey).(http.Request) r.Method = origReq.Method r.RemoteAddr = origReq.RemoteAddr r.RequestURI = origReq.RequestURI cloneURL(origReq.URL, r.URL) // prepare the error log errLog = errLog.With(zap.Duration("duration", duration)) errLoggers := []*zap.Logger{errLog} if s.Logs != nil { errLoggers = s.Logs.wrapLogger(errLog, r) } // get the values that will be used to log the error errStatus, errMsg, errFields := errLogValues(err) // add HTTP error information to request context r = s.Errors.WithError(r, err) var fields []zapcore.Field if s.Errors != nil && len(s.Errors.Routes) > 0 { // execute user-defined error handling route if err2 := s.errorHandlerChain.ServeHTTP(w, r); err2 == nil { // user's error route handled the error response // successfully, so now just log the error for _, logger := range errLoggers { if c := logger.Check(zapcore.DebugLevel, errMsg); c != nil { if fields == nil { fields = errFields() } c.Write(fields...) } } } else { // well... this is awkward for _, logger := range errLoggers { if c := logger.Check(zapcore.ErrorLevel, "error handling handler error"); c != nil { if fields == nil { fields = errFields() fields = append([]zapcore.Field{ zap.String("error", err2.Error()), zap.Namespace("first_error"), zap.String("msg", errMsg), }, fields...) } c.Write(fields...) } } if handlerErr, ok := err.(HandlerError); ok { w.WriteHeader(handlerErr.StatusCode) } else { w.WriteHeader(http.StatusInternalServerError) } } } else { logLevel := zapcore.DebugLevel if errStatus >= 500 { logLevel = zapcore.ErrorLevel } for _, logger := range errLoggers { if c := logger.Check(logLevel, errMsg); c != nil { if fields == nil { fields = errFields() } c.Write(fields...) } } w.WriteHeader(errStatus) } } // wrapPrimaryRoute wraps stack (a compiled middleware handler chain) // in s.enforcementHandler which performs crucial security checks, etc. func (s *Server) wrapPrimaryRoute(stack Handler) Handler { return HandlerFunc(func(w http.ResponseWriter, r *http.Request) error { return s.enforcementHandler(w, r, stack) }) } // enforcementHandler is an implicit middleware which performs // standard checks before executing the HTTP middleware chain. func (s *Server) enforcementHandler(w http.ResponseWriter, r *http.Request, next Handler) error { // enforce strict host matching, which ensures that the SNI // value (if any), matches the Host header; essential for // servers that rely on TLS ClientAuth sharing a listener // with servers that do not; if not enforced, client could // bypass by sending benign SNI then restricted Host header if s.StrictSNIHost != nil && *s.StrictSNIHost && r.TLS != nil { hostname, _, err := net.SplitHostPort(r.Host) if err != nil { hostname = r.Host // OK; probably lacked port } if !strings.EqualFold(r.TLS.ServerName, hostname) { err := fmt.Errorf("strict host matching: TLS ServerName (%s) and HTTP Host (%s) values differ", r.TLS.ServerName, hostname) r.Close = true return Error(http.StatusMisdirectedRequest, err) } } return next.ServeHTTP(w, r) } // listenersUseAnyPortOtherThan returns true if there are any // listeners in s that use a port which is not otherPort. func (s *Server) listenersUseAnyPortOtherThan(otherPort int) bool { for _, lnAddr := range s.Listen { laddrs, err := caddy.ParseNetworkAddress(lnAddr) if err != nil { continue } if uint(otherPort) > laddrs.EndPort || uint(otherPort) < laddrs.StartPort { return true } } return false } // hasListenerAddress returns true if s has a listener // at the given address fullAddr. Currently, fullAddr // must represent exactly one socket address (port // ranges are not supported) func (s *Server) hasListenerAddress(fullAddr string) bool { laddrs, err := caddy.ParseNetworkAddress(fullAddr) if err != nil { return false } if laddrs.PortRangeSize() != 1 { return false // TODO: support port ranges } for _, lnAddr := range s.Listen { thisAddrs, err := caddy.ParseNetworkAddress(lnAddr) if err != nil { continue } if thisAddrs.Network != laddrs.Network { continue } // Apparently, Linux requires all bound ports to be distinct // *regardless of host interface* even if the addresses are // in fact different; binding "192.168.0.1:9000" and then // ":9000" will fail for ":9000" because "address is already // in use" even though it's not, and the same bindings work // fine on macOS. I also found on Linux that listening on // "[::]:9000" would fail with a similar error, except with // the address "0.0.0.0:9000", as if deliberately ignoring // that I specified the IPv6 interface explicitly. This seems // to be a major bug in the Linux network stack and I don't // know why it hasn't been fixed yet, so for now we have to // special-case ourselves around Linux like a doting parent. // The second issue seems very similar to a discussion here: // https://github.com/nodejs/node/issues/9390 // // This is very easy to reproduce by creating an HTTP server // that listens to both addresses or just one with a host // interface; or for a more confusing reproduction, try // listening on "127.0.0.1:80" and ":443" and you'll see // the error, if you take away the GOOS condition below. // // So, an address is equivalent if the port is in the port // range, and if not on Linux, the host is the same... sigh. if (runtime.GOOS == "linux" || thisAddrs.Host == laddrs.Host) && (laddrs.StartPort <= thisAddrs.EndPort) && (laddrs.StartPort >= thisAddrs.StartPort) { return true } } return false } func (s *Server) hasTLSClientAuth() bool { return slices.ContainsFunc(s.TLSConnPolicies, func(cp *caddytls.ConnectionPolicy) bool { return cp.ClientAuthentication != nil && cp.ClientAuthentication.Active() }) } // findLastRouteWithHostMatcher returns the index of the last route // in the server which has a host matcher. Used during Automatic HTTPS // to determine where to insert the HTTP->HTTPS redirect route, such // that it is after any other host matcher but before any "catch-all" // route without a host matcher. func (s *Server) findLastRouteWithHostMatcher() int { foundHostMatcher := false lastIndex := len(s.Routes) for i, route := range s.Routes { // since we want to break out of an inner loop, use a closure // to allow us to use 'return' when we found a host matcher found := (func() bool { for _, sets := range route.MatcherSets { for _, matcher := range sets { switch matcher.(type) { case *MatchHost: foundHostMatcher = true return true } } } return false })() // if we found the host matcher, change the lastIndex to // just after the current route if found { lastIndex = i + 1 } } // If we didn't actually find a host matcher, return 0 // because that means every defined route was a "catch-all". // See https://caddy.community/t/how-to-set-priority-in-caddyfile/13002/8 if !foundHostMatcher { return 0 } return lastIndex } // serveHTTP3 creates a QUIC listener, configures an HTTP/3 server if // not already done, and then uses that server to serve HTTP/3 over // the listener, with Server s as the handler. func (s *Server) serveHTTP3(addr caddy.NetworkAddress, tlsCfg *tls.Config) error { h3net, err := getHTTP3Network(addr.Network) if err != nil { return fmt.Errorf("starting HTTP/3 QUIC listener: %v", err) } addr.Network = h3net h3ln, err := addr.ListenQUIC(s.ctx, 0, net.ListenConfig{}, tlsCfg, s.packetConnWrappers) if err != nil { return fmt.Errorf("starting HTTP/3 QUIC listener: %v", err) } // create HTTP/3 server if not done already if s.h3server == nil { s.h3server = &http3.Server{ Handler: s, TLSConfig: tlsCfg, MaxHeaderBytes: s.MaxHeaderBytes, QUICConfig: &quic.Config{ Versions: []quic.Version{quic.Version1, quic.Version2}, Tracer: h3qlog.DefaultConnectionTracer, }, IdleTimeout: time.Duration(s.IdleTimeout), } } s.quicListeners = append(s.quicListeners, h3ln) //nolint:errcheck go s.h3server.ServeListener(h3ln) return nil } // configureServer applies/binds the registered callback functions to the server. func (s *Server) configureServer(server *http.Server) { for _, f := range s.connStateFuncs { if server.ConnState != nil { baseConnStateFunc := server.ConnState server.ConnState = func(conn net.Conn, state http.ConnState) { baseConnStateFunc(conn, state) f(conn, state) } } else { server.ConnState = f } } for _, f := range s.connContextFuncs { if server.ConnContext != nil { baseConnContextFunc := server.ConnContext server.ConnContext = func(ctx context.Context, c net.Conn) context.Context { return f(baseConnContextFunc(ctx, c), c) } } else { server.ConnContext = f } } for _, f := range s.onShutdownFuncs { server.RegisterOnShutdown(f) } } // RegisterConnState registers f to be invoked on s.ConnState. func (s *Server) RegisterConnState(f func(net.Conn, http.ConnState)) { s.connStateFuncs = append(s.connStateFuncs, f) } // RegisterConnContext registers f to be invoked as part of s.ConnContext. func (s *Server) RegisterConnContext(f func(ctx context.Context, c net.Conn) context.Context) { s.connContextFuncs = append(s.connContextFuncs, f) } // RegisterOnShutdown registers f to be invoked when the server begins to shut down. func (s *Server) RegisterOnShutdown(f func()) { s.onShutdownFuncs = append(s.onShutdownFuncs, f) } // RegisterOnStop registers f to be invoked after the server has shut down completely. // // EXPERIMENTAL: Subject to change or removal. func (s *Server) RegisterOnStop(f func(context.Context) error) { s.onStopFuncs = append(s.onStopFuncs, f) } // HTTPErrorConfig determines how to handle errors // from the HTTP handlers. type HTTPErrorConfig struct { // The routes to evaluate after the primary handler // chain returns an error. In an error route, extra // placeholders are available: // // Placeholder | Description // ------------|--------------- // `{http.error.status_code}` | The recommended HTTP status code // `{http.error.status_text}` | The status text associated with the recommended status code // `{http.error.message}` | The error message // `{http.error.trace}` | The origin of the error // `{http.error.id}` | An identifier for this occurrence of the error Routes RouteList `json:"routes,omitempty"` } // WithError makes a shallow copy of r to add the error to its // context, and sets placeholders on the request's replacer // related to err. It returns the modified request which has // the error information in its context and replacer. It // overwrites any existing error values that are stored. func (*HTTPErrorConfig) WithError(r *http.Request, err error) *http.Request { // add the raw error value to the request context // so it can be accessed by error handlers c := context.WithValue(r.Context(), ErrorCtxKey, err) r = r.WithContext(c) // add error values to the replacer repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) repl.Set("http.error", err) if handlerErr, ok := err.(HandlerError); ok { repl.Set("http.error.status_code", handlerErr.StatusCode) repl.Set("http.error.status_text", http.StatusText(handlerErr.StatusCode)) repl.Set("http.error.id", handlerErr.ID) repl.Set("http.error.trace", handlerErr.Trace) if handlerErr.Err != nil { repl.Set("http.error.message", handlerErr.Err.Error()) } else { repl.Set("http.error.message", http.StatusText(handlerErr.StatusCode)) } } return r } // shouldLogRequest returns true if this request should be logged. func (s *Server) shouldLogRequest(r *http.Request) bool { if s.accessLogger == nil || s.Logs == nil { // logging is disabled return false } // strip off the port if any, logger names are host only hostWithoutPort, _, err := net.SplitHostPort(r.Host) if err != nil { hostWithoutPort = r.Host } for loggerName := range s.Logs.LoggerNames { if certmagic.MatchWildcard(hostWithoutPort, loggerName) { // this host is mapped to a particular logger name return true } } for _, dh := range s.Logs.SkipHosts { // logging for this particular host is disabled if certmagic.MatchWildcard(hostWithoutPort, dh) { return false } } // if configured, this host is not mapped and thus must not be logged return !s.Logs.SkipUnmappedHosts } // logTrace will log that this middleware handler is being invoked. // It emits at DEBUG level. func (s *Server) logTrace(mh MiddlewareHandler) { if s.Logs == nil || !s.Logs.Trace { return } if c := s.traceLogger.Check(zapcore.DebugLevel, caddy.GetModuleName(mh)); c != nil { c.Write(zap.Any("module", mh)) } } // logRequest logs the request to access logs, unless skipped. func (s *Server) logRequest( accLog *zap.Logger, r *http.Request, wrec ResponseRecorder, duration *time.Duration, repl *caddy.Replacer, bodyReader *lengthReader, shouldLogCredentials bool, ) { ctx := r.Context() // this request may be flagged as omitted from the logs if skip, ok := GetVar(ctx, LogSkipVar).(bool); ok && skip { return } status := wrec.Status() size := wrec.Size() repl.Set("http.response.status", status) // will be 0 if no response is written by us (Go will write 200 to client) repl.Set("http.response.size", size) repl.Set("http.response.duration", duration) repl.Set("http.response.duration_ms", duration.Seconds()*1e3) // multiply seconds to preserve decimal (see #4666) loggers := []*zap.Logger{accLog} if s.Logs != nil { loggers = s.Logs.wrapLogger(accLog, r) } message := "handled request" if nop, ok := GetVar(ctx, "unhandled").(bool); ok && nop { message = "NOP" } logLevel := zapcore.InfoLevel if status >= 500 { logLevel = zapcore.ErrorLevel } var fields []zapcore.Field for _, logger := range loggers { c := logger.Check(logLevel, message) if c == nil { continue } if fields == nil { userID, _ := repl.GetString("http.auth.user.id") reqBodyLength := 0 if bodyReader != nil { reqBodyLength = bodyReader.Length } extra := ctx.Value(ExtraLogFieldsCtxKey).(*ExtraLogFields) fieldCount := 6 fields = make([]zapcore.Field, 0, fieldCount+len(extra.fields)) fields = append(fields, zap.Int("bytes_read", reqBodyLength), zap.String("user_id", userID), zap.Duration("duration", *duration), zap.Int("size", size), zap.Int("status", status), zap.Object("resp_headers", LoggableHTTPHeader{ Header: wrec.Header(), ShouldLogCredentials: shouldLogCredentials, }), ) fields = append(fields, extra.fields...) } c.Write(fields...) } } // protocol returns true if the protocol proto is configured/enabled. func (s *Server) protocol(proto string) bool { if s.ListenProtocols == nil { if slices.Contains(s.Protocols, proto) { return true } } else { for _, lnProtocols := range s.ListenProtocols { for _, lnProtocol := range lnProtocols { if lnProtocol == "" && slices.Contains(s.Protocols, proto) || lnProtocol == proto { return true } } } } return false } // Listeners returns the server's listeners. These are active listeners, // so calling Accept() or Close() on them will probably break things. // They are made available here for read-only purposes (e.g. Addr()) // and for type-asserting for purposes where you know what you're doing. // // EXPERIMENTAL: Subject to change or removal. func (s *Server) Listeners() []net.Listener { return s.listeners } // Name returns the server's name. func (s *Server) Name() string { return s.name } // PrepareRequest fills the request r for use in a Caddy HTTP handler chain. w and s can // be nil, but the handlers will lose response placeholders and access to the server. func PrepareRequest(r *http.Request, repl *caddy.Replacer, w http.ResponseWriter, s *Server) *http.Request { // set up the context for the request ctx := context.WithValue(r.Context(), caddy.ReplacerCtxKey, repl) ctx = context.WithValue(ctx, ServerCtxKey, s) trusted, clientIP := determineTrustedProxy(r, s) ctx = context.WithValue(ctx, VarsCtxKey, map[string]any{ TrustedProxyVarKey: trusted, ClientIPVarKey: clientIP, }) ctx = context.WithValue(ctx, routeGroupCtxKey, make(map[string]struct{})) var url2 url.URL // avoid letting this escape to the heap ctx = context.WithValue(ctx, OriginalRequestCtxKey, originalRequest(r, &url2)) ctx = context.WithValue(ctx, ExtraLogFieldsCtxKey, new(ExtraLogFields)) r = r.WithContext(ctx) // once the pointer to the request won't change // anymore, finish setting up the replacer addHTTPVarsToReplacer(repl, r, w) return r } // originalRequest returns a partial, shallow copy of // req, including: req.Method, deep copy of req.URL // (into the urlCopy parameter, which should be on the // stack), req.RequestURI, and req.RemoteAddr. Notably, // headers are not copied. This function is designed to // be very fast and efficient, and useful primarily for // read-only/logging purposes. func originalRequest(req *http.Request, urlCopy *url.URL) http.Request { cloneURL(req.URL, urlCopy)
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
true
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/responsewriter_test.go
modules/caddyhttp/responsewriter_test.go
package caddyhttp import ( "bytes" "io" "net/http" "strings" "testing" ) type responseWriterSpy interface { http.ResponseWriter Written() string CalledReadFrom() bool } var ( _ responseWriterSpy = (*baseRespWriter)(nil) _ responseWriterSpy = (*readFromRespWriter)(nil) ) // a barebones http.ResponseWriter mock type baseRespWriter []byte func (brw *baseRespWriter) Write(d []byte) (int, error) { *brw = append(*brw, d...) return len(d), nil } func (brw *baseRespWriter) Header() http.Header { return nil } func (brw *baseRespWriter) WriteHeader(statusCode int) {} func (brw *baseRespWriter) Written() string { return string(*brw) } func (brw *baseRespWriter) CalledReadFrom() bool { return false } // an http.ResponseWriter mock that supports ReadFrom type readFromRespWriter struct { baseRespWriter called bool } func (rf *readFromRespWriter) ReadFrom(r io.Reader) (int64, error) { rf.called = true return io.Copy(&rf.baseRespWriter, r) } func (rf *readFromRespWriter) CalledReadFrom() bool { return rf.called } func TestResponseWriterWrapperReadFrom(t *testing.T) { tests := map[string]struct { responseWriter responseWriterSpy wantReadFrom bool }{ "no ReadFrom": { responseWriter: &baseRespWriter{}, wantReadFrom: false, }, "has ReadFrom": { responseWriter: &readFromRespWriter{}, wantReadFrom: true, }, } for name, tt := range tests { t.Run(name, func(t *testing.T) { // what we expect middlewares to do: type myWrapper struct { *ResponseWriterWrapper } wrapped := myWrapper{ ResponseWriterWrapper: &ResponseWriterWrapper{ResponseWriter: tt.responseWriter}, } const srcData = "boo!" // hides everything but Read, since strings.Reader implements WriteTo it would // take precedence over our ReadFrom. src := struct{ io.Reader }{strings.NewReader(srcData)} if _, err := io.Copy(wrapped, src); err != nil { t.Errorf("%s: Copy() err = %v", name, err) } if got := tt.responseWriter.Written(); got != srcData { t.Errorf("%s: data = %q, want %q", name, got, srcData) } if tt.responseWriter.CalledReadFrom() != tt.wantReadFrom { if tt.wantReadFrom { t.Errorf("%s: ReadFrom() should have been called", name) } else { t.Errorf("%s: ReadFrom() should not have been called", name) } } }) } } func TestResponseWriterWrapperUnwrap(t *testing.T) { w := &ResponseWriterWrapper{&baseRespWriter{}} if _, ok := w.Unwrap().(*baseRespWriter); !ok { t.Errorf("Unwrap() doesn't return the underlying ResponseWriter") } } func TestResponseRecorderReadFrom(t *testing.T) { tests := map[string]struct { responseWriter responseWriterSpy shouldBuffer bool wantReadFrom bool }{ "buffered plain": { responseWriter: &baseRespWriter{}, shouldBuffer: true, wantReadFrom: false, }, "streamed plain": { responseWriter: &baseRespWriter{}, shouldBuffer: false, wantReadFrom: false, }, "buffered ReadFrom": { responseWriter: &readFromRespWriter{}, shouldBuffer: true, wantReadFrom: false, }, "streamed ReadFrom": { responseWriter: &readFromRespWriter{}, shouldBuffer: false, wantReadFrom: true, }, } for name, tt := range tests { t.Run(name, func(t *testing.T) { var buf bytes.Buffer rr := NewResponseRecorder(tt.responseWriter, &buf, func(status int, header http.Header) bool { return tt.shouldBuffer }) const srcData = "boo!" // hides everything but Read, since strings.Reader implements WriteTo it would // take precedence over our ReadFrom. src := struct{ io.Reader }{strings.NewReader(srcData)} if _, err := io.Copy(rr, src); err != nil { t.Errorf("Copy() err = %v", err) } wantStreamed := srcData wantBuffered := "" if tt.shouldBuffer { wantStreamed = "" wantBuffered = srcData } if got := tt.responseWriter.Written(); got != wantStreamed { t.Errorf("streamed data = %q, want %q", got, wantStreamed) } if got := buf.String(); got != wantBuffered { t.Errorf("buffered data = %q, want %q", got, wantBuffered) } if tt.responseWriter.CalledReadFrom() != tt.wantReadFrom { if tt.wantReadFrom { t.Errorf("ReadFrom() should have been called") } else { t.Errorf("ReadFrom() should not have been called") } } }) } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/vars.go
modules/caddyhttp/vars.go
// Copyright 2015 Matthew Holt and The Caddy 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 caddyhttp import ( "context" "fmt" "net/http" "reflect" "strings" "github.com/google/cel-go/cel" "github.com/google/cel-go/common/types/ref" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) var stringSliceType = reflect.TypeFor[[]string]() func init() { caddy.RegisterModule(VarsMiddleware{}) caddy.RegisterModule(VarsMatcher{}) caddy.RegisterModule(MatchVarsRE{}) } // VarsMiddleware is an HTTP middleware which sets variables to // have values that can be used in the HTTP request handler // chain. The primary way to access variables is with placeholders, // which have the form: `{http.vars.variable_name}`, or with // the `vars` and `vars_regexp` request matchers. // // The key is the variable name, and the value is the value of the // variable. Both the name and value may use or contain placeholders. type VarsMiddleware map[string]any // CaddyModule returns the Caddy module information. func (VarsMiddleware) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.handlers.vars", New: func() caddy.Module { return new(VarsMiddleware) }, } } func (m VarsMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request, next Handler) error { vars := r.Context().Value(VarsCtxKey).(map[string]any) repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) for k, v := range m { keyExpanded := repl.ReplaceAll(k, "") if valStr, ok := v.(string); ok { v = repl.ReplaceAll(valStr, "") } vars[keyExpanded] = v // Special case: the user ID is in the replacer, pulled from there // for access logs. Allow users to override it with the vars handler. if keyExpanded == "http.auth.user.id" { repl.Set(keyExpanded, v) } } return next.ServeHTTP(w, r) } // UnmarshalCaddyfile implements caddyfile.Unmarshaler. Syntax: // // vars [<name> <val>] { // <name> <val> // ... // } func (m *VarsMiddleware) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume directive name if *m == nil { *m = make(VarsMiddleware) } nextVar := func(headerLine bool) error { if headerLine { // header line is optional if !d.NextArg() { return nil } } varName := d.Val() if !d.NextArg() { return d.ArgErr() } varValue := d.ScalarVal() (*m)[varName] = varValue if d.NextArg() { return d.ArgErr() } return nil } if err := nextVar(true); err != nil { return err } for d.NextBlock(0) { if err := nextVar(false); err != nil { return err } } return nil } // VarsMatcher is an HTTP request matcher which can match // requests based on variables in the context or placeholder // values. The key is the placeholder or name of the variable, // and the values are possible values the variable can be in // order to match (logical OR'ed). // // If the key is surrounded by `{ }` it is assumed to be a // placeholder. Otherwise, it will be considered a variable // name. // // Placeholders in the keys are not expanded, but // placeholders in the values are. type VarsMatcher map[string][]string // CaddyModule returns the Caddy module information. func (VarsMatcher) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.matchers.vars", New: func() caddy.Module { return new(VarsMatcher) }, } } // UnmarshalCaddyfile implements caddyfile.Unmarshaler. func (m *VarsMatcher) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { if *m == nil { *m = make(map[string][]string) } // iterate to merge multiple matchers into one for d.Next() { var field string if !d.Args(&field) { return d.Errf("malformed vars matcher: expected field name") } vals := d.RemainingArgs() if len(vals) == 0 { return d.Errf("malformed vars matcher: expected at least one value to match against") } (*m)[field] = append((*m)[field], vals...) if d.NextBlock(0) { return d.Err("malformed vars matcher: blocks are not supported") } } return nil } // Match matches a request based on variables in the context, // or placeholders if the key is not a variable. func (m VarsMatcher) Match(r *http.Request) bool { match, _ := m.MatchWithError(r) return match } // MatchWithError returns true if r matches m. func (m VarsMatcher) MatchWithError(r *http.Request) (bool, error) { if len(m) == 0 { return true, nil } vars := r.Context().Value(VarsCtxKey).(map[string]any) repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) for key, vals := range m { var varValue any if strings.HasPrefix(key, "{") && strings.HasSuffix(key, "}") && strings.Count(key, "{") == 1 { varValue, _ = repl.Get(strings.Trim(key, "{}")) } else { varValue = vars[key] } // see if any of the values given in the matcher match the actual value for _, v := range vals { matcherValExpanded := repl.ReplaceAll(v, "") var varStr string switch vv := varValue.(type) { case string: varStr = vv case fmt.Stringer: varStr = vv.String() case error: varStr = vv.Error() case nil: varStr = "" default: varStr = fmt.Sprintf("%v", vv) } if varStr == matcherValExpanded { return true, nil } } } return false, nil } // CELLibrary produces options that expose this matcher for use in CEL // expression matchers. // // Example: // // expression vars({'{magic_number}': ['3', '5']}) // expression vars({'{foo}': 'single_value'}) func (VarsMatcher) CELLibrary(_ caddy.Context) (cel.Library, error) { return CELMatcherImpl( "vars", "vars_matcher_request_map", []*cel.Type{CELTypeJSON}, func(data ref.Val) (RequestMatcherWithError, error) { mapStrListStr, err := CELValueToMapStrList(data) if err != nil { return nil, err } return VarsMatcher(mapStrListStr), nil }, ) } // MatchVarsRE matches the value of the context variables by a given regular expression. // // Upon a match, it adds placeholders to the request: `{http.regexp.name.capture_group}` // where `name` is the regular expression's name, and `capture_group` is either // the named or positional capture group from the expression itself. If no name // is given, then the placeholder omits the name: `{http.regexp.capture_group}` // (potentially leading to collisions). type MatchVarsRE map[string]*MatchRegexp // CaddyModule returns the Caddy module information. func (MatchVarsRE) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.matchers.vars_regexp", New: func() caddy.Module { return new(MatchVarsRE) }, } } // UnmarshalCaddyfile implements caddyfile.Unmarshaler. func (m *MatchVarsRE) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { if *m == nil { *m = make(map[string]*MatchRegexp) } // iterate to merge multiple matchers into one for d.Next() { var first, second, third string if !d.Args(&first, &second) { return d.ArgErr() } var name, field, val string if d.Args(&third) { name = first field = second val = third } else { field = first val = second } // Default to the named matcher's name, if no regexp name is provided if name == "" { name = d.GetContextString(caddyfile.MatcherNameCtxKey) } (*m)[field] = &MatchRegexp{Pattern: val, Name: name} if d.NextBlock(0) { return d.Err("malformed vars_regexp matcher: blocks are not supported") } } return nil } // Provision compiles m's regular expressions. func (m MatchVarsRE) Provision(ctx caddy.Context) error { for _, rm := range m { err := rm.Provision(ctx) if err != nil { return err } } return nil } // Match returns true if r matches m. func (m MatchVarsRE) Match(r *http.Request) bool { match, _ := m.MatchWithError(r) return match } // MatchWithError returns true if r matches m. func (m MatchVarsRE) MatchWithError(r *http.Request) (bool, error) { vars := r.Context().Value(VarsCtxKey).(map[string]any) repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) for key, val := range m { var varValue any if strings.HasPrefix(key, "{") && strings.HasSuffix(key, "}") && strings.Count(key, "{") == 1 { varValue, _ = repl.Get(strings.Trim(key, "{}")) } else { varValue = vars[key] } var varStr string switch vv := varValue.(type) { case string: varStr = vv case fmt.Stringer: varStr = vv.String() case error: varStr = vv.Error() case nil: varStr = "" default: varStr = fmt.Sprintf("%v", vv) } valExpanded := repl.ReplaceAll(varStr, "") if match := val.Match(valExpanded, repl); match { return match, nil } } return false, nil } // CELLibrary produces options that expose this matcher for use in CEL // expression matchers. // // Example: // // expression vars_regexp('foo', '{magic_number}', '[0-9]+') // expression vars_regexp('{magic_number}', '[0-9]+') func (MatchVarsRE) CELLibrary(ctx caddy.Context) (cel.Library, error) { unnamedPattern, err := CELMatcherImpl( "vars_regexp", "vars_regexp_request_string_string", []*cel.Type{cel.StringType, cel.StringType}, func(data ref.Val) (RequestMatcherWithError, error) { refStringList := stringSliceType params, err := data.ConvertToNative(refStringList) if err != nil { return nil, err } strParams := params.([]string) matcher := MatchVarsRE{} matcher[strParams[0]] = &MatchRegexp{ Pattern: strParams[1], Name: ctx.Value(MatcherNameCtxKey).(string), } err = matcher.Provision(ctx) return matcher, err }, ) if err != nil { return nil, err } namedPattern, err := CELMatcherImpl( "vars_regexp", "vars_regexp_request_string_string_string", []*cel.Type{cel.StringType, cel.StringType, cel.StringType}, func(data ref.Val) (RequestMatcherWithError, error) { refStringList := stringSliceType params, err := data.ConvertToNative(refStringList) if err != nil { return nil, err } strParams := params.([]string) name := strParams[0] if name == "" { name = ctx.Value(MatcherNameCtxKey).(string) } matcher := MatchVarsRE{} matcher[strParams[1]] = &MatchRegexp{ Pattern: strParams[2], Name: name, } err = matcher.Provision(ctx) return matcher, err }, ) if err != nil { return nil, err } envOpts := append(unnamedPattern.CompileOptions(), namedPattern.CompileOptions()...) prgOpts := append(unnamedPattern.ProgramOptions(), namedPattern.ProgramOptions()...) return NewMatcherCELLibrary(envOpts, prgOpts), nil } // Validate validates m's regular expressions. func (m MatchVarsRE) Validate() error { for _, rm := range m { err := rm.Validate() if err != nil { return err } } return nil } // GetVar gets a value out of the context's variable table by key. // If the key does not exist, the return value will be nil. func GetVar(ctx context.Context, key string) any { varMap, ok := ctx.Value(VarsCtxKey).(map[string]any) if !ok { return nil } return varMap[key] } // SetVar sets a value in the context's variable table with // the given key. It overwrites any previous value with the // same key. // // If the value is nil (note: non-nil interface with nil // underlying value does not count) and the key exists in // the table, the key+value will be deleted from the table. func SetVar(ctx context.Context, key string, value any) { varMap, ok := ctx.Value(VarsCtxKey).(map[string]any) if !ok { return } if value == nil { if _, ok := varMap[key]; ok { delete(varMap, key) return } } varMap[key] = value } // Interface guards var ( _ MiddlewareHandler = (*VarsMiddleware)(nil) _ caddyfile.Unmarshaler = (*VarsMiddleware)(nil) _ RequestMatcherWithError = (*VarsMatcher)(nil) _ caddyfile.Unmarshaler = (*VarsMatcher)(nil) _ RequestMatcherWithError = (*MatchVarsRE)(nil) _ caddyfile.Unmarshaler = (*MatchVarsRE)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/celmatcher.go
modules/caddyhttp/celmatcher.go
// Copyright 2015 Matthew Holt and The Caddy 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 caddyhttp import ( "crypto/x509/pkix" "encoding/json" "errors" "fmt" "net/http" "reflect" "regexp" "strings" "time" "github.com/google/cel-go/cel" "github.com/google/cel-go/common" "github.com/google/cel-go/common/ast" "github.com/google/cel-go/common/operators" "github.com/google/cel-go/common/types" "github.com/google/cel-go/common/types/ref" "github.com/google/cel-go/common/types/traits" "github.com/google/cel-go/ext" "github.com/google/cel-go/interpreter" "github.com/google/cel-go/interpreter/functions" "github.com/google/cel-go/parser" "go.uber.org/zap" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func init() { caddy.RegisterModule(MatchExpression{}) } // MatchExpression matches requests by evaluating a // [CEL](https://github.com/google/cel-spec) expression. // This enables complex logic to be expressed using a comfortable, // familiar syntax. Please refer to // [the standard definitions of CEL functions and operators](https://github.com/google/cel-spec/blob/master/doc/langdef.md#standard-definitions). // // This matcher's JSON interface is actually a string, not a struct. // The generated docs are not correct because this type has custom // marshaling logic. // // COMPATIBILITY NOTE: This module is still experimental and is not // subject to Caddy's compatibility guarantee. type MatchExpression struct { // The CEL expression to evaluate. Any Caddy placeholders // will be expanded and situated into proper CEL function // calls before evaluating. Expr string `json:"expr,omitempty"` // Name is an optional name for this matcher. // This is used to populate the name for regexp // matchers that appear in the expression. Name string `json:"name,omitempty"` expandedExpr string prg cel.Program ta types.Adapter log *zap.Logger } // CaddyModule returns the Caddy module information. func (MatchExpression) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.matchers.expression", New: func() caddy.Module { return new(MatchExpression) }, } } // MarshalJSON marshals m's expression. func (m MatchExpression) MarshalJSON() ([]byte, error) { // if the name is empty, then we can marshal just the expression string if m.Name == "" { return json.Marshal(m.Expr) } // otherwise, we need to marshal the full object, using an // anonymous struct to avoid infinite recursion return json.Marshal(struct { Expr string `json:"expr"` Name string `json:"name"` }{ Expr: m.Expr, Name: m.Name, }) } // UnmarshalJSON unmarshals m's expression. func (m *MatchExpression) UnmarshalJSON(data []byte) error { // if the data is a string, then it's just the expression if data[0] == '"' { return json.Unmarshal(data, &m.Expr) } // otherwise, it's a full object, so unmarshal it, // using an temp map to avoid infinite recursion var tmpJson map[string]any err := json.Unmarshal(data, &tmpJson) *m = MatchExpression{ Expr: tmpJson["expr"].(string), Name: tmpJson["name"].(string), } return err } // Provision sets ups m. func (m *MatchExpression) Provision(ctx caddy.Context) error { m.log = ctx.Logger() // replace placeholders with a function call - this is just some // light (and possibly naïve) syntactic sugar m.expandedExpr = placeholderRegexp.ReplaceAllString(m.Expr, placeholderExpansion) // as a second pass, we'll strip the escape character from an escaped // placeholder, so that it can be used as an input to other CEL functions m.expandedExpr = escapedPlaceholderRegexp.ReplaceAllString(m.expandedExpr, escapedPlaceholderExpansion) // our type adapter expands CEL's standard type support m.ta = celTypeAdapter{} // initialize the CEL libraries from the Matcher implementations which // have been configured to support CEL. matcherLibProducers := []CELLibraryProducer{} for _, info := range caddy.GetModules("http.matchers") { p, ok := info.New().(CELLibraryProducer) if ok { matcherLibProducers = append(matcherLibProducers, p) } } // add the matcher name to the context so that the matcher name // can be used by regexp matchers being provisioned ctx = ctx.WithValue(MatcherNameCtxKey, m.Name) // Assemble the compilation and program options from the different library // producers into a single cel.Library implementation. matcherEnvOpts := []cel.EnvOption{} matcherProgramOpts := []cel.ProgramOption{} for _, producer := range matcherLibProducers { l, err := producer.CELLibrary(ctx) if err != nil { return fmt.Errorf("error initializing CEL library for %T: %v", producer, err) } matcherEnvOpts = append(matcherEnvOpts, l.CompileOptions()...) matcherProgramOpts = append(matcherProgramOpts, l.ProgramOptions()...) } matcherLib := cel.Lib(NewMatcherCELLibrary(matcherEnvOpts, matcherProgramOpts)) // create the CEL environment env, err := cel.NewEnv( cel.Function(CELPlaceholderFuncName, cel.SingletonBinaryBinding(m.caddyPlaceholderFunc), cel.Overload( CELPlaceholderFuncName+"_httpRequest_string", []*cel.Type{httpRequestObjectType, cel.StringType}, cel.AnyType, )), cel.Variable(CELRequestVarName, httpRequestObjectType), cel.CustomTypeAdapter(m.ta), ext.Strings(), ext.Bindings(), ext.Lists(), ext.Math(), matcherLib, ) if err != nil { return fmt.Errorf("setting up CEL environment: %v", err) } // parse and type-check the expression checked, issues := env.Compile(m.expandedExpr) if issues.Err() != nil { return fmt.Errorf("compiling CEL program: %s", issues.Err()) } // request matching is a boolean operation, so we don't really know // what to do if the expression returns a non-boolean type if checked.OutputType() != cel.BoolType { return fmt.Errorf("CEL request matcher expects return type of bool, not %s", checked.OutputType()) } // compile the "program" m.prg, err = env.Program(checked, cel.EvalOptions(cel.OptOptimize)) if err != nil { return fmt.Errorf("compiling CEL program: %s", err) } return nil } // Match returns true if r matches m. func (m MatchExpression) Match(r *http.Request) bool { match, err := m.MatchWithError(r) if err != nil { SetVar(r.Context(), MatcherErrorVarKey, err) } return match } // MatchWithError returns true if r matches m. func (m MatchExpression) MatchWithError(r *http.Request) (bool, error) { celReq := celHTTPRequest{r} out, _, err := m.prg.Eval(celReq) if err != nil { m.log.Error("evaluating expression", zap.Error(err)) return false, err } if outBool, ok := out.Value().(bool); ok { return outBool, nil } return false, nil } // UnmarshalCaddyfile implements caddyfile.Unmarshaler. func (m *MatchExpression) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume matcher name // if there's multiple args, then we need to keep the raw // tokens because the user may have used quotes within their // CEL expression (e.g. strings) and we should retain that if d.CountRemainingArgs() > 1 { m.Expr = strings.Join(d.RemainingArgsRaw(), " ") return nil } // there should at least be one arg if !d.NextArg() { return d.ArgErr() } // if there's only one token, then we can safely grab the // cleaned token (no quotes) and use that as the expression // because there's no valid CEL expression that is only a // quoted string; commonly quotes are used in Caddyfile to // define the expression m.Expr = d.Val() // use the named matcher's name, to fill regexp // matchers names by default m.Name = d.GetContextString(caddyfile.MatcherNameCtxKey) return nil } // caddyPlaceholderFunc implements the custom CEL function that accesses the // Replacer on a request and gets values from it. func (m MatchExpression) caddyPlaceholderFunc(lhs, rhs ref.Val) ref.Val { celReq, ok := lhs.(celHTTPRequest) if !ok { return types.NewErr( "invalid request of type '%v' to %s(request, placeholderVarName)", lhs.Type(), CELPlaceholderFuncName, ) } phStr, ok := rhs.(types.String) if !ok { return types.NewErr( "invalid placeholder variable name of type '%v' to %s(request, placeholderVarName)", rhs.Type(), CELPlaceholderFuncName, ) } repl := celReq.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) val, _ := repl.Get(string(phStr)) return m.ta.NativeToValue(val) } // httpRequestCELType is the type representation of a native HTTP request. var httpRequestCELType = cel.ObjectType("http.Request", traits.ReceiverType) // celHTTPRequest wraps an http.Request with ref.Val interface methods. // // This type also implements the interpreter.Activation interface which // drops allocation costs for CEL expression evaluations by roughly half. type celHTTPRequest struct{ *http.Request } func (cr celHTTPRequest) ResolveName(name string) (any, bool) { if name == CELRequestVarName { return cr, true } return nil, false } func (cr celHTTPRequest) Parent() interpreter.Activation { return nil } func (cr celHTTPRequest) ConvertToNative(typeDesc reflect.Type) (any, error) { return cr.Request, nil } func (celHTTPRequest) ConvertToType(typeVal ref.Type) ref.Val { panic("not implemented") } func (cr celHTTPRequest) Equal(other ref.Val) ref.Val { if o, ok := other.Value().(celHTTPRequest); ok { return types.Bool(o.Request == cr.Request) } return types.ValOrErr(other, "%v is not comparable type", other) } func (celHTTPRequest) Type() ref.Type { return httpRequestCELType } func (cr celHTTPRequest) Value() any { return cr } var pkixNameCELType = cel.ObjectType("pkix.Name", traits.ReceiverType) // celPkixName wraps an pkix.Name with // methods to satisfy the ref.Val interface. type celPkixName struct{ *pkix.Name } func (pn celPkixName) ConvertToNative(typeDesc reflect.Type) (any, error) { return pn.Name, nil } func (pn celPkixName) ConvertToType(typeVal ref.Type) ref.Val { if typeVal.TypeName() == "string" { return types.String(pn.Name.String()) } panic("not implemented") } func (pn celPkixName) Equal(other ref.Val) ref.Val { if o, ok := other.Value().(string); ok { return types.Bool(pn.Name.String() == o) } return types.ValOrErr(other, "%v is not comparable type", other) } func (celPkixName) Type() ref.Type { return pkixNameCELType } func (pn celPkixName) Value() any { return pn } // celTypeAdapter can adapt our custom types to a CEL value. type celTypeAdapter struct{} func (celTypeAdapter) NativeToValue(value any) ref.Val { switch v := value.(type) { case celHTTPRequest: return v case pkix.Name: return celPkixName{&v} case time.Time: return types.Timestamp{Time: v} case error: return types.WrapErr(v) } return types.DefaultTypeAdapter.NativeToValue(value) } // CELLibraryProducer provide CEL libraries that expose a Matcher // implementation as a first class function within the CEL expression // matcher. type CELLibraryProducer interface { // CELLibrary creates a cel.Library which makes it possible to use the // target object within CEL expression matchers. CELLibrary(caddy.Context) (cel.Library, error) } // CELMatcherImpl creates a new cel.Library based on the following pieces of // data: // // - macroName: the function name to be used within CEL. This will be a macro // and not a function proper. // - funcName: the function overload name generated by the CEL macro used to // represent the matcher. // - matcherDataTypes: the argument types to the macro. // - fac: a matcherFactory implementation which converts from CEL constant // values to a Matcher instance. // // Note, macro names and function names must not collide with other macros or // functions exposed within CEL expressions, or an error will be produced // during the expression matcher plan time. // // The existing CELMatcherImpl support methods are configured to support a // limited set of function signatures. For strong type validation you may need // to provide a custom macro which does a more detailed analysis of the CEL // literal provided to the macro as an argument. func CELMatcherImpl(macroName, funcName string, matcherDataTypes []*cel.Type, fac any) (cel.Library, error) { requestType := cel.ObjectType("http.Request") var macro parser.Macro switch len(matcherDataTypes) { case 1: matcherDataType := matcherDataTypes[0] switch matcherDataType.String() { case "list(string)": macro = parser.NewGlobalVarArgMacro(macroName, celMatcherStringListMacroExpander(funcName)) case cel.StringType.String(): macro = parser.NewGlobalMacro(macroName, 1, celMatcherStringMacroExpander(funcName)) case CELTypeJSON.String(): macro = parser.NewGlobalMacro(macroName, 1, celMatcherJSONMacroExpander(funcName)) default: return nil, fmt.Errorf("unsupported matcher data type: %s", matcherDataType) } case 2: if matcherDataTypes[0] == cel.StringType && matcherDataTypes[1] == cel.StringType { macro = parser.NewGlobalMacro(macroName, 2, celMatcherStringListMacroExpander(funcName)) matcherDataTypes = []*cel.Type{cel.ListType(cel.StringType)} } else { return nil, fmt.Errorf("unsupported matcher data type: %s, %s", matcherDataTypes[0], matcherDataTypes[1]) } case 3: if matcherDataTypes[0] == cel.StringType && matcherDataTypes[1] == cel.StringType && matcherDataTypes[2] == cel.StringType { macro = parser.NewGlobalMacro(macroName, 3, celMatcherStringListMacroExpander(funcName)) matcherDataTypes = []*cel.Type{cel.ListType(cel.StringType)} } else { return nil, fmt.Errorf("unsupported matcher data type: %s, %s, %s", matcherDataTypes[0], matcherDataTypes[1], matcherDataTypes[2]) } } envOptions := []cel.EnvOption{ cel.Macros(macro), cel.Function(funcName, cel.Overload(funcName, append([]*cel.Type{requestType}, matcherDataTypes...), cel.BoolType), cel.SingletonBinaryBinding(CELMatcherRuntimeFunction(funcName, fac))), } programOptions := []cel.ProgramOption{ cel.CustomDecorator(CELMatcherDecorator(funcName, fac)), } return NewMatcherCELLibrary(envOptions, programOptions), nil } // CELMatcherFactory converts a constant CEL value into a RequestMatcher. // Deprecated: Use CELMatcherWithErrorFactory instead. type CELMatcherFactory = func(data ref.Val) (RequestMatcher, error) // CELMatcherWithErrorFactory converts a constant CEL value into a RequestMatcherWithError. type CELMatcherWithErrorFactory = func(data ref.Val) (RequestMatcherWithError, error) // matcherCELLibrary is a simplistic configurable cel.Library implementation. type matcherCELLibrary struct { envOptions []cel.EnvOption programOptions []cel.ProgramOption } // NewMatcherCELLibrary creates a matcherLibrary from option setes. func NewMatcherCELLibrary(envOptions []cel.EnvOption, programOptions []cel.ProgramOption) cel.Library { return &matcherCELLibrary{ envOptions: envOptions, programOptions: programOptions, } } func (lib *matcherCELLibrary) CompileOptions() []cel.EnvOption { return lib.envOptions } func (lib *matcherCELLibrary) ProgramOptions() []cel.ProgramOption { return lib.programOptions } // CELMatcherDecorator matches a call overload generated by a CEL macro // that takes a single argument, and optimizes the implementation to precompile // the matcher and return a function that references the precompiled and // provisioned matcher. func CELMatcherDecorator(funcName string, fac any) interpreter.InterpretableDecorator { return func(i interpreter.Interpretable) (interpreter.Interpretable, error) { call, ok := i.(interpreter.InterpretableCall) if !ok { return i, nil } if call.OverloadID() != funcName { return i, nil } callArgs := call.Args() reqAttr, ok := callArgs[0].(interpreter.InterpretableAttribute) if !ok { return nil, errors.New("missing 'req' argument") } nsAttr, ok := reqAttr.Attr().(interpreter.NamespacedAttribute) if !ok { return nil, errors.New("missing 'req' argument") } varNames := nsAttr.CandidateVariableNames() if len(varNames) != 1 || len(varNames) == 1 && varNames[0] != CELRequestVarName { return nil, errors.New("missing 'req' argument") } matcherData, ok := callArgs[1].(interpreter.InterpretableConst) if !ok { // If the matcher arguments are not constant, then this means // they contain a Caddy placeholder reference and the evaluation // and matcher provisioning should be handled at dynamically. return i, nil } if factory, ok := fac.(CELMatcherWithErrorFactory); ok { matcher, err := factory(matcherData.Value()) if err != nil { return nil, err } return interpreter.NewCall( i.ID(), funcName, funcName+"_opt", []interpreter.Interpretable{reqAttr}, func(args ...ref.Val) ref.Val { // The request value, guaranteed to be of type celHTTPRequest celReq := args[0] // If needed this call could be changed to convert the value // to a *http.Request using CEL's ConvertToNative method. httpReq := celReq.Value().(celHTTPRequest) match, err := matcher.MatchWithError(httpReq.Request) if err != nil { return types.WrapErr(err) } return types.Bool(match) }, ), nil } if factory, ok := fac.(CELMatcherFactory); ok { matcher, err := factory(matcherData.Value()) if err != nil { return nil, err } return interpreter.NewCall( i.ID(), funcName, funcName+"_opt", []interpreter.Interpretable{reqAttr}, func(args ...ref.Val) ref.Val { // The request value, guaranteed to be of type celHTTPRequest celReq := args[0] // If needed this call could be changed to convert the value // to a *http.Request using CEL's ConvertToNative method. httpReq := celReq.Value().(celHTTPRequest) if m, ok := matcher.(RequestMatcherWithError); ok { match, err := m.MatchWithError(httpReq.Request) if err != nil { return types.WrapErr(err) } return types.Bool(match) } return types.Bool(matcher.Match(httpReq.Request)) }, ), nil } return nil, fmt.Errorf("invalid matcher factory, must be CELMatcherFactory or CELMatcherWithErrorFactory: %T", fac) } } // CELMatcherRuntimeFunction creates a function binding for when the input to the matcher // is dynamically resolved rather than a set of static constant values. func CELMatcherRuntimeFunction(funcName string, fac any) functions.BinaryOp { return func(celReq, matcherData ref.Val) ref.Val { if factory, ok := fac.(CELMatcherWithErrorFactory); ok { matcher, err := factory(matcherData) if err != nil { return types.WrapErr(err) } httpReq := celReq.Value().(celHTTPRequest) match, err := matcher.MatchWithError(httpReq.Request) if err != nil { return types.WrapErr(err) } return types.Bool(match) } if factory, ok := fac.(CELMatcherFactory); ok { matcher, err := factory(matcherData) if err != nil { return types.WrapErr(err) } httpReq := celReq.Value().(celHTTPRequest) if m, ok := matcher.(RequestMatcherWithError); ok { match, err := m.MatchWithError(httpReq.Request) if err != nil { return types.WrapErr(err) } return types.Bool(match) } return types.Bool(matcher.Match(httpReq.Request)) } return types.NewErr("CELMatcherRuntimeFunction invalid matcher factory: %T", fac) } } // celMatcherStringListMacroExpander validates that the macro is called // with a variable number of string arguments (at least one). // // The arguments are collected into a single list argument the following // function call returned: <funcName>(request, [args]) func celMatcherStringListMacroExpander(funcName string) cel.MacroFactory { return func(eh cel.MacroExprFactory, target ast.Expr, args []ast.Expr) (ast.Expr, *common.Error) { matchArgs := []ast.Expr{} if len(args) == 0 { return nil, eh.NewError(0, "matcher requires at least one argument") } for _, arg := range args { if isCELStringExpr(arg) { matchArgs = append(matchArgs, arg) } else { return nil, eh.NewError(arg.ID(), "matcher arguments must be string constants") } } return eh.NewCall(funcName, eh.NewIdent(CELRequestVarName), eh.NewList(matchArgs...)), nil } } // celMatcherStringMacroExpander validates that the macro is called a single // string argument. // // The following function call is returned: <funcName>(request, arg) func celMatcherStringMacroExpander(funcName string) parser.MacroExpander { return func(eh cel.MacroExprFactory, target ast.Expr, args []ast.Expr) (ast.Expr, *common.Error) { if len(args) != 1 { return nil, eh.NewError(0, "matcher requires one argument") } if isCELStringExpr(args[0]) { return eh.NewCall(funcName, eh.NewIdent(CELRequestVarName), args[0]), nil } return nil, eh.NewError(args[0].ID(), "matcher argument must be a string literal") } } // celMatcherJSONMacroExpander validates that the macro is called a single // map literal argument. // // The following function call is returned: <funcName>(request, arg) func celMatcherJSONMacroExpander(funcName string) parser.MacroExpander { return func(eh cel.MacroExprFactory, target ast.Expr, args []ast.Expr) (ast.Expr, *common.Error) { if len(args) != 1 { return nil, eh.NewError(0, "matcher requires a map literal argument") } arg := args[0] switch arg.Kind() { case ast.StructKind: return nil, eh.NewError(arg.ID(), fmt.Sprintf("matcher input must be a map literal, not a %s", arg.AsStruct().TypeName())) case ast.MapKind: mapExpr := arg.AsMap() for _, entry := range mapExpr.Entries() { isStringPlaceholder := isCELStringExpr(entry.AsMapEntry().Key()) if !isStringPlaceholder { return nil, eh.NewError(entry.ID(), "matcher map keys must be string literals") } isStringListPlaceholder := isCELStringExpr(entry.AsMapEntry().Value()) || isCELStringListLiteral(entry.AsMapEntry().Value()) if !isStringListPlaceholder { return nil, eh.NewError(entry.AsMapEntry().Value().ID(), "matcher map values must be string or list literals") } } return eh.NewCall(funcName, eh.NewIdent(CELRequestVarName), arg), nil case ast.UnspecifiedExprKind, ast.CallKind, ast.ComprehensionKind, ast.IdentKind, ast.ListKind, ast.LiteralKind, ast.SelectKind: // appeasing the linter :) } return nil, eh.NewError(arg.ID(), "matcher requires a map literal argument") } } // CELValueToMapStrList converts a CEL value to a map[string][]string // // Earlier validation stages should guarantee that the value has this type // at compile time, and that the runtime value type is map[string]any. // The reason for the slight difference in value type is that CEL allows for // map literals containing heterogeneous values, in this case string and list // of string. func CELValueToMapStrList(data ref.Val) (map[string][]string, error) { mapStrType := reflect.TypeFor[map[string]any]() mapStrRaw, err := data.ConvertToNative(mapStrType) if err != nil { return nil, err } mapStrIface := mapStrRaw.(map[string]any) mapStrListStr := make(map[string][]string, len(mapStrIface)) for k, v := range mapStrIface { switch val := v.(type) { case string: mapStrListStr[k] = []string{val} case types.String: mapStrListStr[k] = []string{string(val)} case []string: mapStrListStr[k] = val case []ref.Val: convVals := make([]string, len(val)) for i, elem := range val { strVal, ok := elem.(types.String) if !ok { return nil, fmt.Errorf("unsupported value type in header match: %T", val) } convVals[i] = string(strVal) } mapStrListStr[k] = convVals default: return nil, fmt.Errorf("unsupported value type in header match: %T", val) } } return mapStrListStr, nil } // isCELStringExpr indicates whether the expression is a supported string expression func isCELStringExpr(e ast.Expr) bool { return isCELStringLiteral(e) || isCELCaddyPlaceholderCall(e) || isCELConcatCall(e) } // isCELStringLiteral returns whether the expression is a CEL string literal. func isCELStringLiteral(e ast.Expr) bool { switch e.Kind() { case ast.LiteralKind: constant := e.AsLiteral() switch constant.Type() { case types.StringType: return true } case ast.UnspecifiedExprKind, ast.CallKind, ast.ComprehensionKind, ast.IdentKind, ast.ListKind, ast.MapKind, ast.SelectKind, ast.StructKind: // appeasing the linter :) } return false } // isCELCaddyPlaceholderCall returns whether the expression is a caddy placeholder call. func isCELCaddyPlaceholderCall(e ast.Expr) bool { switch e.Kind() { case ast.CallKind: call := e.AsCall() if call.FunctionName() == CELPlaceholderFuncName { return true } case ast.UnspecifiedExprKind, ast.ComprehensionKind, ast.IdentKind, ast.ListKind, ast.LiteralKind, ast.MapKind, ast.SelectKind, ast.StructKind: // appeasing the linter :) } return false } // isCELConcatCall tests whether the expression is a concat function (+) with string, placeholder, or // other concat call arguments. func isCELConcatCall(e ast.Expr) bool { switch e.Kind() { case ast.CallKind: call := e.AsCall() if call.Target().Kind() != ast.UnspecifiedExprKind { return false } if call.FunctionName() != operators.Add { return false } for _, arg := range call.Args() { if !isCELStringExpr(arg) { return false } } return true case ast.UnspecifiedExprKind, ast.ComprehensionKind, ast.IdentKind, ast.ListKind, ast.LiteralKind, ast.MapKind, ast.SelectKind, ast.StructKind: // appeasing the linter :) } return false } // isCELStringListLiteral returns whether the expression resolves to a list literal // containing only string constants or a placeholder call. func isCELStringListLiteral(e ast.Expr) bool { switch e.Kind() { case ast.ListKind: list := e.AsList() for _, elem := range list.Elements() { if !isCELStringExpr(elem) { return false } } return true case ast.UnspecifiedExprKind, ast.CallKind, ast.ComprehensionKind, ast.IdentKind, ast.LiteralKind, ast.MapKind, ast.SelectKind, ast.StructKind: // appeasing the linter :) } return false } // Variables used for replacing Caddy placeholders in CEL // expressions with a proper CEL function call; this is // just for syntactic sugar. var ( // The placeholder may not be preceded by a backslash; the expansion // will include the preceding character if it is not a backslash. placeholderRegexp = regexp.MustCompile(`([^\\]|^){([a-zA-Z][\w.-]+)}`) placeholderExpansion = `${1}ph(req, "${2}")` // As a second pass, we need to strip the escape character in front of // the placeholder, if it exists. escapedPlaceholderRegexp = regexp.MustCompile(`\\{([a-zA-Z][\w.-]+)}`) escapedPlaceholderExpansion = `{${1}}` CELTypeJSON = cel.MapType(cel.StringType, cel.DynType) ) var httpRequestObjectType = cel.ObjectType("http.Request") // The name of the CEL function which accesses Replacer values. const CELPlaceholderFuncName = "ph" // The name of the CEL request variable. const CELRequestVarName = "req" const MatcherNameCtxKey = "matcher_name" // Interface guards var ( _ caddy.Provisioner = (*MatchExpression)(nil) _ RequestMatcherWithError = (*MatchExpression)(nil) _ caddyfile.Unmarshaler = (*MatchExpression)(nil) _ json.Marshaler = (*MatchExpression)(nil) _ json.Unmarshaler = (*MatchExpression)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/http2listener.go
modules/caddyhttp/http2listener.go
package caddyhttp import ( "crypto/tls" "io" "net" "go.uber.org/zap" "golang.org/x/net/http2" ) type connectionStater interface { ConnectionState() tls.ConnectionState } // http2Listener wraps the listener to solve the following problems: // 1. prevent genuine h2c connections from succeeding if h2c is not enabled // and the connection doesn't implment connectionStater or the resulting NegotiatedProtocol // isn't http2. // This does allow a connection to pass as tls enabled even if it's not, listener wrappers // can do this. // 2. After wrapping the connection doesn't implement connectionStater, emit a warning so that listener // wrapper authors will hopefully implement it. // 3. check if the connection matches a specific http version. h2/h2c has a distinct preface. type http2Listener struct { useTLS bool useH1 bool useH2 bool net.Listener logger *zap.Logger } func (h *http2Listener) Accept() (net.Conn, error) { conn, err := h.Listener.Accept() if err != nil { return nil, err } // *tls.Conn doesn't need to be wrapped because we already removed unwanted alpns // and handshake won't succeed without mutually supported alpns if tlsConn, ok := conn.(*tls.Conn); ok { return tlsConn, nil } _, isConnectionStater := conn.(connectionStater) // emit a warning if h.useTLS && !isConnectionStater { h.logger.Warn("tls is enabled, but listener wrapper returns a connection that doesn't implement connectionStater") } else if !h.useTLS && isConnectionStater { h.logger.Warn("tls is disabled, but listener wrapper returns a connection that implements connectionStater") } // if both h1 and h2 are enabled, we don't need to check the preface if h.useH1 && h.useH2 { if isConnectionStater { return tlsStateConn{conn}, nil } return conn, nil } // impossible both are false, either useH1 or useH2 must be true, // or else the listener wouldn't be created h2Conn := &http2Conn{ h2Expected: h.useH2, logger: h.logger, Conn: conn, } if isConnectionStater { return tlsStateConn{http2StateConn{h2Conn}}, nil } return h2Conn, nil } // tlsStateConn wraps a net.Conn that implements connectionStater to hide that method // we can call netConn to get the original net.Conn and get the tls connection state // golang 1.25 will call that method, and it breaks h2 with connections other than *tls.Conn type tlsStateConn struct { net.Conn } func (conn tlsStateConn) tlsNetConn() net.Conn { return conn.Conn } type http2StateConn struct { *http2Conn } func (conn http2StateConn) ConnectionState() tls.ConnectionState { return conn.Conn.(connectionStater).ConnectionState() } type http2Conn struct { // current index where the preface should match, // no matching is done if idx is >= len(http2.ClientPreface) idx int // whether the connection is expected to be h2/h2c h2Expected bool // log if one such connection is detected logger *zap.Logger net.Conn } func (c *http2Conn) Read(p []byte) (int, error) { if c.idx >= len(http2.ClientPreface) { return c.Conn.Read(p) } n, err := c.Conn.Read(p) for i := range n { // first mismatch if p[i] != http2.ClientPreface[c.idx] { // close the connection if h2 is expected if c.h2Expected { c.logger.Debug("h1 connection detected, but h1 is not enabled") _ = c.Conn.Close() return 0, io.EOF } // no need to continue matching anymore c.idx = len(http2.ClientPreface) return n, err } c.idx++ // matching complete if c.idx == len(http2.ClientPreface) && !c.h2Expected { c.logger.Debug("h2/h2c connection detected, but h2/h2c is not enabled") _ = c.Conn.Close() return 0, io.EOF } } return n, err }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/replacer_test.go
modules/caddyhttp/replacer_test.go
// Copyright 2015 Matthew Holt and The Caddy 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 caddyhttp import ( "context" "crypto/tls" "crypto/x509" "encoding/pem" "net" "net/http" "net/http/httptest" "testing" "github.com/caddyserver/caddy/v2" ) func TestHTTPVarReplacement(t *testing.T) { req, _ := http.NewRequest(http.MethodGet, "/foo/bar.tar.gz?a=1&b=2", nil) repl := caddy.NewReplacer() localAddr, _ := net.ResolveTCPAddr("tcp", "192.168.159.1:80") ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl) ctx = context.WithValue(ctx, http.LocalAddrContextKey, localAddr) req = req.WithContext(ctx) req.Host = "example.com:80" req.RemoteAddr = "192.168.159.32:1234" clientCert := []byte(`-----BEGIN CERTIFICATE----- MIIB9jCCAV+gAwIBAgIBAjANBgkqhkiG9w0BAQsFADAYMRYwFAYDVQQDDA1DYWRk eSBUZXN0IENBMB4XDTE4MDcyNDIxMzUwNVoXDTI4MDcyMTIxMzUwNVowHTEbMBkG A1UEAwwSY2xpZW50LmxvY2FsZG9tYWluMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCB iQKBgQDFDEpzF0ew68teT3xDzcUxVFaTII+jXH1ftHXxxP4BEYBU4q90qzeKFneF z83I0nC0WAQ45ZwHfhLMYHFzHPdxr6+jkvKPASf0J2v2HDJuTM1bHBbik5Ls5eq+ fVZDP8o/VHKSBKxNs8Goc2NTsr5b07QTIpkRStQK+RJALk4x9QIDAQABo0swSTAJ BgNVHRMEAjAAMAsGA1UdDwQEAwIHgDAaBgNVHREEEzARgglsb2NhbGhvc3SHBH8A AAEwEwYDVR0lBAwwCgYIKwYBBQUHAwIwDQYJKoZIhvcNAQELBQADgYEANSjz2Sk+ eqp31wM9il1n+guTNyxJd+FzVAH+hCZE5K+tCgVDdVFUlDEHHbS/wqb2PSIoouLV 3Q9fgDkiUod+uIK0IynzIKvw+Cjg+3nx6NQ0IM0zo8c7v398RzB4apbXKZyeeqUH 9fNwfEi+OoXR6s+upSKobCmLGLGi9Na5s5g= -----END CERTIFICATE-----`) block, _ := pem.Decode(clientCert) if block == nil { t.Fatalf("failed to decode PEM certificate") } cert, err := x509.ParseCertificate(block.Bytes) if err != nil { t.Fatalf("failed to decode PEM certificate: %v", err) } req.TLS = &tls.ConnectionState{ Version: tls.VersionTLS13, HandshakeComplete: true, ServerName: "example.com", CipherSuite: tls.TLS_AES_256_GCM_SHA384, PeerCertificates: []*x509.Certificate{cert}, NegotiatedProtocol: "h2", NegotiatedProtocolIsMutual: true, } res := httptest.NewRecorder() addHTTPVarsToReplacer(repl, req, res) for i, tc := range []struct { get string expect string }{ { get: "http.request.scheme", expect: "https", }, { get: "http.request.method", expect: http.MethodGet, }, { get: "http.request.host", expect: "example.com", }, { get: "http.request.port", expect: "80", }, { get: "http.request.hostport", expect: "example.com:80", }, { get: "http.request.local.host", expect: "192.168.159.1", }, { get: "http.request.local.port", expect: "80", }, { get: "http.request.local", expect: "192.168.159.1:80", }, { get: "http.request.remote.host", expect: "192.168.159.32", }, { get: "http.request.remote.host/24", expect: "192.168.159.0/24", }, { get: "http.request.remote.host/24,32", expect: "192.168.159.0/24", }, { get: "http.request.remote.host/999", expect: "", }, { get: "http.request.remote.port", expect: "1234", }, { get: "http.request.host.labels.0", expect: "com", }, { get: "http.request.host.labels.1", expect: "example", }, { get: "http.request.host.labels.2", expect: "", }, { get: "http.request.uri", expect: "/foo/bar.tar.gz?a=1&b=2", }, { get: "http.request.uri_escaped", expect: "%2Ffoo%2Fbar.tar.gz%3Fa%3D1%26b%3D2", }, { get: "http.request.uri.path", expect: "/foo/bar.tar.gz", }, { get: "http.request.uri.path_escaped", expect: "%2Ffoo%2Fbar.tar.gz", }, { get: "http.request.uri.path.file", expect: "bar.tar.gz", }, { get: "http.request.uri.path.file.base", expect: "bar.tar", }, { // not ideal, but also most correct, given that files can have dots (example: index.<SHA>.html) TODO: maybe this isn't right.. get: "http.request.uri.path.file.ext", expect: ".gz", }, { get: "http.request.uri.query", expect: "a=1&b=2", }, { get: "http.request.uri.query_escaped", expect: "a%3D1%26b%3D2", }, { get: "http.request.uri.query.a", expect: "1", }, { get: "http.request.uri.query.b", expect: "2", }, { get: "http.request.uri.prefixed_query", expect: "?a=1&b=2", }, { get: "http.request.tls.cipher_suite", expect: "TLS_AES_256_GCM_SHA384", }, { get: "http.request.tls.proto", expect: "h2", }, { get: "http.request.tls.proto_mutual", expect: "true", }, { get: "http.request.tls.resumed", expect: "false", }, { get: "http.request.tls.server_name", expect: "example.com", }, { get: "http.request.tls.version", expect: "tls1.3", }, { get: "http.request.tls.client.fingerprint", expect: "9f57b7b497cceacc5459b76ac1c3afedbc12b300e728071f55f84168ff0f7702", }, { get: "http.request.tls.client.issuer", expect: "CN=Caddy Test CA", }, { get: "http.request.tls.client.serial", expect: "2", }, { get: "http.request.tls.client.subject", expect: "CN=client.localdomain", }, { get: "http.request.tls.client.san.dns_names", expect: "[localhost]", }, { get: "http.request.tls.client.san.dns_names.0", expect: "localhost", }, { get: "http.request.tls.client.san.dns_names.1", expect: "", }, { get: "http.request.tls.client.san.ips", expect: "[127.0.0.1]", }, { get: "http.request.tls.client.san.ips.0", expect: "127.0.0.1", }, { get: "http.request.tls.client.certificate_pem", expect: string(clientCert) + "\n", // returned value comes with a newline appended to it }, } { actual, got := repl.GetString(tc.get) if !got { t.Errorf("Test %d: Expected to recognize the placeholder name, but didn't", i) } if actual != tc.expect { t.Errorf("Test %d: Expected %s to be '%s' but got '%s'", i, tc.get, tc.expect, actual) } } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/httpredirectlistener.go
modules/caddyhttp/httpredirectlistener.go
// Copyright 2015 Matthew Holt and The Caddy 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 caddyhttp import ( "bufio" "bytes" "fmt" "io" "net" "net/http" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func init() { caddy.RegisterModule(HTTPRedirectListenerWrapper{}) } // HTTPRedirectListenerWrapper provides HTTP->HTTPS redirects for // connections that come on the TLS port as an HTTP request, // by detecting using the first few bytes that it's not a TLS // handshake, but instead an HTTP request. // // This is especially useful when using a non-standard HTTPS port. // A user may simply type the address in their browser without the // https:// scheme, which would cause the browser to attempt the // connection over HTTP, but this would cause a "Client sent an // HTTP request to an HTTPS server" error response. // // This listener wrapper must be placed BEFORE the "tls" listener // wrapper, for it to work properly. type HTTPRedirectListenerWrapper struct { // MaxHeaderBytes is the maximum size to parse from a client's // HTTP request headers. Default: 1 MB MaxHeaderBytes int64 `json:"max_header_bytes,omitempty"` } func (HTTPRedirectListenerWrapper) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "caddy.listeners.http_redirect", New: func() caddy.Module { return new(HTTPRedirectListenerWrapper) }, } } func (h *HTTPRedirectListenerWrapper) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { return nil } func (h *HTTPRedirectListenerWrapper) WrapListener(l net.Listener) net.Listener { return &httpRedirectListener{l, h.MaxHeaderBytes} } // httpRedirectListener is listener that checks the first few bytes // of the request when the server is intended to accept HTTPS requests, // to respond to an HTTP request with a redirect. type httpRedirectListener struct { net.Listener maxHeaderBytes int64 } // Accept waits for and returns the next connection to the listener, // wrapping it with a httpRedirectConn. func (l *httpRedirectListener) Accept() (net.Conn, error) { c, err := l.Listener.Accept() if err != nil { return nil, err } maxHeaderBytes := l.maxHeaderBytes if maxHeaderBytes == 0 { maxHeaderBytes = 1024 * 1024 } return &httpRedirectConn{ Conn: c, limit: maxHeaderBytes, r: bufio.NewReader(c), }, nil } type httpRedirectConn struct { net.Conn once bool limit int64 r *bufio.Reader } // Read tries to peek at the first few bytes of the request, and if we get // an error reading the headers, and that error was due to the bytes looking // like an HTTP request, then we perform a HTTP->HTTPS redirect on the same // port as the original connection. func (c *httpRedirectConn) Read(p []byte) (int, error) { if c.once { return c.r.Read(p) } // no need to use sync.Once - net.Conn is not read from concurrently. c.once = true firstBytes, err := c.r.Peek(5) if err != nil { return 0, err } // If the request doesn't look like HTTP, then it's probably // TLS bytes, and we don't need to do anything. if !firstBytesLookLikeHTTP(firstBytes) { return c.r.Read(p) } // From now on, we can be almost certain the request is HTTP. // The returned error will be non nil and caller are expected to // close the connection. // Set the read limit, io.MultiReader is needed because // when resetting, *bufio.Reader discards buffered data. buffered, _ := c.r.Peek(c.r.Buffered()) mr := io.MultiReader(bytes.NewReader(buffered), c.Conn) c.r.Reset(io.LimitReader(mr, c.limit)) // Parse the HTTP request, so we can get the Host and URL to redirect to. req, err := http.ReadRequest(c.r) if err != nil { return 0, fmt.Errorf("couldn't read HTTP request") } // Build the redirect response, using the same Host and URL, // but replacing the scheme with https. headers := make(http.Header) headers.Add("Location", "https://"+req.Host+req.URL.String()) resp := &http.Response{ Proto: "HTTP/1.0", Status: "308 Permanent Redirect", StatusCode: 308, ProtoMajor: 1, ProtoMinor: 0, Header: headers, } err = resp.Write(c.Conn) if err != nil { return 0, fmt.Errorf("couldn't write HTTP->HTTPS redirect") } return 0, fmt.Errorf("redirected HTTP request on HTTPS port") } // firstBytesLookLikeHTTP reports whether a TLS record header // looks like it might've been a misdirected plaintext HTTP request. func firstBytesLookLikeHTTP(hdr []byte) bool { switch string(hdr[:5]) { case "GET /", "HEAD ", "POST ", "PUT /", "OPTIO": return true } return false } var ( _ caddy.ListenerWrapper = (*HTTPRedirectListenerWrapper)(nil) _ caddyfile.Unmarshaler = (*HTTPRedirectListenerWrapper)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/invoke.go
modules/caddyhttp/invoke.go
// Copyright 2015 Matthew Holt and The Caddy 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 caddyhttp import ( "fmt" "net/http" "github.com/caddyserver/caddy/v2" ) func init() { caddy.RegisterModule(Invoke{}) } // Invoke implements a handler that compiles and executes a // named route that was defined on the server. // // EXPERIMENTAL: Subject to change or removal. type Invoke struct { // Name is the key of the named route to execute Name string `json:"name,omitempty"` } // CaddyModule returns the Caddy module information. func (Invoke) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.handlers.invoke", New: func() caddy.Module { return new(Invoke) }, } } func (invoke *Invoke) ServeHTTP(w http.ResponseWriter, r *http.Request, next Handler) error { server := r.Context().Value(ServerCtxKey).(*Server) if route, ok := server.NamedRoutes[invoke.Name]; ok { return route.Compile(next).ServeHTTP(w, r) } return fmt.Errorf("invoke: route '%s' not found", invoke.Name) } // Interface guards var ( _ MiddlewareHandler = (*Invoke)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/responsematchers.go
modules/caddyhttp/responsematchers.go
// Copyright 2015 Matthew Holt and The Caddy 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 caddyhttp import ( "net/http" "strconv" "strings" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) // ResponseMatcher is a type which can determine if an // HTTP response matches some criteria. type ResponseMatcher struct { // If set, one of these status codes would be required. // A one-digit status can be used to represent all codes // in that class (e.g. 3 for all 3xx codes). StatusCode []int `json:"status_code,omitempty"` // If set, each header specified must be one of the // specified values, with the same logic used by the // [request header matcher](/docs/json/apps/http/servers/routes/match/header/). Headers http.Header `json:"headers,omitempty"` } // Match returns true if the given statusCode and hdr match rm. func (rm ResponseMatcher) Match(statusCode int, hdr http.Header) bool { if !rm.matchStatusCode(statusCode) { return false } return matchHeaders(hdr, rm.Headers, "", []string{}, nil) } func (rm ResponseMatcher) matchStatusCode(statusCode int) bool { if rm.StatusCode == nil { return true } for _, code := range rm.StatusCode { if StatusCodeMatches(statusCode, code) { return true } } return false } // ParseNamedResponseMatcher parses the tokens of a named response matcher. // // @name { // header <field> [<value>] // status <code...> // } // // Or, single line syntax: // // @name [header <field> [<value>]] | [status <code...>] func ParseNamedResponseMatcher(d *caddyfile.Dispenser, matchers map[string]ResponseMatcher) error { d.Next() // consume matcher name definitionName := d.Val() if _, ok := matchers[definitionName]; ok { return d.Errf("matcher is defined more than once: %s", definitionName) } matcher := ResponseMatcher{} for nesting := d.Nesting(); d.NextArg() || d.NextBlock(nesting); { switch d.Val() { case "header": if matcher.Headers == nil { matcher.Headers = http.Header{} } // reuse the header request matcher's unmarshaler headerMatcher := MatchHeader(matcher.Headers) err := headerMatcher.UnmarshalCaddyfile(d.NewFromNextSegment()) if err != nil { return err } matcher.Headers = http.Header(headerMatcher) case "status": if matcher.StatusCode == nil { matcher.StatusCode = []int{} } args := d.RemainingArgs() if len(args) == 0 { return d.ArgErr() } for _, arg := range args { if len(arg) == 3 && strings.HasSuffix(arg, "xx") { arg = arg[:1] } statusNum, err := strconv.Atoi(arg) if err != nil { return d.Errf("bad status value '%s': %v", arg, err) } matcher.StatusCode = append(matcher.StatusCode, statusNum) } default: return d.Errf("unrecognized response matcher %s", d.Val()) } } matchers[definitionName] = matcher return nil }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/ip_range.go
modules/caddyhttp/ip_range.go
// Copyright 2015 Matthew Holt and The Caddy 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 caddyhttp import ( "fmt" "net/http" "net/netip" "strings" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/internal" ) func init() { caddy.RegisterModule(StaticIPRange{}) } // IPRangeSource gets a list of IP ranges. // // The request is passed as an argument to allow plugin implementations // to have more flexibility. But, a plugin MUST NOT modify the request. // The caller will have read the `r.RemoteAddr` before getting IP ranges. // // This should be a very fast function -- instant if possible. // The list of IP ranges should be sourced as soon as possible if loaded // from an external source (i.e. initially loaded during Provisioning), // so that it's ready to be used when requests start getting handled. // A read lock should probably be used to get the cached value if the // ranges can change at runtime (e.g. periodically refreshed). // Using a `caddy.UsagePool` may be a good idea to avoid having refetch // the values when a config reload occurs, which would waste time. // // If the list of IP ranges cannot be sourced, then provisioning SHOULD // fail. Getting the IP ranges at runtime MUST NOT fail, because it would // cancel incoming requests. If refreshing the list fails, then the // previous list of IP ranges should continue to be returned so that the // server can continue to operate normally. type IPRangeSource interface { GetIPRanges(*http.Request) []netip.Prefix } // StaticIPRange provides a static range of IP address prefixes (CIDRs). type StaticIPRange struct { // A static list of IP ranges (supports CIDR notation). Ranges []string `json:"ranges,omitempty"` // Holds the parsed CIDR ranges from Ranges. ranges []netip.Prefix } // CaddyModule returns the Caddy module information. func (StaticIPRange) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.ip_sources.static", New: func() caddy.Module { return new(StaticIPRange) }, } } func (s *StaticIPRange) Provision(ctx caddy.Context) error { for _, str := range s.Ranges { prefix, err := CIDRExpressionToPrefix(str) if err != nil { return err } s.ranges = append(s.ranges, prefix) } return nil } func (s *StaticIPRange) GetIPRanges(_ *http.Request) []netip.Prefix { return s.ranges } // UnmarshalCaddyfile implements caddyfile.Unmarshaler. func (m *StaticIPRange) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { if !d.Next() { return nil } for d.NextArg() { if d.Val() == "private_ranges" { m.Ranges = append(m.Ranges, internal.PrivateRangesCIDR()...) continue } m.Ranges = append(m.Ranges, d.Val()) } return nil } // CIDRExpressionToPrefix takes a string which could be either a // CIDR expression or a single IP address, and returns a netip.Prefix. func CIDRExpressionToPrefix(expr string) (netip.Prefix, error) { // Having a slash means it should be a CIDR expression if strings.Contains(expr, "/") { prefix, err := netip.ParsePrefix(expr) if err != nil { return netip.Prefix{}, fmt.Errorf("parsing CIDR expression: '%s': %v", expr, err) } return prefix, nil } // Otherwise it's likely a single IP address parsed, err := netip.ParseAddr(expr) if err != nil { return netip.Prefix{}, fmt.Errorf("invalid IP address: '%s': %v", expr, err) } prefix := netip.PrefixFrom(parsed, parsed.BitLen()) return prefix, nil } // Interface guards var ( _ caddy.Provisioner = (*StaticIPRange)(nil) _ caddyfile.Unmarshaler = (*StaticIPRange)(nil) _ IPRangeSource = (*StaticIPRange)(nil) ) // PrivateRangesCIDR returns a list of private CIDR range // strings, which can be used as a configuration shortcut. // Note: this function is used at least by mholt/caddy-l4. func PrivateRangesCIDR() []string { return internal.PrivateRangesCIDR() }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/app.go
modules/caddyhttp/app.go
// Copyright 2015 Matthew Holt and The Caddy 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 caddyhttp import ( "cmp" "context" "crypto/tls" "fmt" "maps" "net" "net/http" "strconv" "sync" "time" "go.uber.org/zap" "golang.org/x/net/http2" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyevents" "github.com/caddyserver/caddy/v2/modules/caddytls" ) func init() { caddy.RegisterModule(App{}) } // App is a robust, production-ready HTTP server. // // HTTPS is enabled by default if host matchers with qualifying names are used // in any of routes; certificates are automatically provisioned and renewed. // Additionally, automatic HTTPS will also enable HTTPS for servers that listen // only on the HTTPS port but which do not have any TLS connection policies // defined by adding a good, default TLS connection policy. // // In HTTP routes, additional placeholders are available (replace any `*`): // // Placeholder | Description // ------------|--------------- // `{http.request.body}` | The request body (⚠️ inefficient; use only for debugging) // `{http.request.body_base64}` | The request body, base64-encoded (⚠️ for debugging) // `{http.request.cookie.*}` | HTTP request cookie // `{http.request.duration}` | Time up to now spent handling the request (after decoding headers from client) // `{http.request.duration_ms}` | Same as 'duration', but in milliseconds. // `{http.request.uuid}` | The request unique identifier // `{http.request.header.*}` | Specific request header field // `{http.request.host}` | The host part of the request's Host header // `{http.request.host.labels.*}` | Request host labels (0-based from right); e.g. for foo.example.com: 0=com, 1=example, 2=foo // `{http.request.hostport}` | The host and port from the request's Host header // `{http.request.method}` | The request method // `{http.request.orig_method}` | The request's original method // `{http.request.orig_uri}` | The request's original URI // `{http.request.orig_uri.path}` | The request's original path // `{http.request.orig_uri.path.*}` | Parts of the original path, split by `/` (0-based from left) // `{http.request.orig_uri.path.dir}` | The request's original directory // `{http.request.orig_uri.path.file}` | The request's original filename // `{http.request.orig_uri.query}` | The request's original query string (without `?`) // `{http.request.port}` | The port part of the request's Host header // `{http.request.proto}` | The protocol of the request // `{http.request.local.host}` | The host (IP) part of the local address the connection arrived on // `{http.request.local.port}` | The port part of the local address the connection arrived on // `{http.request.local}` | The local address the connection arrived on // `{http.request.remote.host}` | The host (IP) part of the remote client's address, if available (not known with HTTP/3 early data) // `{http.request.remote.port}` | The port part of the remote client's address // `{http.request.remote}` | The address of the remote client // `{http.request.scheme}` | The request scheme, typically `http` or `https` // `{http.request.tls.version}` | The TLS version name // `{http.request.tls.cipher_suite}` | The TLS cipher suite // `{http.request.tls.resumed}` | The TLS connection resumed a previous connection // `{http.request.tls.proto}` | The negotiated next protocol // `{http.request.tls.proto_mutual}` | The negotiated next protocol was advertised by the server // `{http.request.tls.server_name}` | The server name requested by the client, if any // `{http.request.tls.ech}` | Whether ECH was offered by the client and accepted by the server // `{http.request.tls.client.fingerprint}` | The SHA256 checksum of the client certificate // `{http.request.tls.client.public_key}` | The public key of the client certificate. // `{http.request.tls.client.public_key_sha256}` | The SHA256 checksum of the client's public key. // `{http.request.tls.client.certificate_pem}` | The PEM-encoded value of the certificate. // `{http.request.tls.client.certificate_der_base64}` | The base64-encoded value of the certificate. // `{http.request.tls.client.issuer}` | The issuer DN of the client certificate // `{http.request.tls.client.serial}` | The serial number of the client certificate // `{http.request.tls.client.subject}` | The subject DN of the client certificate // `{http.request.tls.client.san.dns_names.*}` | SAN DNS names(index optional) // `{http.request.tls.client.san.emails.*}` | SAN email addresses (index optional) // `{http.request.tls.client.san.ips.*}` | SAN IP addresses (index optional) // `{http.request.tls.client.san.uris.*}` | SAN URIs (index optional) // `{http.request.uri}` | The full request URI // `{http.request.uri.path}` | The path component of the request URI // `{http.request.uri.path.*}` | Parts of the path, split by `/` (0-based from left) // `{http.request.uri.path.dir}` | The directory, excluding leaf filename // `{http.request.uri.path.file}` | The filename of the path, excluding directory // `{http.request.uri.query}` | The query string (without `?`) // `{http.request.uri.query.*}` | Individual query string value // `{http.response.header.*}` | Specific response header field // `{http.vars.*}` | Custom variables in the HTTP handler chain // `{http.shutting_down}` | True if the HTTP app is shutting down // `{http.time_until_shutdown}` | Time until HTTP server shutdown, if scheduled type App struct { // HTTPPort specifies the port to use for HTTP (as opposed to HTTPS), // which is used when setting up HTTP->HTTPS redirects or ACME HTTP // challenge solvers. Default: 80. HTTPPort int `json:"http_port,omitempty"` // HTTPSPort specifies the port to use for HTTPS, which is used when // solving the ACME TLS-ALPN challenges, or whenever HTTPS is needed // but no specific port number is given. Default: 443. HTTPSPort int `json:"https_port,omitempty"` // GracePeriod is how long to wait for active connections when shutting // down the servers. During the grace period, no new connections are // accepted, idle connections are closed, and active connections will // be given the full length of time to become idle and close. // Once the grace period is over, connections will be forcefully closed. // If zero, the grace period is eternal. Default: 0. GracePeriod caddy.Duration `json:"grace_period,omitempty"` // ShutdownDelay is how long to wait before initiating the grace // period. When this app is stopping (e.g. during a config reload or // process exit), all servers will be shut down. Normally this immediately // initiates the grace period. However, if this delay is configured, servers // will not be shut down until the delay is over. During this time, servers // continue to function normally and allow new connections. At the end, the // grace period will begin. This can be useful to allow downstream load // balancers time to move this instance out of the rotation without hiccups. // // When shutdown has been scheduled, placeholders {http.shutting_down} (bool) // and {http.time_until_shutdown} (duration) may be useful for health checks. ShutdownDelay caddy.Duration `json:"shutdown_delay,omitempty"` // Servers is the list of servers, keyed by arbitrary names chosen // at your discretion for your own convenience; the keys do not // affect functionality. Servers map[string]*Server `json:"servers,omitempty"` // If set, metrics observations will be enabled. // This setting is EXPERIMENTAL and subject to change. Metrics *Metrics `json:"metrics,omitempty"` ctx caddy.Context logger *zap.Logger tlsApp *caddytls.TLS // stopped indicates whether the app has stopped // It can only happen if it has started successfully in the first place. // Otherwise, Cleanup will call Stop to clean up resources. stopped bool // used temporarily between phases 1 and 2 of auto HTTPS allCertDomains map[string]struct{} } // CaddyModule returns the Caddy module information. func (App) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http", New: func() caddy.Module { return new(App) }, } } // Provision sets up the app. func (app *App) Provision(ctx caddy.Context) error { // store some references app.logger = ctx.Logger() app.ctx = ctx // provision TLS and events apps tlsAppIface, err := ctx.App("tls") if err != nil { return fmt.Errorf("getting tls app: %v", err) } app.tlsApp = tlsAppIface.(*caddytls.TLS) eventsAppIface, err := ctx.App("events") if err != nil { return fmt.Errorf("getting events app: %v", err) } repl := caddy.NewReplacer() // this provisions the matchers for each route, // and prepares auto HTTP->HTTPS redirects, and // is required before we provision each server err = app.automaticHTTPSPhase1(ctx, repl) if err != nil { return err } if app.Metrics != nil { app.Metrics.init = sync.Once{} app.Metrics.httpMetrics = &httpMetrics{} // Scan config for allowed hosts to prevent cardinality explosion app.Metrics.scanConfigForHosts(app) } // prepare each server oldContext := ctx.Context for srvName, srv := range app.Servers { ctx.Context = context.WithValue(oldContext, ServerCtxKey, srv) srv.name = srvName srv.tlsApp = app.tlsApp srv.events = eventsAppIface.(*caddyevents.App) srv.ctx = ctx srv.logger = app.logger.Named("log") srv.errorLogger = app.logger.Named("log.error") srv.shutdownAtMu = new(sync.RWMutex) if srv.Metrics != nil { srv.logger.Warn("per-server 'metrics' is deprecated; use 'metrics' in the root 'http' app instead") app.Metrics = cmp.Or(app.Metrics, &Metrics{ init: sync.Once{}, httpMetrics: &httpMetrics{}, }) app.Metrics.PerHost = app.Metrics.PerHost || srv.Metrics.PerHost } // only enable access logs if configured if srv.Logs != nil { srv.accessLogger = app.logger.Named("log.access") if srv.Logs.Trace { srv.traceLogger = app.logger.Named("log.trace") } } // if no protocols configured explicitly, enable all except h2c if len(srv.Protocols) == 0 { srv.Protocols = []string{"h1", "h2", "h3"} } srvProtocolsUnique := map[string]struct{}{} for _, srvProtocol := range srv.Protocols { srvProtocolsUnique[srvProtocol] = struct{}{} } if srv.ListenProtocols != nil { if len(srv.ListenProtocols) != len(srv.Listen) { return fmt.Errorf("server %s: listener protocols count does not match address count: %d != %d", srvName, len(srv.ListenProtocols), len(srv.Listen)) } for i, lnProtocols := range srv.ListenProtocols { if lnProtocols != nil { // populate empty listen protocols with server protocols lnProtocolsDefault := false var lnProtocolsInclude []string srvProtocolsInclude := maps.Clone(srvProtocolsUnique) // keep existing listener protocols unless they are empty for _, lnProtocol := range lnProtocols { if lnProtocol == "" { lnProtocolsDefault = true } else { lnProtocolsInclude = append(lnProtocolsInclude, lnProtocol) delete(srvProtocolsInclude, lnProtocol) } } // append server protocols to listener protocols if any listener protocols were empty if lnProtocolsDefault { for _, srvProtocol := range srv.Protocols { if _, ok := srvProtocolsInclude[srvProtocol]; ok { lnProtocolsInclude = append(lnProtocolsInclude, srvProtocol) } } } srv.ListenProtocols[i] = lnProtocolsInclude } } } // if not explicitly configured by the user, disallow TLS // client auth bypass (domain fronting) which could // otherwise be exploited by sending an unprotected SNI // value during a TLS handshake, then putting a protected // domain in the Host header after establishing connection; // this is a safe default, but we allow users to override // it for example in the case of running a proxy where // domain fronting is desired and access is not restricted // based on hostname if srv.StrictSNIHost == nil && srv.hasTLSClientAuth() { app.logger.Warn("enabling strict SNI-Host enforcement because TLS client auth is configured", zap.String("server_id", srvName)) trueBool := true srv.StrictSNIHost = &trueBool } // set up the trusted proxies source for srv.TrustedProxiesRaw != nil { val, err := ctx.LoadModule(srv, "TrustedProxiesRaw") if err != nil { return fmt.Errorf("loading trusted proxies modules: %v", err) } srv.trustedProxies = val.(IPRangeSource) } // set the default client IP header to read from if srv.ClientIPHeaders == nil { srv.ClientIPHeaders = []string{"X-Forwarded-For"} } // process each listener address for i := range srv.Listen { lnOut, err := repl.ReplaceOrErr(srv.Listen[i], true, true) if err != nil { return fmt.Errorf("server %s, listener %d: %v", srvName, i, err) } srv.Listen[i] = lnOut } // set up each listener modifier if srv.ListenerWrappersRaw != nil { vals, err := ctx.LoadModule(srv, "ListenerWrappersRaw") if err != nil { return fmt.Errorf("loading listener wrapper modules: %v", err) } var hasTLSPlaceholder bool for i, val := range vals.([]any) { if _, ok := val.(*tlsPlaceholderWrapper); ok { if i == 0 { // putting the tls placeholder wrapper first is nonsensical because // that is the default, implicit setting: without it, all wrappers // will go after the TLS listener anyway return fmt.Errorf("it is unnecessary to specify the TLS listener wrapper in the first position because that is the default") } if hasTLSPlaceholder { return fmt.Errorf("TLS listener wrapper can only be specified once") } hasTLSPlaceholder = true } srv.listenerWrappers = append(srv.listenerWrappers, val.(caddy.ListenerWrapper)) } // if any wrappers were configured but the TLS placeholder wrapper is // absent, prepend it so all defined wrappers come after the TLS // handshake; this simplifies logic when starting the server, since we // can simply assume the TLS placeholder will always be there if !hasTLSPlaceholder && len(srv.listenerWrappers) > 0 { srv.listenerWrappers = append([]caddy.ListenerWrapper{new(tlsPlaceholderWrapper)}, srv.listenerWrappers...) } } // set up each packet conn modifier if srv.PacketConnWrappersRaw != nil { vals, err := ctx.LoadModule(srv, "PacketConnWrappersRaw") if err != nil { return fmt.Errorf("loading packet conn wrapper modules: %v", err) } // if any wrappers were configured, they come before the QUIC handshake; // unlike TLS above, there is no QUIC placeholder for _, val := range vals.([]any) { srv.packetConnWrappers = append(srv.packetConnWrappers, val.(caddy.PacketConnWrapper)) } } // pre-compile the primary handler chain, and be sure to wrap it in our // route handler so that important security checks are done, etc. primaryRoute := emptyHandler if srv.Routes != nil { err := srv.Routes.ProvisionHandlers(ctx, app.Metrics) if err != nil { return fmt.Errorf("server %s: setting up route handlers: %v", srvName, err) } primaryRoute = srv.Routes.Compile(emptyHandler) } srv.primaryHandlerChain = srv.wrapPrimaryRoute(primaryRoute) // pre-compile the error handler chain if srv.Errors != nil { err := srv.Errors.Routes.Provision(ctx) if err != nil { return fmt.Errorf("server %s: setting up error handling routes: %v", srvName, err) } srv.errorHandlerChain = srv.Errors.Routes.Compile(errorEmptyHandler) } // provision the named routes (they get compiled at runtime) for name, route := range srv.NamedRoutes { err := route.Provision(ctx, app.Metrics) if err != nil { return fmt.Errorf("server %s: setting up named route '%s' handlers: %v", name, srvName, err) } } // prepare the TLS connection policies err = srv.TLSConnPolicies.Provision(ctx) if err != nil { return fmt.Errorf("server %s: setting up TLS connection policies: %v", srvName, err) } // if there is no idle timeout, set a sane default; users have complained // before that aggressive CDNs leave connections open until the server // closes them, so if we don't close them it leads to resource exhaustion if srv.IdleTimeout == 0 { srv.IdleTimeout = defaultIdleTimeout } if srv.ReadHeaderTimeout == 0 { srv.ReadHeaderTimeout = defaultReadHeaderTimeout // see #6663 } } ctx.Context = oldContext return nil } // Validate ensures the app's configuration is valid. func (app *App) Validate() error { lnAddrs := make(map[string]string) for srvName, srv := range app.Servers { // each server must use distinct listener addresses for _, addr := range srv.Listen { listenAddr, err := caddy.ParseNetworkAddress(addr) if err != nil { return fmt.Errorf("invalid listener address '%s': %v", addr, err) } // check that every address in the port range is unique to this server; // we do not use <= here because PortRangeSize() adds 1 to EndPort for us for i := uint(0); i < listenAddr.PortRangeSize(); i++ { addr := caddy.JoinNetworkAddress(listenAddr.Network, listenAddr.Host, strconv.FormatUint(uint64(listenAddr.StartPort+i), 10)) if sn, ok := lnAddrs[addr]; ok { return fmt.Errorf("server %s: listener address repeated: %s (already claimed by server '%s')", srvName, addr, sn) } lnAddrs[addr] = srvName } } // logger names must not have ports if srv.Logs != nil { for host := range srv.Logs.LoggerNames { if _, _, err := net.SplitHostPort(host); err == nil { return fmt.Errorf("server %s: logger name must not have a port: %s", srvName, host) } } } } return nil } func removeTLSALPN(srv *Server, target string) { for _, cp := range srv.TLSConnPolicies { // the TLSConfig was already provisioned, so... manually remove it for i, np := range cp.TLSConfig.NextProtos { if np == target { cp.TLSConfig.NextProtos = append(cp.TLSConfig.NextProtos[:i], cp.TLSConfig.NextProtos[i+1:]...) break } } // remove it from the parent connection policy too, just to keep things tidy for i, alpn := range cp.ALPN { if alpn == target { cp.ALPN = append(cp.ALPN[:i], cp.ALPN[i+1:]...) break } } } } // Start runs the app. It finishes automatic HTTPS if enabled, // including management of certificates. func (app *App) Start() error { // get a logger compatible with http.Server serverLogger, err := zap.NewStdLogAt(app.logger.Named("stdlib"), zap.DebugLevel) if err != nil { return fmt.Errorf("failed to set up server logger: %v", err) } for srvName, srv := range app.Servers { srv.server = &http.Server{ ReadTimeout: time.Duration(srv.ReadTimeout), ReadHeaderTimeout: time.Duration(srv.ReadHeaderTimeout), WriteTimeout: time.Duration(srv.WriteTimeout), IdleTimeout: time.Duration(srv.IdleTimeout), MaxHeaderBytes: srv.MaxHeaderBytes, Handler: srv, ErrorLog: serverLogger, Protocols: new(http.Protocols), ConnContext: func(ctx context.Context, c net.Conn) context.Context { if nc, ok := c.(interface{ tlsNetConn() net.Conn }); ok { getTlsConStateFunc := sync.OnceValue(func() *tls.ConnectionState { tlsConnState := nc.tlsNetConn().(connectionStater).ConnectionState() return &tlsConnState }) ctx = context.WithValue(ctx, tlsConnectionStateFuncCtxKey, getTlsConStateFunc) } return ctx }, } // disable HTTP/2, which we enabled by default during provisioning if !srv.protocol("h2") { srv.server.TLSNextProto = make(map[string]func(*http.Server, *tls.Conn, http.Handler)) removeTLSALPN(srv, "h2") } if !srv.protocol("h1") { removeTLSALPN(srv, "http/1.1") } // configure the http versions the server will serve if srv.protocol("h1") { srv.server.Protocols.SetHTTP1(true) } if srv.protocol("h2") || srv.protocol("h2c") { // skip setting h2 because if NextProtos is present, it's list of alpn versions will take precedence. // it will always be present because http2.ConfigureServer will populate that field // enabling h2c because some listener wrapper will wrap the connection that is no longer *tls.Conn // However, we need to handle the case that if the connection is h2c but h2c is not enabled. We identify // this type of connection by checking if it's behind a TLS listener wrapper or if it implements tls.ConnectionState. srv.server.Protocols.SetUnencryptedHTTP2(true) // when h2c is enabled but h2 disabled, we already removed h2 from NextProtos // the handshake will never succeed with h2 // http2.ConfigureServer will enable the server to handle both h2 and h2c h2server := new(http2.Server) //nolint:errcheck http2.ConfigureServer(srv.server, h2server) } // this TLS config is used by the std lib to choose the actual TLS config for connections // by looking through the connection policies to find the first one that matches tlsCfg := srv.TLSConnPolicies.TLSConfig(app.ctx) srv.configureServer(srv.server) for lnIndex, lnAddr := range srv.Listen { listenAddr, err := caddy.ParseNetworkAddress(lnAddr) if err != nil { return fmt.Errorf("%s: parsing listen address '%s': %v", srvName, lnAddr, err) } srv.addresses = append(srv.addresses, listenAddr) protocols := srv.Protocols if srv.ListenProtocols != nil && srv.ListenProtocols[lnIndex] != nil { protocols = srv.ListenProtocols[lnIndex] } protocolsUnique := map[string]struct{}{} for _, protocol := range protocols { protocolsUnique[protocol] = struct{}{} } _, h1ok := protocolsUnique["h1"] _, h2ok := protocolsUnique["h2"] _, h2cok := protocolsUnique["h2c"] _, h3ok := protocolsUnique["h3"] for portOffset := uint(0); portOffset < listenAddr.PortRangeSize(); portOffset++ { hostport := listenAddr.JoinHostPort(portOffset) // enable TLS if there is a policy and if this is not the HTTP port useTLS := len(srv.TLSConnPolicies) > 0 && int(listenAddr.StartPort+portOffset) != app.httpPort() if h1ok || h2ok && useTLS || h2cok { // create the listener for this socket lnAny, err := listenAddr.Listen(app.ctx, portOffset, net.ListenConfig{ KeepAliveConfig: net.KeepAliveConfig{ Enable: srv.KeepAliveInterval >= 0, Interval: time.Duration(srv.KeepAliveInterval), Idle: time.Duration(srv.KeepAliveIdle), Count: srv.KeepAliveCount, }, }) if err != nil { return fmt.Errorf("listening on %s: %v", listenAddr.At(portOffset), err) } ln, ok := lnAny.(net.Listener) if !ok { return fmt.Errorf("network '%s' cannot handle HTTP/1 or HTTP/2 connections", listenAddr.Network) } // wrap listener before TLS (up to the TLS placeholder wrapper) var lnWrapperIdx int for i, lnWrapper := range srv.listenerWrappers { if _, ok := lnWrapper.(*tlsPlaceholderWrapper); ok { lnWrapperIdx = i + 1 // mark the next wrapper's spot break } ln = lnWrapper.WrapListener(ln) } if useTLS { // create TLS listener - this enables and terminates TLS ln = tls.NewListener(ln, tlsCfg) } // finish wrapping listener where we left off before TLS for i := lnWrapperIdx; i < len(srv.listenerWrappers); i++ { ln = srv.listenerWrappers[i].WrapListener(ln) } // check if the connection is h2c ln = &http2Listener{ useTLS: useTLS, useH1: h1ok, useH2: h2ok || h2cok, Listener: ln, logger: app.logger, } // if binding to port 0, the OS chooses a port for us; // but the user won't know the port unless we print it if !listenAddr.IsUnixNetwork() && !listenAddr.IsFdNetwork() && listenAddr.StartPort == 0 && listenAddr.EndPort == 0 { app.logger.Info("port 0 listener", zap.String("input_address", lnAddr), zap.String("actual_address", ln.Addr().String())) } app.logger.Debug("starting server loop", zap.String("address", ln.Addr().String()), zap.Bool("tls", useTLS), zap.Bool("http3", srv.h3server != nil)) srv.listeners = append(srv.listeners, ln) //nolint:errcheck go srv.server.Serve(ln) } if h2ok && !useTLS { // Can only serve h2 with TLS enabled app.logger.Warn("HTTP/2 skipped because it requires TLS", zap.String("network", listenAddr.Network), zap.String("addr", hostport)) } if h3ok { // Can't serve HTTP/3 on the same socket as HTTP/1 and 2 because it uses // a different transport mechanism... which is fine, but the OS doesn't // differentiate between a SOCK_STREAM file and a SOCK_DGRAM file; they // are still one file on the system. So even though "unixpacket" and // "unixgram" are different network types just as "tcp" and "udp" are, // the OS will not let us use the same file as both STREAM and DGRAM. if listenAddr.IsUnixNetwork() { app.logger.Warn("HTTP/3 disabled because Unix can't multiplex STREAM and DGRAM on same socket", zap.String("file", hostport)) continue } if useTLS { // enable HTTP/3 if configured app.logger.Info("enabling HTTP/3 listener", zap.String("addr", hostport)) if err := srv.serveHTTP3(listenAddr.At(portOffset), tlsCfg); err != nil { return err } } else { // Can only serve h3 with TLS enabled app.logger.Warn("HTTP/3 skipped because it requires TLS", zap.String("network", listenAddr.Network), zap.String("addr", hostport)) } } } } srv.logger.Info("server running", zap.String("name", srvName), zap.Strings("protocols", srv.Protocols)) } // finish automatic HTTPS by finally beginning // certificate management err = app.automaticHTTPSPhase2() if err != nil { return fmt.Errorf("finalizing automatic HTTPS: %v", err) } return nil } // Stop gracefully shuts down the HTTP server. func (app *App) Stop() error { ctx := context.Background() // see if any listeners in our config will be closing or if they are continuing // through a reload; because if any are closing, we will enforce shutdown delay var delay bool scheduledTime := time.Now().Add(time.Duration(app.ShutdownDelay)) if app.ShutdownDelay > 0 { for _, server := range app.Servers { for _, na := range server.addresses { for _, addr := range na.Expand() { if caddy.ListenerUsage(addr.Network, addr.JoinHostPort(0)) < 2 { app.logger.Debug("listener closing and shutdown delay is configured", zap.String("address", addr.String())) server.shutdownAtMu.Lock() server.shutdownAt = scheduledTime server.shutdownAtMu.Unlock() delay = true } else { app.logger.Debug("shutdown delay configured but listener will remain open", zap.String("address", addr.String())) } } } } } // honor scheduled/delayed shutdown time if delay { app.logger.Info("shutdown scheduled", zap.Duration("delay_duration", time.Duration(app.ShutdownDelay)), zap.Time("time", scheduledTime)) time.Sleep(time.Duration(app.ShutdownDelay)) } // enforce grace period if configured if app.GracePeriod > 0 { var cancel context.CancelFunc ctx, cancel = context.WithTimeout(ctx, time.Duration(app.GracePeriod)) defer cancel() app.logger.Info("servers shutting down; grace period initiated", zap.Duration("duration", time.Duration(app.GracePeriod))) } else { app.logger.Info("servers shutting down with eternal grace period") } // goroutines aren't guaranteed to be scheduled right away, // so we'll use one WaitGroup to wait for all the goroutines // to start their server shutdowns, and another to wait for // them to finish; we'll always block for them to start so // that when we return the caller can be confident* that the // old servers are no longer accepting new connections // (* the scheduler might still pause them right before // calling Shutdown(), but it's unlikely) var startedShutdown, finishedShutdown sync.WaitGroup // these will run in goroutines stopServer := func(server *Server) { defer finishedShutdown.Done() startedShutdown.Done() // possible if server failed to Start if server.server == nil { return } if err := server.server.Shutdown(ctx); err != nil { app.logger.Error("server shutdown", zap.Error(err), zap.Strings("addresses", server.Listen)) } } stopH3Server := func(server *Server) { defer finishedShutdown.Done() startedShutdown.Done() if server.h3server == nil { return } // closing quic listeners won't affect accepted connections now // so like stdlib, close listeners first, but keep the net.PacketConns open for _, h3ln := range server.quicListeners { if err := h3ln.Close(); err != nil { app.logger.Error("http3 listener close", zap.Error(err)) } } if err := server.h3server.Shutdown(ctx); err != nil { app.logger.Error("HTTP/3 server shutdown", zap.Error(err), zap.Strings("addresses", server.Listen)) } // close the underlying net.PacketConns now // see the comment for ListenQUIC for _, h3ln := range server.quicListeners { if err := h3ln.Close(); err != nil { app.logger.Error("http3 listener close socket", zap.Error(err)) } } } for _, server := range app.Servers { startedShutdown.Add(2) finishedShutdown.Add(2) go stopServer(server) go stopH3Server(server) } // block until all the goroutines have been run by the scheduler; // this means that they have likely called Shutdown() by now startedShutdown.Wait() // if the process is exiting, we need to block here and wait // for the grace periods to complete, otherwise the process will // terminate before the servers are finished shutting down; but // we don't really need to wait for the grace period to finish // if the process isn't exiting (but note that frequent config // reloads with long grace periods for a sustained length of time // may deplete resources) if caddy.Exiting() { finishedShutdown.Wait() } // run stop callbacks now that the server shutdowns are complete for name, s := range app.Servers { for _, stopHook := range s.onStopFuncs { if err := stopHook(ctx); err != nil { app.logger.Error("server stop hook", zap.String("server", name), zap.Error(err)) } } } app.stopped = true return nil } // Cleanup will close remaining listeners if they still remain // because some of the servers fail to start. // It simply calls Stop because Stop won't be called when Start fails. func (app *App) Cleanup() error { if app.stopped { return nil } return app.Stop() } func (app *App) httpPort() int { if app.HTTPPort == 0 { return DefaultHTTPPort } return app.HTTPPort } func (app *App) httpsPort() int { if app.HTTPSPort == 0 { return DefaultHTTPSPort } return app.HTTPSPort } const ( // defaultIdleTimeout is the default HTTP server timeout // for closing idle connections; useful to avoid resource // exhaustion behind hungry CDNs, for example (we've had // several complaints without this). defaultIdleTimeout = caddy.Duration(5 * time.Minute) // defaultReadHeaderTimeout is the default timeout for // reading HTTP headers from clients. Headers are generally // small, often less than 1 KB, so it shouldn't take a // long time even on legitimately slow connections or // busy servers to read it. defaultReadHeaderTimeout = caddy.Duration(time.Minute) ) // Interface guards var ( _ caddy.App = (*App)(nil) _ caddy.Provisioner = (*App)(nil) _ caddy.Validator = (*App)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/metrics_test.go
modules/caddyhttp/metrics_test.go
package caddyhttp import ( "context" "crypto/tls" "errors" "net/http" "net/http/httptest" "strings" "sync" "testing" "github.com/prometheus/client_golang/prometheus/testutil" "github.com/caddyserver/caddy/v2" ) func TestServerNameFromContext(t *testing.T) { ctx := context.Background() expected := "UNKNOWN" if actual := serverNameFromContext(ctx); actual != expected { t.Errorf("Not equal: expected %q, but got %q", expected, actual) } in := "foo" ctx = context.WithValue(ctx, ServerCtxKey, &Server{name: in}) if actual := serverNameFromContext(ctx); actual != in { t.Errorf("Not equal: expected %q, but got %q", in, actual) } } func TestMetricsInstrumentedHandler(t *testing.T) { ctx, _ := caddy.NewContext(caddy.Context{Context: context.Background()}) metrics := &Metrics{ init: sync.Once{}, httpMetrics: &httpMetrics{}, } handlerErr := errors.New("oh noes") response := []byte("hello world!") h := HandlerFunc(func(w http.ResponseWriter, r *http.Request) error { if actual := testutil.ToFloat64(metrics.httpMetrics.requestInFlight); actual != 1.0 { t.Errorf("Not same: expected %#v, but got %#v", 1.0, actual) } if handlerErr == nil { w.Write(response) } return handlerErr }) mh := middlewareHandlerFunc(func(w http.ResponseWriter, r *http.Request, h Handler) error { return h.ServeHTTP(w, r) }) ih := newMetricsInstrumentedHandler(ctx, "bar", mh, metrics) r := httptest.NewRequest("GET", "/", nil) w := httptest.NewRecorder() if actual := ih.ServeHTTP(w, r, h); actual != handlerErr { t.Errorf("Not same: expected %#v, but got %#v", handlerErr, actual) } if actual := testutil.ToFloat64(metrics.httpMetrics.requestInFlight); actual != 0.0 { t.Errorf("Not same: expected %#v, but got %#v", 0.0, actual) } handlerErr = nil if err := ih.ServeHTTP(w, r, h); err != nil { t.Errorf("Received unexpected error: %v", err) } // an empty handler - no errors, no header written mh = middlewareHandlerFunc(func(w http.ResponseWriter, r *http.Request, h Handler) error { return nil }) ih = newMetricsInstrumentedHandler(ctx, "empty", mh, metrics) r = httptest.NewRequest("GET", "/", nil) w = httptest.NewRecorder() if err := ih.ServeHTTP(w, r, h); err != nil { t.Errorf("Received unexpected error: %v", err) } if actual := w.Result().StatusCode; actual != 200 { t.Errorf("Not same: expected status code %#v, but got %#v", 200, actual) } if actual := w.Result().Header; len(actual) != 0 { t.Errorf("Not empty: expected headers to be empty, but got %#v", actual) } // handler returning an error with an HTTP status mh = middlewareHandlerFunc(func(w http.ResponseWriter, r *http.Request, h Handler) error { return Error(http.StatusTooManyRequests, nil) }) ih = newMetricsInstrumentedHandler(ctx, "foo", mh, metrics) r = httptest.NewRequest("GET", "/", nil) w = httptest.NewRecorder() if err := ih.ServeHTTP(w, r, nil); err == nil { t.Errorf("expected error to be propagated") } expected := ` # HELP caddy_http_request_duration_seconds Histogram of round-trip request durations. # TYPE caddy_http_request_duration_seconds histogram caddy_http_request_duration_seconds_bucket{code="429",handler="foo",method="GET",server="UNKNOWN",le="0.005"} 1 caddy_http_request_duration_seconds_bucket{code="429",handler="foo",method="GET",server="UNKNOWN",le="0.01"} 1 caddy_http_request_duration_seconds_bucket{code="429",handler="foo",method="GET",server="UNKNOWN",le="0.025"} 1 caddy_http_request_duration_seconds_bucket{code="429",handler="foo",method="GET",server="UNKNOWN",le="0.05"} 1 caddy_http_request_duration_seconds_bucket{code="429",handler="foo",method="GET",server="UNKNOWN",le="0.1"} 1 caddy_http_request_duration_seconds_bucket{code="429",handler="foo",method="GET",server="UNKNOWN",le="0.25"} 1 caddy_http_request_duration_seconds_bucket{code="429",handler="foo",method="GET",server="UNKNOWN",le="0.5"} 1 caddy_http_request_duration_seconds_bucket{code="429",handler="foo",method="GET",server="UNKNOWN",le="1"} 1 caddy_http_request_duration_seconds_bucket{code="429",handler="foo",method="GET",server="UNKNOWN",le="2.5"} 1 caddy_http_request_duration_seconds_bucket{code="429",handler="foo",method="GET",server="UNKNOWN",le="5"} 1 caddy_http_request_duration_seconds_bucket{code="429",handler="foo",method="GET",server="UNKNOWN",le="10"} 1 caddy_http_request_duration_seconds_bucket{code="429",handler="foo",method="GET",server="UNKNOWN",le="+Inf"} 1 caddy_http_request_duration_seconds_count{code="429",handler="foo",method="GET",server="UNKNOWN"} 1 # HELP caddy_http_request_size_bytes Total size of the request. Includes body # TYPE caddy_http_request_size_bytes histogram caddy_http_request_size_bytes_bucket{code="200",handler="bar",method="GET",server="UNKNOWN",le="256"} 1 caddy_http_request_size_bytes_bucket{code="200",handler="bar",method="GET",server="UNKNOWN",le="1024"} 1 caddy_http_request_size_bytes_bucket{code="200",handler="bar",method="GET",server="UNKNOWN",le="4096"} 1 caddy_http_request_size_bytes_bucket{code="200",handler="bar",method="GET",server="UNKNOWN",le="16384"} 1 caddy_http_request_size_bytes_bucket{code="200",handler="bar",method="GET",server="UNKNOWN",le="65536"} 1 caddy_http_request_size_bytes_bucket{code="200",handler="bar",method="GET",server="UNKNOWN",le="262144"} 1 caddy_http_request_size_bytes_bucket{code="200",handler="bar",method="GET",server="UNKNOWN",le="1.048576e+06"} 1 caddy_http_request_size_bytes_bucket{code="200",handler="bar",method="GET",server="UNKNOWN",le="4.194304e+06"} 1 caddy_http_request_size_bytes_bucket{code="200",handler="bar",method="GET",server="UNKNOWN",le="+Inf"} 1 caddy_http_request_size_bytes_sum{code="200",handler="bar",method="GET",server="UNKNOWN"} 23 caddy_http_request_size_bytes_count{code="200",handler="bar",method="GET",server="UNKNOWN"} 1 caddy_http_request_size_bytes_bucket{code="200",handler="empty",method="GET",server="UNKNOWN",le="256"} 1 caddy_http_request_size_bytes_bucket{code="200",handler="empty",method="GET",server="UNKNOWN",le="1024"} 1 caddy_http_request_size_bytes_bucket{code="200",handler="empty",method="GET",server="UNKNOWN",le="4096"} 1 caddy_http_request_size_bytes_bucket{code="200",handler="empty",method="GET",server="UNKNOWN",le="16384"} 1 caddy_http_request_size_bytes_bucket{code="200",handler="empty",method="GET",server="UNKNOWN",le="65536"} 1 caddy_http_request_size_bytes_bucket{code="200",handler="empty",method="GET",server="UNKNOWN",le="262144"} 1 caddy_http_request_size_bytes_bucket{code="200",handler="empty",method="GET",server="UNKNOWN",le="1.048576e+06"} 1 caddy_http_request_size_bytes_bucket{code="200",handler="empty",method="GET",server="UNKNOWN",le="4.194304e+06"} 1 caddy_http_request_size_bytes_bucket{code="200",handler="empty",method="GET",server="UNKNOWN",le="+Inf"} 1 caddy_http_request_size_bytes_sum{code="200",handler="empty",method="GET",server="UNKNOWN"} 23 caddy_http_request_size_bytes_count{code="200",handler="empty",method="GET",server="UNKNOWN"} 1 caddy_http_request_size_bytes_bucket{code="429",handler="foo",method="GET",server="UNKNOWN",le="256"} 1 caddy_http_request_size_bytes_bucket{code="429",handler="foo",method="GET",server="UNKNOWN",le="1024"} 1 caddy_http_request_size_bytes_bucket{code="429",handler="foo",method="GET",server="UNKNOWN",le="4096"} 1 caddy_http_request_size_bytes_bucket{code="429",handler="foo",method="GET",server="UNKNOWN",le="16384"} 1 caddy_http_request_size_bytes_bucket{code="429",handler="foo",method="GET",server="UNKNOWN",le="65536"} 1 caddy_http_request_size_bytes_bucket{code="429",handler="foo",method="GET",server="UNKNOWN",le="262144"} 1 caddy_http_request_size_bytes_bucket{code="429",handler="foo",method="GET",server="UNKNOWN",le="1.048576e+06"} 1 caddy_http_request_size_bytes_bucket{code="429",handler="foo",method="GET",server="UNKNOWN",le="4.194304e+06"} 1 caddy_http_request_size_bytes_bucket{code="429",handler="foo",method="GET",server="UNKNOWN",le="+Inf"} 1 caddy_http_request_size_bytes_sum{code="429",handler="foo",method="GET",server="UNKNOWN"} 23 caddy_http_request_size_bytes_count{code="429",handler="foo",method="GET",server="UNKNOWN"} 1 # HELP caddy_http_response_size_bytes Size of the returned response. # TYPE caddy_http_response_size_bytes histogram caddy_http_response_size_bytes_bucket{code="200",handler="bar",method="GET",server="UNKNOWN",le="256"} 1 caddy_http_response_size_bytes_bucket{code="200",handler="bar",method="GET",server="UNKNOWN",le="1024"} 1 caddy_http_response_size_bytes_bucket{code="200",handler="bar",method="GET",server="UNKNOWN",le="4096"} 1 caddy_http_response_size_bytes_bucket{code="200",handler="bar",method="GET",server="UNKNOWN",le="16384"} 1 caddy_http_response_size_bytes_bucket{code="200",handler="bar",method="GET",server="UNKNOWN",le="65536"} 1 caddy_http_response_size_bytes_bucket{code="200",handler="bar",method="GET",server="UNKNOWN",le="262144"} 1 caddy_http_response_size_bytes_bucket{code="200",handler="bar",method="GET",server="UNKNOWN",le="1.048576e+06"} 1 caddy_http_response_size_bytes_bucket{code="200",handler="bar",method="GET",server="UNKNOWN",le="4.194304e+06"} 1 caddy_http_response_size_bytes_bucket{code="200",handler="bar",method="GET",server="UNKNOWN",le="+Inf"} 1 caddy_http_response_size_bytes_sum{code="200",handler="bar",method="GET",server="UNKNOWN"} 12 caddy_http_response_size_bytes_count{code="200",handler="bar",method="GET",server="UNKNOWN"} 1 caddy_http_response_size_bytes_bucket{code="200",handler="empty",method="GET",server="UNKNOWN",le="256"} 1 caddy_http_response_size_bytes_bucket{code="200",handler="empty",method="GET",server="UNKNOWN",le="1024"} 1 caddy_http_response_size_bytes_bucket{code="200",handler="empty",method="GET",server="UNKNOWN",le="4096"} 1 caddy_http_response_size_bytes_bucket{code="200",handler="empty",method="GET",server="UNKNOWN",le="16384"} 1 caddy_http_response_size_bytes_bucket{code="200",handler="empty",method="GET",server="UNKNOWN",le="65536"} 1 caddy_http_response_size_bytes_bucket{code="200",handler="empty",method="GET",server="UNKNOWN",le="262144"} 1 caddy_http_response_size_bytes_bucket{code="200",handler="empty",method="GET",server="UNKNOWN",le="1.048576e+06"} 1 caddy_http_response_size_bytes_bucket{code="200",handler="empty",method="GET",server="UNKNOWN",le="4.194304e+06"} 1 caddy_http_response_size_bytes_bucket{code="200",handler="empty",method="GET",server="UNKNOWN",le="+Inf"} 1 caddy_http_response_size_bytes_sum{code="200",handler="empty",method="GET",server="UNKNOWN"} 0 caddy_http_response_size_bytes_count{code="200",handler="empty",method="GET",server="UNKNOWN"} 1 caddy_http_response_size_bytes_bucket{code="429",handler="foo",method="GET",server="UNKNOWN",le="256"} 1 caddy_http_response_size_bytes_bucket{code="429",handler="foo",method="GET",server="UNKNOWN",le="1024"} 1 caddy_http_response_size_bytes_bucket{code="429",handler="foo",method="GET",server="UNKNOWN",le="4096"} 1 caddy_http_response_size_bytes_bucket{code="429",handler="foo",method="GET",server="UNKNOWN",le="16384"} 1 caddy_http_response_size_bytes_bucket{code="429",handler="foo",method="GET",server="UNKNOWN",le="65536"} 1 caddy_http_response_size_bytes_bucket{code="429",handler="foo",method="GET",server="UNKNOWN",le="262144"} 1 caddy_http_response_size_bytes_bucket{code="429",handler="foo",method="GET",server="UNKNOWN",le="1.048576e+06"} 1 caddy_http_response_size_bytes_bucket{code="429",handler="foo",method="GET",server="UNKNOWN",le="4.194304e+06"} 1 caddy_http_response_size_bytes_bucket{code="429",handler="foo",method="GET",server="UNKNOWN",le="+Inf"} 1 caddy_http_response_size_bytes_sum{code="429",handler="foo",method="GET",server="UNKNOWN"} 0 caddy_http_response_size_bytes_count{code="429",handler="foo",method="GET",server="UNKNOWN"} 1 # HELP caddy_http_request_errors_total Number of requests resulting in middleware errors. # TYPE caddy_http_request_errors_total counter caddy_http_request_errors_total{handler="bar",server="UNKNOWN"} 1 caddy_http_request_errors_total{handler="foo",server="UNKNOWN"} 1 ` if err := testutil.GatherAndCompare(ctx.GetMetricsRegistry(), strings.NewReader(expected), "caddy_http_request_size_bytes", "caddy_http_response_size_bytes", // caddy_http_request_duration_seconds_sum will vary based on how long the test took to run, // so we check just the _bucket and _count metrics "caddy_http_request_duration_seconds_bucket", "caddy_http_request_duration_seconds_count", "caddy_http_request_errors_total", ); err != nil { t.Errorf("received unexpected error: %s", err) } } func TestMetricsInstrumentedHandlerPerHost(t *testing.T) { ctx, _ := caddy.NewContext(caddy.Context{Context: context.Background()}) metrics := &Metrics{ PerHost: true, AllowCatchAllHosts: true, // Allow all hosts for testing init: sync.Once{}, httpMetrics: &httpMetrics{}, allowedHosts: make(map[string]struct{}), } handlerErr := errors.New("oh noes") response := []byte("hello world!") h := HandlerFunc(func(w http.ResponseWriter, r *http.Request) error { if actual := testutil.ToFloat64(metrics.httpMetrics.requestInFlight); actual != 1.0 { t.Errorf("Not same: expected %#v, but got %#v", 1.0, actual) } if handlerErr == nil { w.Write(response) } return handlerErr }) mh := middlewareHandlerFunc(func(w http.ResponseWriter, r *http.Request, h Handler) error { return h.ServeHTTP(w, r) }) ih := newMetricsInstrumentedHandler(ctx, "bar", mh, metrics) r := httptest.NewRequest("GET", "/", nil) w := httptest.NewRecorder() if actual := ih.ServeHTTP(w, r, h); actual != handlerErr { t.Errorf("Not same: expected %#v, but got %#v", handlerErr, actual) } if actual := testutil.ToFloat64(metrics.httpMetrics.requestInFlight); actual != 0.0 { t.Errorf("Not same: expected %#v, but got %#v", 0.0, actual) } handlerErr = nil if err := ih.ServeHTTP(w, r, h); err != nil { t.Errorf("Received unexpected error: %v", err) } // an empty handler - no errors, no header written mh = middlewareHandlerFunc(func(w http.ResponseWriter, r *http.Request, h Handler) error { return nil }) ih = newMetricsInstrumentedHandler(ctx, "empty", mh, metrics) r = httptest.NewRequest("GET", "/", nil) w = httptest.NewRecorder() if err := ih.ServeHTTP(w, r, h); err != nil { t.Errorf("Received unexpected error: %v", err) } if actual := w.Result().StatusCode; actual != 200 { t.Errorf("Not same: expected status code %#v, but got %#v", 200, actual) } if actual := w.Result().Header; len(actual) != 0 { t.Errorf("Not empty: expected headers to be empty, but got %#v", actual) } // handler returning an error with an HTTP status mh = middlewareHandlerFunc(func(w http.ResponseWriter, r *http.Request, h Handler) error { return Error(http.StatusTooManyRequests, nil) }) ih = newMetricsInstrumentedHandler(ctx, "foo", mh, metrics) r = httptest.NewRequest("GET", "/", nil) w = httptest.NewRecorder() if err := ih.ServeHTTP(w, r, nil); err == nil { t.Errorf("expected error to be propagated") } expected := ` # HELP caddy_http_request_duration_seconds Histogram of round-trip request durations. # TYPE caddy_http_request_duration_seconds histogram caddy_http_request_duration_seconds_bucket{code="429",handler="foo",host="example.com",method="GET",server="UNKNOWN",le="0.005"} 1 caddy_http_request_duration_seconds_bucket{code="429",handler="foo",host="example.com",method="GET",server="UNKNOWN",le="0.01"} 1 caddy_http_request_duration_seconds_bucket{code="429",handler="foo",host="example.com",method="GET",server="UNKNOWN",le="0.025"} 1 caddy_http_request_duration_seconds_bucket{code="429",handler="foo",host="example.com",method="GET",server="UNKNOWN",le="0.05"} 1 caddy_http_request_duration_seconds_bucket{code="429",handler="foo",host="example.com",method="GET",server="UNKNOWN",le="0.1"} 1 caddy_http_request_duration_seconds_bucket{code="429",handler="foo",host="example.com",method="GET",server="UNKNOWN",le="0.25"} 1 caddy_http_request_duration_seconds_bucket{code="429",handler="foo",host="example.com",method="GET",server="UNKNOWN",le="0.5"} 1 caddy_http_request_duration_seconds_bucket{code="429",handler="foo",host="example.com",method="GET",server="UNKNOWN",le="1"} 1 caddy_http_request_duration_seconds_bucket{code="429",handler="foo",host="example.com",method="GET",server="UNKNOWN",le="2.5"} 1 caddy_http_request_duration_seconds_bucket{code="429",handler="foo",host="example.com",method="GET",server="UNKNOWN",le="5"} 1 caddy_http_request_duration_seconds_bucket{code="429",handler="foo",host="example.com",method="GET",server="UNKNOWN",le="10"} 1 caddy_http_request_duration_seconds_bucket{code="429",handler="foo",host="example.com",method="GET",server="UNKNOWN",le="+Inf"} 1 caddy_http_request_duration_seconds_count{code="429",handler="foo",host="example.com",method="GET",server="UNKNOWN"} 1 # HELP caddy_http_request_size_bytes Total size of the request. Includes body # TYPE caddy_http_request_size_bytes histogram caddy_http_request_size_bytes_bucket{code="200",handler="bar",host="example.com",method="GET",server="UNKNOWN",le="256"} 1 caddy_http_request_size_bytes_bucket{code="200",handler="bar",host="example.com",method="GET",server="UNKNOWN",le="1024"} 1 caddy_http_request_size_bytes_bucket{code="200",handler="bar",host="example.com",method="GET",server="UNKNOWN",le="4096"} 1 caddy_http_request_size_bytes_bucket{code="200",handler="bar",host="example.com",method="GET",server="UNKNOWN",le="16384"} 1 caddy_http_request_size_bytes_bucket{code="200",handler="bar",host="example.com",method="GET",server="UNKNOWN",le="65536"} 1 caddy_http_request_size_bytes_bucket{code="200",handler="bar",host="example.com",method="GET",server="UNKNOWN",le="262144"} 1 caddy_http_request_size_bytes_bucket{code="200",handler="bar",host="example.com",method="GET",server="UNKNOWN",le="1.048576e+06"} 1 caddy_http_request_size_bytes_bucket{code="200",handler="bar",host="example.com",method="GET",server="UNKNOWN",le="4.194304e+06"} 1 caddy_http_request_size_bytes_bucket{code="200",handler="bar",host="example.com",method="GET",server="UNKNOWN",le="+Inf"} 1 caddy_http_request_size_bytes_sum{code="200",handler="bar",host="example.com",method="GET",server="UNKNOWN"} 23 caddy_http_request_size_bytes_count{code="200",handler="bar",host="example.com",method="GET",server="UNKNOWN"} 1 caddy_http_request_size_bytes_bucket{code="200",handler="empty",host="example.com",method="GET",server="UNKNOWN",le="256"} 1 caddy_http_request_size_bytes_bucket{code="200",handler="empty",host="example.com",method="GET",server="UNKNOWN",le="1024"} 1 caddy_http_request_size_bytes_bucket{code="200",handler="empty",host="example.com",method="GET",server="UNKNOWN",le="4096"} 1 caddy_http_request_size_bytes_bucket{code="200",handler="empty",host="example.com",method="GET",server="UNKNOWN",le="16384"} 1 caddy_http_request_size_bytes_bucket{code="200",handler="empty",host="example.com",method="GET",server="UNKNOWN",le="65536"} 1 caddy_http_request_size_bytes_bucket{code="200",handler="empty",host="example.com",method="GET",server="UNKNOWN",le="262144"} 1 caddy_http_request_size_bytes_bucket{code="200",handler="empty",host="example.com",method="GET",server="UNKNOWN",le="1.048576e+06"} 1 caddy_http_request_size_bytes_bucket{code="200",handler="empty",host="example.com",method="GET",server="UNKNOWN",le="4.194304e+06"} 1 caddy_http_request_size_bytes_bucket{code="200",handler="empty",host="example.com",method="GET",server="UNKNOWN",le="+Inf"} 1 caddy_http_request_size_bytes_sum{code="200",handler="empty",host="example.com",method="GET",server="UNKNOWN"} 23 caddy_http_request_size_bytes_count{code="200",handler="empty",host="example.com",method="GET",server="UNKNOWN"} 1 caddy_http_request_size_bytes_bucket{code="429",handler="foo",host="example.com",method="GET",server="UNKNOWN",le="256"} 1 caddy_http_request_size_bytes_bucket{code="429",handler="foo",host="example.com",method="GET",server="UNKNOWN",le="1024"} 1 caddy_http_request_size_bytes_bucket{code="429",handler="foo",host="example.com",method="GET",server="UNKNOWN",le="4096"} 1 caddy_http_request_size_bytes_bucket{code="429",handler="foo",host="example.com",method="GET",server="UNKNOWN",le="16384"} 1 caddy_http_request_size_bytes_bucket{code="429",handler="foo",host="example.com",method="GET",server="UNKNOWN",le="65536"} 1 caddy_http_request_size_bytes_bucket{code="429",handler="foo",host="example.com",method="GET",server="UNKNOWN",le="262144"} 1 caddy_http_request_size_bytes_bucket{code="429",handler="foo",host="example.com",method="GET",server="UNKNOWN",le="1.048576e+06"} 1 caddy_http_request_size_bytes_bucket{code="429",handler="foo",host="example.com",method="GET",server="UNKNOWN",le="4.194304e+06"} 1 caddy_http_request_size_bytes_bucket{code="429",handler="foo",host="example.com",method="GET",server="UNKNOWN",le="+Inf"} 1 caddy_http_request_size_bytes_sum{code="429",handler="foo",host="example.com",method="GET",server="UNKNOWN"} 23 caddy_http_request_size_bytes_count{code="429",handler="foo",host="example.com",method="GET",server="UNKNOWN"} 1 # HELP caddy_http_response_size_bytes Size of the returned response. # TYPE caddy_http_response_size_bytes histogram caddy_http_response_size_bytes_bucket{code="200",handler="bar",host="example.com",method="GET",server="UNKNOWN",le="256"} 1 caddy_http_response_size_bytes_bucket{code="200",handler="bar",host="example.com",method="GET",server="UNKNOWN",le="1024"} 1 caddy_http_response_size_bytes_bucket{code="200",handler="bar",host="example.com",method="GET",server="UNKNOWN",le="4096"} 1 caddy_http_response_size_bytes_bucket{code="200",handler="bar",host="example.com",method="GET",server="UNKNOWN",le="16384"} 1 caddy_http_response_size_bytes_bucket{code="200",handler="bar",host="example.com",method="GET",server="UNKNOWN",le="65536"} 1 caddy_http_response_size_bytes_bucket{code="200",handler="bar",host="example.com",method="GET",server="UNKNOWN",le="262144"} 1 caddy_http_response_size_bytes_bucket{code="200",handler="bar",host="example.com",method="GET",server="UNKNOWN",le="1.048576e+06"} 1 caddy_http_response_size_bytes_bucket{code="200",handler="bar",host="example.com",method="GET",server="UNKNOWN",le="4.194304e+06"} 1 caddy_http_response_size_bytes_bucket{code="200",handler="bar",host="example.com",method="GET",server="UNKNOWN",le="+Inf"} 1 caddy_http_response_size_bytes_sum{code="200",handler="bar",host="example.com",method="GET",server="UNKNOWN"} 12 caddy_http_response_size_bytes_count{code="200",handler="bar",host="example.com",method="GET",server="UNKNOWN"} 1 caddy_http_response_size_bytes_bucket{code="200",handler="empty",host="example.com",method="GET",server="UNKNOWN",le="256"} 1 caddy_http_response_size_bytes_bucket{code="200",handler="empty",host="example.com",method="GET",server="UNKNOWN",le="1024"} 1 caddy_http_response_size_bytes_bucket{code="200",handler="empty",host="example.com",method="GET",server="UNKNOWN",le="4096"} 1 caddy_http_response_size_bytes_bucket{code="200",handler="empty",host="example.com",method="GET",server="UNKNOWN",le="16384"} 1 caddy_http_response_size_bytes_bucket{code="200",handler="empty",host="example.com",method="GET",server="UNKNOWN",le="65536"} 1 caddy_http_response_size_bytes_bucket{code="200",handler="empty",host="example.com",method="GET",server="UNKNOWN",le="262144"} 1 caddy_http_response_size_bytes_bucket{code="200",handler="empty",host="example.com",method="GET",server="UNKNOWN",le="1.048576e+06"} 1 caddy_http_response_size_bytes_bucket{code="200",handler="empty",host="example.com",method="GET",server="UNKNOWN",le="4.194304e+06"} 1 caddy_http_response_size_bytes_bucket{code="200",handler="empty",host="example.com",method="GET",server="UNKNOWN",le="+Inf"} 1 caddy_http_response_size_bytes_sum{code="200",handler="empty",host="example.com",method="GET",server="UNKNOWN"} 0 caddy_http_response_size_bytes_count{code="200",handler="empty",host="example.com",method="GET",server="UNKNOWN"} 1 caddy_http_response_size_bytes_bucket{code="429",handler="foo",host="example.com",method="GET",server="UNKNOWN",le="256"} 1 caddy_http_response_size_bytes_bucket{code="429",handler="foo",host="example.com",method="GET",server="UNKNOWN",le="1024"} 1 caddy_http_response_size_bytes_bucket{code="429",handler="foo",host="example.com",method="GET",server="UNKNOWN",le="4096"} 1 caddy_http_response_size_bytes_bucket{code="429",handler="foo",host="example.com",method="GET",server="UNKNOWN",le="16384"} 1 caddy_http_response_size_bytes_bucket{code="429",handler="foo",host="example.com",method="GET",server="UNKNOWN",le="65536"} 1 caddy_http_response_size_bytes_bucket{code="429",handler="foo",host="example.com",method="GET",server="UNKNOWN",le="262144"} 1 caddy_http_response_size_bytes_bucket{code="429",handler="foo",host="example.com",method="GET",server="UNKNOWN",le="1.048576e+06"} 1 caddy_http_response_size_bytes_bucket{code="429",handler="foo",host="example.com",method="GET",server="UNKNOWN",le="4.194304e+06"} 1 caddy_http_response_size_bytes_bucket{code="429",handler="foo",host="example.com",method="GET",server="UNKNOWN",le="+Inf"} 1 caddy_http_response_size_bytes_sum{code="429",handler="foo",host="example.com",method="GET",server="UNKNOWN"} 0 caddy_http_response_size_bytes_count{code="429",handler="foo",host="example.com",method="GET",server="UNKNOWN"} 1 # HELP caddy_http_request_errors_total Number of requests resulting in middleware errors. # TYPE caddy_http_request_errors_total counter caddy_http_request_errors_total{handler="bar",host="example.com",server="UNKNOWN"} 1 caddy_http_request_errors_total{handler="foo",host="example.com",server="UNKNOWN"} 1 ` if err := testutil.GatherAndCompare(ctx.GetMetricsRegistry(), strings.NewReader(expected), "caddy_http_request_size_bytes", "caddy_http_response_size_bytes", // caddy_http_request_duration_seconds_sum will vary based on how long the test took to run, // so we check just the _bucket and _count metrics "caddy_http_request_duration_seconds_bucket", "caddy_http_request_duration_seconds_count", "caddy_http_request_errors_total", ); err != nil { t.Errorf("received unexpected error: %s", err) } } func TestMetricsCardinalityProtection(t *testing.T) { ctx, _ := caddy.NewContext(caddy.Context{Context: context.Background()}) // Test 1: Without AllowCatchAllHosts, arbitrary hosts should be mapped to "_other" metrics := &Metrics{ PerHost: true, AllowCatchAllHosts: false, // Default - should map unknown hosts to "_other" init: sync.Once{}, httpMetrics: &httpMetrics{}, allowedHosts: make(map[string]struct{}), } // Add one allowed host metrics.allowedHosts["allowed.com"] = struct{}{} mh := middlewareHandlerFunc(func(w http.ResponseWriter, r *http.Request, h Handler) error { w.Write([]byte("hello")) return nil }) ih := newMetricsInstrumentedHandler(ctx, "test", mh, metrics) // Test request to allowed host r1 := httptest.NewRequest("GET", "http://allowed.com/", nil) r1.Host = "allowed.com" w1 := httptest.NewRecorder() ih.ServeHTTP(w1, r1, HandlerFunc(func(w http.ResponseWriter, r *http.Request) error { return nil })) // Test request to unknown host (should be mapped to "_other") r2 := httptest.NewRequest("GET", "http://attacker.com/", nil) r2.Host = "attacker.com" w2 := httptest.NewRecorder() ih.ServeHTTP(w2, r2, HandlerFunc(func(w http.ResponseWriter, r *http.Request) error { return nil })) // Test request to another unknown host (should also be mapped to "_other") r3 := httptest.NewRequest("GET", "http://evil.com/", nil) r3.Host = "evil.com" w3 := httptest.NewRecorder() ih.ServeHTTP(w3, r3, HandlerFunc(func(w http.ResponseWriter, r *http.Request) error { return nil })) // Check that metrics contain: // - One entry for "allowed.com" // - One entry for "_other" (aggregating attacker.com and evil.com) expected := ` # HELP caddy_http_requests_total Counter of HTTP(S) requests made. # TYPE caddy_http_requests_total counter caddy_http_requests_total{handler="test",host="_other",server="UNKNOWN"} 2 caddy_http_requests_total{handler="test",host="allowed.com",server="UNKNOWN"} 1 ` if err := testutil.GatherAndCompare(ctx.GetMetricsRegistry(), strings.NewReader(expected), "caddy_http_requests_total", ); err != nil { t.Errorf("Cardinality protection test failed: %s", err) } } func TestMetricsHTTPSCatchAll(t *testing.T) { ctx, _ := caddy.NewContext(caddy.Context{Context: context.Background()}) // Test that HTTPS requests allow catch-all even when AllowCatchAllHosts is false metrics := &Metrics{ PerHost: true, AllowCatchAllHosts: false, hasHTTPSServer: true, // Simulate having HTTPS servers init: sync.Once{}, httpMetrics: &httpMetrics{}, allowedHosts: make(map[string]struct{}), // Empty - no explicitly allowed hosts } mh := middlewareHandlerFunc(func(w http.ResponseWriter, r *http.Request, h Handler) error { w.Write([]byte("hello")) return nil }) ih := newMetricsInstrumentedHandler(ctx, "test", mh, metrics) // Test HTTPS request (should be allowed even though not in allowedHosts) r1 := httptest.NewRequest("GET", "https://unknown.com/", nil) r1.Host = "unknown.com" r1.TLS = &tls.ConnectionState{} // Mark as TLS/HTTPS w1 := httptest.NewRecorder() ih.ServeHTTP(w1, r1, HandlerFunc(func(w http.ResponseWriter, r *http.Request) error { return nil })) // Test HTTP request (should be mapped to "_other") r2 := httptest.NewRequest("GET", "http://unknown.com/", nil) r2.Host = "unknown.com" // No TLS field = HTTP request w2 := httptest.NewRecorder() ih.ServeHTTP(w2, r2, HandlerFunc(func(w http.ResponseWriter, r *http.Request) error { return nil })) // Check that HTTPS request gets real host, HTTP gets "_other" expected := ` # HELP caddy_http_requests_total Counter of HTTP(S) requests made. # TYPE caddy_http_requests_total counter caddy_http_requests_total{handler="test",host="_other",server="UNKNOWN"} 1 caddy_http_requests_total{handler="test",host="unknown.com",server="UNKNOWN"} 1 ` if err := testutil.GatherAndCompare(ctx.GetMetricsRegistry(), strings.NewReader(expected), "caddy_http_requests_total", ); err != nil { t.Errorf("HTTPS catch-all test failed: %s", err) } } type middlewareHandlerFunc func(http.ResponseWriter, *http.Request, Handler) error func (f middlewareHandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request, h Handler) error { return f(w, r, h) }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/autohttps.go
modules/caddyhttp/autohttps.go
// Copyright 2015 Matthew Holt and The Caddy 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 caddyhttp import ( "fmt" "net/http" "slices" "strconv" "strings" "github.com/caddyserver/certmagic" "go.uber.org/zap" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/internal" "github.com/caddyserver/caddy/v2/modules/caddytls" ) // AutoHTTPSConfig is used to disable automatic HTTPS // or certain aspects of it for a specific server. // HTTPS is enabled automatically and by default when // qualifying hostnames are available from the config. type AutoHTTPSConfig struct { // If true, automatic HTTPS will be entirely disabled, // including certificate management and redirects. Disabled bool `json:"disable,omitempty"` // If true, only automatic HTTP->HTTPS redirects will // be disabled, but other auto-HTTPS features will // remain enabled. DisableRedir bool `json:"disable_redirects,omitempty"` // If true, automatic certificate management will be // disabled, but other auto-HTTPS features will // remain enabled. DisableCerts bool `json:"disable_certificates,omitempty"` // Hosts/domain names listed here will not be included // in automatic HTTPS (they will not have certificates // loaded nor redirects applied). Skip []string `json:"skip,omitempty"` // Hosts/domain names listed here will still be enabled // for automatic HTTPS (unless in the Skip list), except // that certificates will not be provisioned and managed // for these names. SkipCerts []string `json:"skip_certificates,omitempty"` // By default, automatic HTTPS will obtain and renew // certificates for qualifying hostnames. However, if // a certificate with a matching SAN is already loaded // into the cache, certificate management will not be // enabled. To force automated certificate management // regardless of loaded certificates, set this to true. IgnoreLoadedCerts bool `json:"ignore_loaded_certificates,omitempty"` } // automaticHTTPSPhase1 provisions all route matchers, determines // which domain names found in the routes qualify for automatic // HTTPS, and sets up HTTP->HTTPS redirects. This phase must occur // at the beginning of provisioning, because it may add routes and // even servers to the app, which still need to be set up with the // rest of them during provisioning. func (app *App) automaticHTTPSPhase1(ctx caddy.Context, repl *caddy.Replacer) error { logger := app.logger.Named("auto_https") // this map acts as a set to store the domain names // for which we will manage certificates automatically uniqueDomainsForCerts := make(map[string]struct{}) // this maps domain names for automatic HTTP->HTTPS // redirects to their destination server addresses // (there might be more than 1 if bind is used; see // https://github.com/caddyserver/caddy/issues/3443) redirDomains := make(map[string][]caddy.NetworkAddress) // the log configuration for an HTTPS enabled server var logCfg *ServerLogConfig for srvName, srv := range app.Servers { // as a prerequisite, provision route matchers; this is // required for all routes on all servers, and must be // done before we attempt to do phase 1 of auto HTTPS, // since we have to access the decoded host matchers the // handlers will be provisioned later if srv.Routes != nil { err := srv.Routes.ProvisionMatchers(ctx) if err != nil { return fmt.Errorf("server %s: setting up route matchers: %v", srvName, err) } } // prepare for automatic HTTPS if srv.AutoHTTPS == nil { srv.AutoHTTPS = new(AutoHTTPSConfig) } if srv.AutoHTTPS.Disabled { logger.Info("automatic HTTPS is completely disabled for server", zap.String("server_name", srvName)) continue } // skip if all listeners use the HTTP port if !srv.listenersUseAnyPortOtherThan(app.httpPort()) { logger.Warn("server is listening only on the HTTP port, so no automatic HTTPS will be applied to this server", zap.String("server_name", srvName), zap.Int("http_port", app.httpPort()), ) srv.AutoHTTPS.Disabled = true continue } // if all listeners are on the HTTPS port, make sure // there is at least one TLS connection policy; it // should be obvious that they want to use TLS without // needing to specify one empty policy to enable it if srv.TLSConnPolicies == nil && !srv.listenersUseAnyPortOtherThan(app.httpsPort()) { logger.Info("server is listening only on the HTTPS port but has no TLS connection policies; adding one to enable TLS", zap.String("server_name", srvName), zap.Int("https_port", app.httpsPort()), ) srv.TLSConnPolicies = caddytls.ConnectionPolicies{new(caddytls.ConnectionPolicy)} } // find all qualifying domain names (deduplicated) in this server // (this is where we need the provisioned, decoded request matchers) serverDomainSet := make(map[string]struct{}) for routeIdx, route := range srv.Routes { for matcherSetIdx, matcherSet := range route.MatcherSets { for matcherIdx, m := range matcherSet { if hm, ok := m.(*MatchHost); ok { for hostMatcherIdx, d := range *hm { var err error d, err = repl.ReplaceOrErr(d, true, false) if err != nil { return fmt.Errorf("%s: route %d, matcher set %d, matcher %d, host matcher %d: %v", srvName, routeIdx, matcherSetIdx, matcherIdx, hostMatcherIdx, err) } if !slices.Contains(srv.AutoHTTPS.Skip, d) { serverDomainSet[d] = struct{}{} } } } } } } // build the list of domains that could be used with ECH (if enabled) // so the TLS app can know to publish ECH configs for them echDomains := make([]string, 0, len(serverDomainSet)) for d := range serverDomainSet { echDomains = append(echDomains, d) } app.tlsApp.RegisterServerNames(echDomains) // nothing more to do here if there are no domains that qualify for // automatic HTTPS and there are no explicit TLS connection policies: // if there is at least one domain but no TLS conn policy (F&&T), we'll // add one below; if there are no domains but at least one TLS conn // policy (meaning TLS is enabled) (T&&F), it could be a catch-all with // on-demand TLS -- and in that case we would still need HTTP->HTTPS // redirects, which we set up below; hence these two conditions if len(serverDomainSet) == 0 && len(srv.TLSConnPolicies) == 0 { continue } // clone the logger so we can apply it to the HTTP server // (not sure if necessary to clone it; but probably safer) // (we choose one log cfg arbitrarily; not sure which is best) if srv.Logs != nil { logCfg = srv.Logs.clone() } // for all the hostnames we found, filter them so we have // a deduplicated list of names for which to obtain certs // (only if cert management not disabled for this server) if srv.AutoHTTPS.DisableCerts { logger.Warn("skipping automated certificate management for server because it is disabled", zap.String("server_name", srvName)) } else { for d := range serverDomainSet { if certmagic.SubjectQualifiesForCert(d) && !slices.Contains(srv.AutoHTTPS.SkipCerts, d) { // if a certificate for this name is already loaded, // don't obtain another one for it, unless we are // supposed to ignore loaded certificates if !srv.AutoHTTPS.IgnoreLoadedCerts && app.tlsApp.HasCertificateForSubject(d) { logger.Info("skipping automatic certificate management because one or more matching certificates are already loaded", zap.String("domain", d), zap.String("server_name", srvName), ) continue } // most clients don't accept wildcards like *.tld... we // can handle that, but as a courtesy, warn the user if strings.Contains(d, "*") && strings.Count(strings.Trim(d, "."), ".") == 1 { logger.Warn("most clients do not trust second-level wildcard certificates (*.tld)", zap.String("domain", d)) } uniqueDomainsForCerts[d] = struct{}{} } } } // tell the server to use TLS if it is not already doing so if srv.TLSConnPolicies == nil { srv.TLSConnPolicies = caddytls.ConnectionPolicies{new(caddytls.ConnectionPolicy)} } // nothing left to do if auto redirects are disabled if srv.AutoHTTPS.DisableRedir { logger.Info("automatic HTTP->HTTPS redirects are disabled", zap.String("server_name", srvName)) continue } logger.Info("enabling automatic HTTP->HTTPS redirects", zap.String("server_name", srvName)) // create HTTP->HTTPS redirects for _, listenAddr := range srv.Listen { // figure out the address we will redirect to... addr, err := caddy.ParseNetworkAddress(listenAddr) if err != nil { msg := "%s: invalid listener address: %v" if strings.Count(listenAddr, ":") > 1 { msg = msg + ", there are too many colons, so the port is ambiguous. Did you mean to wrap the IPv6 address with [] brackets?" } return fmt.Errorf(msg, srvName, listenAddr) } // this address might not have a hostname, i.e. might be a // catch-all address for a particular port; we need to keep // track if it is, so we can set up redirects for it anyway // (e.g. the user might have enabled on-demand TLS); we use // an empty string to indicate a catch-all, which we have to // treat special later if len(serverDomainSet) == 0 { redirDomains[""] = append(redirDomains[""], addr) continue } // ...and associate it with each domain in this server for d := range serverDomainSet { // if this domain is used on more than one HTTPS-enabled // port, we'll have to choose one, so prefer the HTTPS port if _, ok := redirDomains[d]; !ok || addr.StartPort == uint(app.httpsPort()) { redirDomains[d] = append(redirDomains[d], addr) } } } } // if all servers have auto_https disabled and no domains need certs, // skip the rest of the TLS automation setup to avoid creating // unnecessary PKI infrastructure and automation policies allServersDisabled := true for _, srv := range app.Servers { if srv.AutoHTTPS == nil || !srv.AutoHTTPS.Disabled { allServersDisabled = false break } } if allServersDisabled && len(uniqueDomainsForCerts) == 0 { logger.Debug("all servers have automatic HTTPS disabled and no domains need certificates, skipping TLS automation setup") return nil } // we now have a list of all the unique names for which we need certs var internal, tailscale []string uniqueDomainsLoop: for d := range uniqueDomainsForCerts { // some names we've found might already have automation policies // explicitly specified for them; we should exclude those from // our hidden/implicit policy, since applying a name to more than // one automation policy would be confusing and an error if app.tlsApp.Automation != nil { for _, ap := range app.tlsApp.Automation.Policies { for _, apHost := range ap.Subjects() { if apHost == d { // if the automation policy has all internal subjects but no issuers, // it will default to CertMagic's issuers which are public CAs; use // our internal issuer instead if len(ap.Issuers) == 0 && ap.AllInternalSubjects() { iss := new(caddytls.InternalIssuer) if err := iss.Provision(ctx); err != nil { return err } ap.Issuers = append(ap.Issuers, iss) } continue uniqueDomainsLoop } } } } // if no automation policy exists for the name yet, we will associate it with an implicit one; // we handle tailscale domains specially, and we also separate out identifiers that need the // internal issuer (self-signed certs); certmagic does not consider public IP addresses to be // disqualified for public certs, because there are public CAs that will issue certs for IPs. // However, with auto-HTTPS, many times there is no issuer explicitly defined, and the default // issuers do not (currently, as of 2024) issue IP certificates; so assign all IP subjects to // the internal issuer when there are no explicit automation policies shouldUseInternal := func(ident string) bool { usingDefaultIssuersAndIsIP := certmagic.SubjectIsIP(ident) && (app.tlsApp == nil || app.tlsApp.Automation == nil || len(app.tlsApp.Automation.Policies) == 0) return !certmagic.SubjectQualifiesForPublicCert(d) || usingDefaultIssuersAndIsIP } if isTailscaleDomain(d) { tailscale = append(tailscale, d) delete(uniqueDomainsForCerts, d) // not managed by us; handled separately } else if shouldUseInternal(d) { internal = append(internal, d) } } // ensure there is an automation policy to handle these certs err := app.createAutomationPolicies(ctx, internal, tailscale) if err != nil { return err } // we need to reduce the mapping, i.e. group domains by address // since new routes are appended to servers by their address domainsByAddr := make(map[string][]string) for domain, addrs := range redirDomains { for _, addr := range addrs { addrStr := addr.String() domainsByAddr[addrStr] = append(domainsByAddr[addrStr], domain) } } // these keep track of the redirect server address(es) // and the routes for those servers which actually // respond with the redirects redirServerAddrs := make(map[string]struct{}) redirServers := make(map[string][]Route) var redirRoutes RouteList for addrStr, domains := range domainsByAddr { // build the matcher set for this redirect route; (note that we happen // to bypass Provision and Validate steps for these matcher modules) matcherSet := MatcherSet{MatchProtocol("http")} // match on known domain names, unless it's our special case of a // catch-all which is an empty string (common among catch-all sites // that enable on-demand TLS for yet-unknown domain names) if len(domains) != 1 || domains[0] != "" { matcherSet = append(matcherSet, MatchHost(domains)) } addr, err := caddy.ParseNetworkAddress(addrStr) if err != nil { return err } redirRoute := app.makeRedirRoute(addr.StartPort, matcherSet) // use the network/host information from the address, // but change the port to the HTTP port then rebuild redirAddr := addr redirAddr.StartPort = uint(app.httpPort()) redirAddr.EndPort = redirAddr.StartPort redirAddrStr := redirAddr.String() redirServers[redirAddrStr] = append(redirServers[redirAddrStr], redirRoute) } // on-demand TLS means that hostnames may be used which are not // explicitly defined in the config, and we still need to redirect // those; so we can append a single catch-all route (notice there // is no Host matcher) after the other redirect routes which will // allow us to handle unexpected/new hostnames... however, it's // not entirely clear what the redirect destination should be, // so I'm going to just hard-code the app's HTTPS port and call // it good for now... // TODO: This implies that all plaintext requests will be blindly // redirected to their HTTPS equivalent, even if this server // doesn't handle that hostname at all; I don't think this is a // bad thing, and it also obscures the actual hostnames that this // server is configured to match on, which may be desirable, but // it's not something that should be relied on. We can change this // if we want to. appendCatchAll := func(routes []Route) []Route { return append(routes, app.makeRedirRoute(uint(app.httpsPort()), MatcherSet{MatchProtocol("http")})) } redirServersLoop: for redirServerAddr, routes := range redirServers { // for each redirect listener, see if there's already a // server configured to listen on that exact address; if so, // insert the redirect route to the end of its route list // after any other routes with host matchers; otherwise, // we'll create a new server for all the listener addresses // that are unused and serve the remaining redirects from it for _, srv := range app.Servers { // only look at servers which listen on an address which // we want to add redirects to if !srv.hasListenerAddress(redirServerAddr) { continue } // find the index of the route after the last route with a host // matcher, then insert the redirects there, but before any // user-defined catch-all routes // see https://github.com/caddyserver/caddy/issues/3212 insertIndex := srv.findLastRouteWithHostMatcher() // add the redirects at the insert index, except for when // we have a catch-all for HTTPS, in which case the user's // defined catch-all should take precedence. See #4829 if len(uniqueDomainsForCerts) != 0 { srv.Routes = append(srv.Routes[:insertIndex], append(routes, srv.Routes[insertIndex:]...)...) } // append our catch-all route in case the user didn't define their own srv.Routes = appendCatchAll(srv.Routes) continue redirServersLoop } // no server with this listener address exists; // save this address and route for custom server redirServerAddrs[redirServerAddr] = struct{}{} redirRoutes = append(redirRoutes, routes...) } // if there are routes remaining which do not belong // in any existing server, make our own to serve the // rest of the redirects if len(redirServerAddrs) > 0 { redirServerAddrsList := make([]string, 0, len(redirServerAddrs)) for a := range redirServerAddrs { redirServerAddrsList = append(redirServerAddrsList, a) } app.Servers["remaining_auto_https_redirects"] = &Server{ Listen: redirServerAddrsList, Routes: appendCatchAll(redirRoutes), Logs: logCfg, } } // persist the domains/IPs we're managing certs for through provisioning/startup app.allCertDomains = uniqueDomainsForCerts logger.Debug("adjusted config", zap.Reflect("tls", app.tlsApp), zap.Reflect("http", app)) return nil } func (app *App) makeRedirRoute(redirToPort uint, matcherSet MatcherSet) Route { redirTo := "https://{http.request.host}" // since this is an external redirect, we should only append an explicit // port if we know it is not the officially standardized HTTPS port, and, // notably, also not the port that Caddy thinks is the HTTPS port (the // configurable HTTPSPort parameter) - we can't change the standard HTTPS // port externally, so that config parameter is for internal use only; // we also do not append the port if it happens to be the HTTP port as // well, obviously (for example, user defines the HTTP port explicitly // in the list of listen addresses for a server) if redirToPort != uint(app.httpPort()) && redirToPort != uint(app.httpsPort()) && redirToPort != DefaultHTTPPort && redirToPort != DefaultHTTPSPort { redirTo += ":" + strconv.Itoa(int(redirToPort)) } redirTo += "{http.request.uri}" return Route{ MatcherSets: []MatcherSet{matcherSet}, Handlers: []MiddlewareHandler{ StaticResponse{ StatusCode: WeakString(strconv.Itoa(http.StatusPermanentRedirect)), Headers: http.Header{ "Location": []string{redirTo}, }, Close: true, }, }, } } // createAutomationPolicies ensures that automated certificates for this // app are managed properly. This adds up to two automation policies: // one for the public names, and one for the internal names. If a catch-all // automation policy exists, it will be shallow-copied and used as the // base for the new ones (this is important for preserving behavior the // user intends to be "defaults"). func (app *App) createAutomationPolicies(ctx caddy.Context, internalNames, tailscaleNames []string) error { // before we begin, loop through the existing automation policies // and, for any ACMEIssuers we find, make sure they're filled in // with default values that might be specified in our HTTP app; also // look for a base (or "catch-all" / default) automation policy, // which we're going to essentially require, to make sure it has // those defaults, too var basePolicy *caddytls.AutomationPolicy var foundBasePolicy bool if app.tlsApp.Automation == nil { // we will expect this to not be nil from now on app.tlsApp.Automation = new(caddytls.AutomationConfig) } for _, ap := range app.tlsApp.Automation.Policies { // on-demand policies can have the tailscale manager added implicitly // if there's no explicit manager configured -- for convenience if ap.OnDemand && len(ap.Managers) == 0 { var ts caddytls.Tailscale if err := ts.Provision(ctx); err != nil { return err } ap.Managers = []certmagic.Manager{ts} // must reprovision the automation policy so that the underlying // CertMagic config knows about the updated Managers if err := ap.Provision(app.tlsApp); err != nil { return fmt.Errorf("re-provisioning automation policy: %v", err) } } // set up default issuer -- honestly, this is only // really necessary because the HTTP app is opinionated // and has settings which could be inferred as new // defaults for the ACMEIssuer in the TLS app (such as // what the HTTP and HTTPS ports are) if ap.Issuers == nil { var err error ap.Issuers, err = caddytls.DefaultIssuersProvisioned(ctx) if err != nil { return err } } for _, iss := range ap.Issuers { if acmeIssuer, ok := iss.(acmeCapable); ok { err := app.fillInACMEIssuer(acmeIssuer.GetACMEIssuer()) if err != nil { return err } } } // while we're here, is this the catch-all/base policy? if !foundBasePolicy && len(ap.SubjectsRaw) == 0 { basePolicy = ap foundBasePolicy = true } } if basePolicy == nil { // no base policy found; we will make one basePolicy = new(caddytls.AutomationPolicy) } // if the basePolicy has an existing ACMEIssuer (particularly to // include any type that embeds/wraps an ACMEIssuer), let's use it // (I guess we just use the first one?), otherwise we'll make one var baseACMEIssuer *caddytls.ACMEIssuer for _, iss := range basePolicy.Issuers { if acmeWrapper, ok := iss.(acmeCapable); ok { baseACMEIssuer = acmeWrapper.GetACMEIssuer() break } } if baseACMEIssuer == nil { // note that this happens if basePolicy.Issuers is empty // OR if it is not empty but does not have not an ACMEIssuer baseACMEIssuer = new(caddytls.ACMEIssuer) } // if there was a base policy to begin with, we already // filled in its issuer's defaults; if there wasn't, we // still need to do that if !foundBasePolicy { err := app.fillInACMEIssuer(baseACMEIssuer) if err != nil { return err } } // never overwrite any other issuer that might already be configured if basePolicy.Issuers == nil { var err error basePolicy.Issuers, err = caddytls.DefaultIssuersProvisioned(ctx) if err != nil { return err } for _, iss := range basePolicy.Issuers { if acmeIssuer, ok := iss.(acmeCapable); ok { err := app.fillInACMEIssuer(acmeIssuer.GetACMEIssuer()) if err != nil { return err } } } } if !foundBasePolicy { // there was no base policy to begin with, so add // our base/catch-all policy - this will serve the // public-looking names as well as any other names // that don't match any other policy err := app.tlsApp.AddAutomationPolicy(basePolicy) if err != nil { return err } } else { // a base policy already existed; we might have // changed it, so re-provision it err := basePolicy.Provision(app.tlsApp) if err != nil { return err } } // public names will be taken care of by the base (catch-all) // policy, which we've ensured exists if not already specified; // internal names, however, need to be handled by an internal // issuer, which we need to make a new policy for, scoped to // just those names (yes, this logic is a bit asymmetric, but // it works, because our assumed/natural default issuer is an // ACME issuer) if len(internalNames) > 0 { internalIssuer := new(caddytls.InternalIssuer) // shallow-copy the base policy; we want to inherit // from it, not replace it... this takes two lines to // overrule compiler optimizations policyCopy := *basePolicy newPolicy := &policyCopy // very important to provision the issuer, since we // are bypassing the JSON-unmarshaling step if err := internalIssuer.Provision(ctx); err != nil { return err } // this policy should apply only to the given names // and should use our issuer -- yes, this overrides // any issuer that may have been set in the base // policy, but we do this because these names do not // already have a policy associated with them, which // is easy to do; consider the case of a Caddyfile // that has only "localhost" as a name, but sets the // default/global ACME CA to the Let's Encrypt staging // endpoint... they probably don't intend to change the // fundamental set of names that setting applies to, // rather they just want to change the CA for the set // of names that would normally use the production API; // anyway, that gets into the weeds a bit... newPolicy.SubjectsRaw = internalNames newPolicy.Issuers = []certmagic.Issuer{internalIssuer} err := app.tlsApp.AddAutomationPolicy(newPolicy) if err != nil { return err } } // tailscale names go in their own automation policies because // they require on-demand TLS to be enabled, which we obviously // can't enable for everything if len(tailscaleNames) > 0 { policyCopy := *basePolicy newPolicy := &policyCopy var ts caddytls.Tailscale if err := ts.Provision(ctx); err != nil { return err } newPolicy.SubjectsRaw = tailscaleNames newPolicy.Issuers = nil newPolicy.Managers = append(newPolicy.Managers, ts) err := app.tlsApp.AddAutomationPolicy(newPolicy) if err != nil { return err } } // we just changed a lot of stuff, so double-check that it's all good err := app.tlsApp.Validate() if err != nil { return err } return nil } // fillInACMEIssuer fills in default values into acmeIssuer that // are defined in app; these values at time of writing are just // app.HTTPPort and app.HTTPSPort, which are used by ACMEIssuer. // Sure, we could just use the global/CertMagic defaults, but if // a user has configured those ports in the HTTP app, it makes // sense to use them in the TLS app too, even if they forgot (or // were too lazy, like me) to set it in each automation policy // that uses it -- this just makes things a little less tedious // for the user, so they don't have to repeat those ports in // potentially many places. This function never steps on existing // config values. If any changes are made, acmeIssuer is // reprovisioned. acmeIssuer must not be nil. func (app *App) fillInACMEIssuer(acmeIssuer *caddytls.ACMEIssuer) error { if app.HTTPPort > 0 || app.HTTPSPort > 0 { if acmeIssuer.Challenges == nil { acmeIssuer.Challenges = new(caddytls.ChallengesConfig) } } if app.HTTPPort > 0 { if acmeIssuer.Challenges.HTTP == nil { acmeIssuer.Challenges.HTTP = new(caddytls.HTTPChallengeConfig) } // don't overwrite existing explicit config if acmeIssuer.Challenges.HTTP.AlternatePort == 0 { acmeIssuer.Challenges.HTTP.AlternatePort = app.HTTPPort } } if app.HTTPSPort > 0 { if acmeIssuer.Challenges.TLSALPN == nil { acmeIssuer.Challenges.TLSALPN = new(caddytls.TLSALPNChallengeConfig) } // don't overwrite existing explicit config if acmeIssuer.Challenges.TLSALPN.AlternatePort == 0 { acmeIssuer.Challenges.TLSALPN.AlternatePort = app.HTTPSPort } } // we must provision all ACME issuers, even if nothing // was changed, because we don't know if they are new // and haven't been provisioned yet; if an ACME issuer // never gets provisioned, its Agree field stays false, // which leads to, um, problems later on return acmeIssuer.Provision(app.ctx) } // automaticHTTPSPhase2 begins certificate management for // all names in the qualifying domain set for each server. // This phase must occur after provisioning and at the end // of app start, after all the servers have been started. // Doing this last ensures that there won't be any race // for listeners on the HTTP or HTTPS ports when management // is async (if CertMagic's solvers bind to those ports // first, then our servers would fail to bind to them, // which would be bad, since CertMagic's bindings are // temporary and don't serve the user's sites!). func (app *App) automaticHTTPSPhase2() error { if len(app.allCertDomains) == 0 { return nil } app.logger.Info("enabling automatic TLS certificate management", zap.Strings("domains", internal.MaxSizeSubjectsListForLog(app.allCertDomains, 1000)), ) err := app.tlsApp.Manage(app.allCertDomains) if err != nil { return fmt.Errorf("managing certificates for %d domains: %s", len(app.allCertDomains), err) } app.allCertDomains = nil // no longer needed; allow GC to deallocate return nil } func isTailscaleDomain(name string) bool { return strings.HasSuffix(strings.ToLower(name), ".ts.net") } type acmeCapable interface{ GetACMEIssuer() *caddytls.ACMEIssuer }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/routes.go
modules/caddyhttp/routes.go
// Copyright 2015 Matthew Holt and The Caddy 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 caddyhttp import ( "encoding/json" "fmt" "net/http" "github.com/caddyserver/caddy/v2" ) // Route consists of a set of rules for matching HTTP requests, // a list of handlers to execute, and optional flow control // parameters which customize the handling of HTTP requests // in a highly flexible and performant manner. type Route struct { // Group is an optional name for a group to which this // route belongs. Grouping a route makes it mutually // exclusive with others in its group; if a route belongs // to a group, only the first matching route in that group // will be executed. Group string `json:"group,omitempty"` // The matcher sets which will be used to qualify this // route for a request (essentially the "if" statement // of this route). Each matcher set is OR'ed, but matchers // within a set are AND'ed together. MatcherSetsRaw RawMatcherSets `json:"match,omitempty" caddy:"namespace=http.matchers"` // The list of handlers for this route. Upon matching a request, they are chained // together in a middleware fashion: requests flow from the first handler to the last // (top of the list to the bottom), with the possibility that any handler could stop // the chain and/or return an error. Responses flow back through the chain (bottom of // the list to the top) as they are written out to the client. // // Not all handlers call the next handler in the chain. For example, the reverse_proxy // handler always sends a request upstream or returns an error. Thus, configuring // handlers after reverse_proxy in the same route is illogical, since they would never // be executed. You will want to put handlers which originate the response at the very // end of your route(s). The documentation for a module should state whether it invokes // the next handler, but sometimes it is common sense. // // Some handlers manipulate the response. Remember that requests flow down the list, and // responses flow up the list. // // For example, if you wanted to use both `templates` and `encode` handlers, you would // need to put `templates` after `encode` in your route, because responses flow up. // Thus, `templates` will be able to parse and execute the plain-text response as a // template, and then return it up to the `encode` handler which will then compress it // into a binary format. // // If `templates` came before `encode`, then `encode` would write a compressed, // binary-encoded response to `templates` which would not be able to parse the response // properly. // // The correct order, then, is this: // // [ // {"handler": "encode"}, // {"handler": "templates"}, // {"handler": "file_server"} // ] // // The request flows ⬇️ DOWN (`encode` -> `templates` -> `file_server`). // // 1. First, `encode` will choose how to `encode` the response and wrap the response. // 2. Then, `templates` will wrap the response with a buffer. // 3. Finally, `file_server` will originate the content from a file. // // The response flows ⬆️ UP (`file_server` -> `templates` -> `encode`): // // 1. First, `file_server` will write the file to the response. // 2. That write will be buffered and then executed by `templates`. // 3. Lastly, the write from `templates` will flow into `encode` which will compress the stream. // // If you think of routes in this way, it will be easy and even fun to solve the puzzle of writing correct routes. HandlersRaw []json.RawMessage `json:"handle,omitempty" caddy:"namespace=http.handlers inline_key=handler"` // If true, no more routes will be executed after this one. Terminal bool `json:"terminal,omitempty"` // decoded values MatcherSets MatcherSets `json:"-"` Handlers []MiddlewareHandler `json:"-"` middleware []Middleware } // Empty returns true if the route has all zero/default values. func (r Route) Empty() bool { return len(r.MatcherSetsRaw) == 0 && len(r.MatcherSets) == 0 && len(r.HandlersRaw) == 0 && len(r.Handlers) == 0 && !r.Terminal && r.Group == "" } func (r Route) String() string { handlersRaw := "[" for _, hr := range r.HandlersRaw { handlersRaw += " " + string(hr) } handlersRaw += "]" return fmt.Sprintf(`{Group:"%s" MatcherSetsRaw:%s HandlersRaw:%s Terminal:%t}`, r.Group, r.MatcherSetsRaw, handlersRaw, r.Terminal) } // Provision sets up both the matchers and handlers in the route. func (r *Route) Provision(ctx caddy.Context, metrics *Metrics) error { err := r.ProvisionMatchers(ctx) if err != nil { return err } return r.ProvisionHandlers(ctx, metrics) } // ProvisionMatchers sets up all the matchers by loading the // matcher modules. Only call this method directly if you need // to set up matchers and handlers separately without having // to provision a second time; otherwise use Provision instead. func (r *Route) ProvisionMatchers(ctx caddy.Context) error { // matchers matchersIface, err := ctx.LoadModule(r, "MatcherSetsRaw") if err != nil { return fmt.Errorf("loading matcher modules: %v", err) } err = r.MatcherSets.FromInterface(matchersIface) if err != nil { return err } return nil } // ProvisionHandlers sets up all the handlers by loading the // handler modules. Only call this method directly if you need // to set up matchers and handlers separately without having // to provision a second time; otherwise use Provision instead. func (r *Route) ProvisionHandlers(ctx caddy.Context, metrics *Metrics) error { handlersIface, err := ctx.LoadModule(r, "HandlersRaw") if err != nil { return fmt.Errorf("loading handler modules: %v", err) } for _, handler := range handlersIface.([]any) { r.Handlers = append(r.Handlers, handler.(MiddlewareHandler)) } // Make ProvisionHandlers idempotent by clearing the middleware field r.middleware = []Middleware{} // pre-compile the middleware handler chain for _, midhandler := range r.Handlers { r.middleware = append(r.middleware, wrapMiddleware(ctx, midhandler, metrics)) } return nil } // Compile prepares a middleware chain from the route list. // This should only be done once during the request, just // before the middleware chain is executed. func (r Route) Compile(next Handler) Handler { return wrapRoute(r)(next) } // RouteList is a list of server routes that can // create a middleware chain. type RouteList []Route // Provision sets up both the matchers and handlers in the routes. func (routes RouteList) Provision(ctx caddy.Context) error { err := routes.ProvisionMatchers(ctx) if err != nil { return err } return routes.ProvisionHandlers(ctx, nil) } // ProvisionMatchers sets up all the matchers by loading the // matcher modules. Only call this method directly if you need // to set up matchers and handlers separately without having // to provision a second time; otherwise use Provision instead. func (routes RouteList) ProvisionMatchers(ctx caddy.Context) error { for i := range routes { err := routes[i].ProvisionMatchers(ctx) if err != nil { return fmt.Errorf("route %d: %v", i, err) } } return nil } // ProvisionHandlers sets up all the handlers by loading the // handler modules. Only call this method directly if you need // to set up matchers and handlers separately without having // to provision a second time; otherwise use Provision instead. func (routes RouteList) ProvisionHandlers(ctx caddy.Context, metrics *Metrics) error { for i := range routes { err := routes[i].ProvisionHandlers(ctx, metrics) if err != nil { return fmt.Errorf("route %d: %v", i, err) } } return nil } // Compile prepares a middleware chain from the route list. // This should only be done either once during provisioning // for top-level routes, or on each request just before the // middleware chain is executed for subroutes. func (routes RouteList) Compile(next Handler) Handler { mid := make([]Middleware, 0, len(routes)) for _, route := range routes { mid = append(mid, wrapRoute(route)) } stack := next for i := len(mid) - 1; i >= 0; i-- { stack = mid[i](stack) } return stack } // wrapRoute wraps route with a middleware and handler so that it can // be chained in and defer evaluation of its matchers to request-time. // Like wrapMiddleware, it is vital that this wrapping takes place in // its own stack frame so as to not overwrite the reference to the // intended route by looping and changing the reference each time. func wrapRoute(route Route) Middleware { return func(next Handler) Handler { return HandlerFunc(func(rw http.ResponseWriter, req *http.Request) error { // TODO: Update this comment, it seems we've moved the copy into the handler? // copy the next handler (it's an interface, so it's just // a very lightweight copy of a pointer); this is important // because this is a closure to the func below, which // re-assigns the value as it compiles the middleware stack; // if we don't make this copy, we'd affect the underlying // pointer for all future request (yikes); we could // alternatively solve this by moving the func below out of // this closure and into a standalone package-level func, // but I just thought this made more sense nextCopy := next // route must match at least one of the matcher sets matches, err := route.MatcherSets.AnyMatchWithError(req) if err != nil { // allow matchers the opportunity to short circuit // the request and trigger the error handling chain return err } if !matches { // call the next handler, and skip this one, // since the matcher didn't match return nextCopy.ServeHTTP(rw, req) } // if route is part of a group, ensure only the // first matching route in the group is applied if route.Group != "" { groups := req.Context().Value(routeGroupCtxKey).(map[string]struct{}) if _, ok := groups[route.Group]; ok { // this group has already been // satisfied by a matching route return nextCopy.ServeHTTP(rw, req) } // this matching route satisfies the group groups[route.Group] = struct{}{} } // make terminal routes terminate if route.Terminal { if _, ok := req.Context().Value(ErrorCtxKey).(error); ok { nextCopy = errorEmptyHandler } else { nextCopy = emptyHandler } } // compile this route's handler stack for i := len(route.middleware) - 1; i >= 0; i-- { nextCopy = route.middleware[i](nextCopy) } return nextCopy.ServeHTTP(rw, req) }) } } // wrapMiddleware wraps mh such that it can be correctly // appended to a list of middleware in preparation for // compiling into a handler chain. func wrapMiddleware(ctx caddy.Context, mh MiddlewareHandler, metrics *Metrics) Middleware { handlerToUse := mh if metrics != nil { // wrap the middleware with metrics instrumentation handlerToUse = newMetricsInstrumentedHandler(ctx, caddy.GetModuleName(mh), mh, metrics) } return func(next Handler) Handler { return HandlerFunc(func(w http.ResponseWriter, r *http.Request) error { // EXPERIMENTAL: Trace each module that gets invoked if server, ok := r.Context().Value(ServerCtxKey).(*Server); ok && server != nil { server.logTrace(handlerToUse) } return handlerToUse.ServeHTTP(w, r, next) }) } } // MatcherSet is a set of matchers which // must all match in order for the request // to be matched successfully. type MatcherSet []any // Match returns true if the request matches all // matchers in mset or if there are no matchers. func (mset MatcherSet) Match(r *http.Request) bool { for _, m := range mset { if me, ok := m.(RequestMatcherWithError); ok { match, _ := me.MatchWithError(r) if !match { return false } continue } if me, ok := m.(RequestMatcher); ok { if !me.Match(r) { return false } continue } return false } return true } // MatchWithError returns true if r matches m. func (mset MatcherSet) MatchWithError(r *http.Request) (bool, error) { for _, m := range mset { if me, ok := m.(RequestMatcherWithError); ok { match, err := me.MatchWithError(r) if err != nil || !match { return match, err } continue } if me, ok := m.(RequestMatcher); ok { if !me.Match(r) { // for backwards compatibility err, ok := GetVar(r.Context(), MatcherErrorVarKey).(error) if ok { // clear out the error from context since we've consumed it SetVar(r.Context(), MatcherErrorVarKey, nil) return false, err } return false, nil } continue } return false, fmt.Errorf("matcher is not a RequestMatcher or RequestMatcherWithError: %#v", m) } return true, nil } // RawMatcherSets is a group of matcher sets // in their raw, JSON form. type RawMatcherSets []caddy.ModuleMap // MatcherSets is a group of matcher sets capable // of checking whether a request matches any of // the sets. type MatcherSets []MatcherSet // AnyMatch returns true if req matches any of the // matcher sets in ms or if there are no matchers, // in which case the request always matches. // // Deprecated: Use AnyMatchWithError instead. func (ms MatcherSets) AnyMatch(req *http.Request) bool { for _, m := range ms { match, err := m.MatchWithError(req) if err != nil { SetVar(req.Context(), MatcherErrorVarKey, err) return false } if match { return match } } return len(ms) == 0 } // AnyMatchWithError returns true if req matches any of the // matcher sets in ms or if there are no matchers, in which // case the request always matches. If any matcher returns // an error, we cut short and return the error. func (ms MatcherSets) AnyMatchWithError(req *http.Request) (bool, error) { for _, m := range ms { match, err := m.MatchWithError(req) if err != nil || match { return match, err } } return len(ms) == 0, nil } // FromInterface fills ms from an 'any' value obtained from LoadModule. func (ms *MatcherSets) FromInterface(matcherSets any) error { for _, matcherSetIfaces := range matcherSets.([]map[string]any) { var matcherSet MatcherSet for _, matcher := range matcherSetIfaces { if m, ok := matcher.(RequestMatcherWithError); ok { matcherSet = append(matcherSet, m) continue } if m, ok := matcher.(RequestMatcher); ok { matcherSet = append(matcherSet, m) continue } return fmt.Errorf("decoded module is not a RequestMatcher or RequestMatcherWithError: %#v", matcher) } *ms = append(*ms, matcherSet) } return nil } // TODO: Is this used? func (ms MatcherSets) String() string { result := "[" for _, matcherSet := range ms { for _, matcher := range matcherSet { result += fmt.Sprintf(" %#v", matcher) } } return result + " ]" } var routeGroupCtxKey = caddy.CtxKey("route_group")
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/push/caddyfile.go
modules/caddyhttp/push/caddyfile.go
// Copyright 2015 Matthew Holt and The Caddy 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 push import ( "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" "github.com/caddyserver/caddy/v2/modules/caddyhttp/headers" ) func init() { httpcaddyfile.RegisterHandlerDirective("push", parseCaddyfile) } // parseCaddyfile sets up the push handler. Syntax: // // push [<matcher>] [<resource>] { // [GET|HEAD] <resource> // headers { // [+]<field> [<value|regexp> [<replacement>]] // -<field> // } // } // // A single resource can be specified inline without opening a // block for the most common/simple case. Or, a block can be // opened and multiple resources can be specified, one per // line, optionally preceded by the method. The headers // subdirective can be used to customize the headers that // are set on each (synthetic) push request, using the same // syntax as the 'header' directive for request headers. // Placeholders are accepted in resource and header field // name and value and replacement tokens. func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) { h.Next() // consume directive name handler := new(Handler) // inline resources if h.NextArg() { handler.Resources = append(handler.Resources, Resource{Target: h.Val()}) } // optional block for h.NextBlock(0) { switch h.Val() { case "headers": if h.NextArg() { return nil, h.ArgErr() } for nesting := h.Nesting(); h.NextBlock(nesting); { var err error // include current token, which we treat as an argument here args := []string{h.Val()} args = append(args, h.RemainingArgs()...) if handler.Headers == nil { handler.Headers = new(HeaderConfig) } switch len(args) { case 1: err = headers.CaddyfileHeaderOp(&handler.Headers.HeaderOps, args[0], "", nil) case 2: err = headers.CaddyfileHeaderOp(&handler.Headers.HeaderOps, args[0], args[1], nil) case 3: err = headers.CaddyfileHeaderOp(&handler.Headers.HeaderOps, args[0], args[1], &args[2]) default: return nil, h.ArgErr() } if err != nil { return nil, h.Err(err.Error()) } } case "GET", "HEAD": method := h.Val() if !h.NextArg() { return nil, h.ArgErr() } target := h.Val() handler.Resources = append(handler.Resources, Resource{ Method: method, Target: target, }) default: handler.Resources = append(handler.Resources, Resource{Target: h.Val()}) } } return handler, nil }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/push/link.go
modules/caddyhttp/push/link.go
// Copyright 2015 Matthew Holt and The Caddy 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 push import ( "strings" ) // linkResource contains the results of a parsed Link header. type linkResource struct { uri string params map[string]string } // parseLinkHeader is responsible for parsing Link header // and returning list of found resources. // // Accepted formats are: // // Link: <resource>; as=script // Link: <resource>; as=script,<resource>; as=style // Link: <resource>;<resource2> // // where <resource> begins with a forward slash (/). func parseLinkHeader(header string) []linkResource { resources := []linkResource{} if header == "" { return resources } for link := range strings.SplitSeq(header, comma) { l := linkResource{params: make(map[string]string)} li, ri := strings.Index(link, "<"), strings.Index(link, ">") if li == -1 || ri == -1 { continue } l.uri = strings.TrimSpace(link[li+1 : ri]) for param := range strings.SplitSeq(strings.TrimSpace(link[ri+1:]), semicolon) { before, after, isCut := strings.Cut(strings.TrimSpace(param), equal) key := strings.TrimSpace(before) if key == "" { continue } if isCut { l.params[key] = strings.TrimSpace(after) } else { l.params[key] = key } } resources = append(resources, l) } return resources } const ( comma = "," semicolon = ";" equal = "=" )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/push/link_test.go
modules/caddyhttp/push/link_test.go
// Copyright 2015 Matthew Holt and The Caddy 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 push import ( "reflect" "testing" ) func TestParseLinkHeader(t *testing.T) { testCases := []struct { header string expectedResources []linkResource }{ { header: "</resource>; as=script", expectedResources: []linkResource{{uri: "/resource", params: map[string]string{"as": "script"}}}, }, { header: "</resource>", expectedResources: []linkResource{{uri: "/resource", params: map[string]string{}}}, }, { header: "</resource>; nopush", expectedResources: []linkResource{{uri: "/resource", params: map[string]string{"nopush": "nopush"}}}, }, { header: "</resource>;nopush;rel=next", expectedResources: []linkResource{{uri: "/resource", params: map[string]string{"nopush": "nopush", "rel": "next"}}}, }, { header: "</resource>;nopush;rel=next,</resource2>;nopush", expectedResources: []linkResource{ {uri: "/resource", params: map[string]string{"nopush": "nopush", "rel": "next"}}, {uri: "/resource2", params: map[string]string{"nopush": "nopush"}}, }, }, { header: "</resource>,</resource2>", expectedResources: []linkResource{ {uri: "/resource", params: map[string]string{}}, {uri: "/resource2", params: map[string]string{}}, }, }, { header: "malformed", expectedResources: []linkResource{}, }, { header: "<malformed", expectedResources: []linkResource{}, }, { header: ",", expectedResources: []linkResource{}, }, { header: ";", expectedResources: []linkResource{}, }, { header: "</resource> ; ", expectedResources: []linkResource{{uri: "/resource", params: map[string]string{}}}, }, } for i, test := range testCases { actualResources := parseLinkHeader(test.header) if !reflect.DeepEqual(actualResources, test.expectedResources) { t.Errorf("Test %d (header: %s) - expected resources %v, got %v", i, test.header, test.expectedResources, actualResources) } } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/push/handler.go
modules/caddyhttp/push/handler.go
// Copyright 2015 Matthew Holt and The Caddy 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 push import ( "fmt" "net/http" "strings" "go.uber.org/zap" "go.uber.org/zap/zapcore" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" "github.com/caddyserver/caddy/v2/modules/caddyhttp/headers" ) func init() { caddy.RegisterModule(Handler{}) } // Handler is a middleware for HTTP/2 server push. Note that // HTTP/2 server push has been deprecated by some clients and // its use is discouraged unless you can accurately predict // which resources actually need to be pushed to the client; // it can be difficult to know what the client already has // cached. Pushing unnecessary resources results in worse // performance. Consider using HTTP 103 Early Hints instead. // // This handler supports pushing from Link headers; in other // words, if the eventual response has Link headers, this // handler will push the resources indicated by those headers, // even without specifying any resources in its config. type Handler struct { // The resources to push. Resources []Resource `json:"resources,omitempty"` // Headers to modify for the push requests. Headers *HeaderConfig `json:"headers,omitempty"` logger *zap.Logger } // CaddyModule returns the Caddy module information. func (Handler) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.handlers.push", New: func() caddy.Module { return new(Handler) }, } } // Provision sets up h. func (h *Handler) Provision(ctx caddy.Context) error { h.logger = ctx.Logger() if h.Headers != nil { err := h.Headers.Provision(ctx) if err != nil { return fmt.Errorf("provisioning header operations: %v", err) } } return nil } func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { pusher, ok := w.(http.Pusher) if !ok { return next.ServeHTTP(w, r) } // short-circuit recursive pushes if _, ok := r.Header[pushHeader]; ok { return next.ServeHTTP(w, r) } repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) server := r.Context().Value(caddyhttp.ServerCtxKey).(*caddyhttp.Server) shouldLogCredentials := server.Logs != nil && server.Logs.ShouldLogCredentials // create header for push requests hdr := h.initializePushHeaders(r, repl) // push first! for _, resource := range h.Resources { if c := h.logger.Check(zapcore.DebugLevel, "pushing resource"); c != nil { c.Write( zap.String("uri", r.RequestURI), zap.String("push_method", resource.Method), zap.String("push_target", resource.Target), zap.Object("push_headers", caddyhttp.LoggableHTTPHeader{ Header: hdr, ShouldLogCredentials: shouldLogCredentials, }), ) } err := pusher.Push(repl.ReplaceAll(resource.Target, "."), &http.PushOptions{ Method: resource.Method, Header: hdr, }) if err != nil { // usually this means either that push is not // supported or concurrent streams are full break } } // wrap the response writer so that we can initiate push of any resources // described in Link header fields before the response is written lp := linkPusher{ ResponseWriterWrapper: &caddyhttp.ResponseWriterWrapper{ResponseWriter: w}, handler: h, pusher: pusher, header: hdr, request: r, } // serve only after pushing! if err := next.ServeHTTP(lp, r); err != nil { return err } return nil } func (h Handler) initializePushHeaders(r *http.Request, repl *caddy.Replacer) http.Header { hdr := make(http.Header) // prevent recursive pushes hdr.Set(pushHeader, "1") // set initial header fields; since exactly how headers should // be implemented for server push is not well-understood, we // are being conservative for now like httpd is: // https://httpd.apache.org/docs/2.4/en/howto/http2.html#push // we only copy some well-known, safe headers that are likely // crucial when requesting certain kinds of content for _, fieldName := range safeHeaders { if vals, ok := r.Header[fieldName]; ok { hdr[fieldName] = vals } } // user can customize the push request headers if h.Headers != nil { h.Headers.ApplyTo(hdr, repl) } return hdr } // servePreloadLinks parses Link headers from upstream and pushes // resources described by them. If a resource has the "nopush" // attribute or describes an external entity (meaning, the resource // URI includes a scheme), it will not be pushed. func (h Handler) servePreloadLinks(pusher http.Pusher, hdr http.Header, resources []string) { for _, resource := range resources { for _, resource := range parseLinkHeader(resource) { if _, ok := resource.params["nopush"]; ok { continue } if isRemoteResource(resource.uri) { continue } err := pusher.Push(resource.uri, &http.PushOptions{ Header: hdr, }) if err != nil { return } } } } // Resource represents a request for a resource to push. type Resource struct { // Method is the request method, which must be GET or HEAD. // Default is GET. Method string `json:"method,omitempty"` // Target is the path to the resource being pushed. Target string `json:"target,omitempty"` } // HeaderConfig configures headers for synthetic push requests. type HeaderConfig struct { headers.HeaderOps } // linkPusher is a http.ResponseWriter that intercepts // the WriteHeader() call to ensure that any resources // described by Link response headers get pushed before // the response is allowed to be written. type linkPusher struct { *caddyhttp.ResponseWriterWrapper handler Handler pusher http.Pusher header http.Header request *http.Request } func (lp linkPusher) WriteHeader(statusCode int) { if links, ok := lp.ResponseWriter.Header()["Link"]; ok { // only initiate these pushes if it hasn't been done yet if val := caddyhttp.GetVar(lp.request.Context(), pushedLink); val == nil { if c := lp.handler.logger.Check(zapcore.DebugLevel, "pushing Link resources"); c != nil { c.Write(zap.Strings("linked", links)) } caddyhttp.SetVar(lp.request.Context(), pushedLink, true) lp.handler.servePreloadLinks(lp.pusher, lp.header, links) } } lp.ResponseWriter.WriteHeader(statusCode) } // isRemoteResource returns true if resource starts with // a scheme or is a protocol-relative URI. func isRemoteResource(resource string) bool { return strings.HasPrefix(resource, "//") || strings.HasPrefix(resource, "http://") || strings.HasPrefix(resource, "https://") } // safeHeaders is a list of header fields that are // safe to copy to push requests implicitly. It is // assumed that requests for certain kinds of content // would fail without these fields present. var safeHeaders = []string{ "Accept-Encoding", "Accept-Language", "Accept", "Cache-Control", "User-Agent", } // pushHeader is a header field that gets added to push requests // in order to avoid recursive/infinite pushes. const pushHeader = "Caddy-Push" // pushedLink is the key for the variable on the request // context that we use to remember whether we have already // pushed resources from Link headers yet; otherwise, if // multiple push handlers are invoked, it would repeat the // pushing of Link headers. const pushedLink = "http.handlers.push.pushed_link" // Interface guards var ( _ caddy.Provisioner = (*Handler)(nil) _ caddyhttp.MiddlewareHandler = (*Handler)(nil) _ http.ResponseWriter = (*linkPusher)(nil) _ http.Pusher = (*linkPusher)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/standard/imports.go
modules/caddyhttp/standard/imports.go
package standard import ( // standard Caddy HTTP app modules _ "github.com/caddyserver/caddy/v2/modules/caddyhttp" _ "github.com/caddyserver/caddy/v2/modules/caddyhttp/caddyauth" _ "github.com/caddyserver/caddy/v2/modules/caddyhttp/encode" _ "github.com/caddyserver/caddy/v2/modules/caddyhttp/encode/brotli" _ "github.com/caddyserver/caddy/v2/modules/caddyhttp/encode/gzip" _ "github.com/caddyserver/caddy/v2/modules/caddyhttp/encode/zstd" _ "github.com/caddyserver/caddy/v2/modules/caddyhttp/fileserver" _ "github.com/caddyserver/caddy/v2/modules/caddyhttp/headers" _ "github.com/caddyserver/caddy/v2/modules/caddyhttp/intercept" _ "github.com/caddyserver/caddy/v2/modules/caddyhttp/logging" _ "github.com/caddyserver/caddy/v2/modules/caddyhttp/map" _ "github.com/caddyserver/caddy/v2/modules/caddyhttp/proxyprotocol" _ "github.com/caddyserver/caddy/v2/modules/caddyhttp/push" _ "github.com/caddyserver/caddy/v2/modules/caddyhttp/requestbody" _ "github.com/caddyserver/caddy/v2/modules/caddyhttp/reverseproxy" _ "github.com/caddyserver/caddy/v2/modules/caddyhttp/reverseproxy/fastcgi" _ "github.com/caddyserver/caddy/v2/modules/caddyhttp/reverseproxy/forwardauth" _ "github.com/caddyserver/caddy/v2/modules/caddyhttp/rewrite" _ "github.com/caddyserver/caddy/v2/modules/caddyhttp/templates" _ "github.com/caddyserver/caddy/v2/modules/caddyhttp/tracing" )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/proxyprotocol/policy.go
modules/caddyhttp/proxyprotocol/policy.go
package proxyprotocol import ( "errors" "fmt" "strings" goproxy "github.com/pires/go-proxyproto" ) type Policy int // as defined in: https://pkg.go.dev/github.com/pires/go-proxyproto@v0.7.0#Policy const ( // IGNORE address from PROXY header, but accept connection PolicyIGNORE Policy = iota // USE address from PROXY header PolicyUSE // REJECT connection when PROXY header is sent // Note: even though the first read on the connection returns an error if // a PROXY header is present, subsequent reads do not. It is the task of // the code using the connection to handle that case properly. PolicyREJECT // REQUIRE connection to send PROXY header, reject if not present // Note: even though the first read on the connection returns an error if // a PROXY header is not present, subsequent reads do not. It is the task // of the code using the connection to handle that case properly. PolicyREQUIRE // SKIP accepts a connection without requiring the PROXY header // Note: an example usage can be found in the SkipProxyHeaderForCIDR // function. PolicySKIP ) var policyToGoProxyPolicy = map[Policy]goproxy.Policy{ PolicyUSE: goproxy.USE, PolicyIGNORE: goproxy.IGNORE, PolicyREJECT: goproxy.REJECT, PolicyREQUIRE: goproxy.REQUIRE, PolicySKIP: goproxy.SKIP, } var policyMap = map[Policy]string{ PolicyUSE: "USE", PolicyIGNORE: "IGNORE", PolicyREJECT: "REJECT", PolicyREQUIRE: "REQUIRE", PolicySKIP: "SKIP", } var policyMapRev = map[string]Policy{ "USE": PolicyUSE, "IGNORE": PolicyIGNORE, "REJECT": PolicyREJECT, "REQUIRE": PolicyREQUIRE, "SKIP": PolicySKIP, } // MarshalText implements the text marshaller method. func (x Policy) MarshalText() ([]byte, error) { return []byte(policyMap[x]), nil } // UnmarshalText implements the text unmarshaller method. func (x *Policy) UnmarshalText(text []byte) error { name := string(text) tmp, err := parsePolicy(name) if err != nil { return err } *x = tmp return nil } func parsePolicy(name string) (Policy, error) { if x, ok := policyMapRev[strings.ToUpper(name)]; ok { return x, nil } return Policy(0), fmt.Errorf("%s is %w", name, errInvalidPolicy) } var errInvalidPolicy = errors.New("invalid policy")
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/proxyprotocol/module.go
modules/caddyhttp/proxyprotocol/module.go
// Copyright 2015 Matthew Holt and The Caddy 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 proxyprotocol import ( "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func init() { caddy.RegisterModule(ListenerWrapper{}) } func (ListenerWrapper) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "caddy.listeners.proxy_protocol", New: func() caddy.Module { return new(ListenerWrapper) }, } } // UnmarshalCaddyfile sets up the listener Listenerwrapper from Caddyfile tokens. Syntax: // // proxy_protocol { // timeout <duration> // allow <IPs...> // deny <IPs...> // fallback_policy <policy> // } func (w *ListenerWrapper) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume wrapper name // No same-line options are supported if d.NextArg() { return d.ArgErr() } for d.NextBlock(0) { switch d.Val() { case "timeout": if !d.NextArg() { return d.ArgErr() } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("parsing proxy_protocol timeout duration: %v", err) } w.Timeout = caddy.Duration(dur) case "allow": w.Allow = append(w.Allow, d.RemainingArgs()...) case "deny": w.Deny = append(w.Deny, d.RemainingArgs()...) case "fallback_policy": if !d.NextArg() { return d.ArgErr() } p, err := parsePolicy(d.Val()) if err != nil { return d.WrapErr(err) } w.FallbackPolicy = p default: return d.ArgErr() } } return nil } // Interface guards var ( _ caddy.Provisioner = (*ListenerWrapper)(nil) _ caddy.Module = (*ListenerWrapper)(nil) _ caddy.ListenerWrapper = (*ListenerWrapper)(nil) _ caddyfile.Unmarshaler = (*ListenerWrapper)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/proxyprotocol/listenerwrapper.go
modules/caddyhttp/proxyprotocol/listenerwrapper.go
// Copyright 2015 Matthew Holt and The Caddy 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 proxyprotocol import ( "net" "net/netip" "time" goproxy "github.com/pires/go-proxyproto" "github.com/caddyserver/caddy/v2" ) // ListenerWrapper provides PROXY protocol support to Caddy by implementing // the caddy.ListenerWrapper interface. If a connection is received via Unix // socket, it's trusted. Otherwise, it's checked against the Allow/Deny lists, // then it's handled by the FallbackPolicy. // // It must be loaded before the `tls` listener because the PROXY protocol // encapsulates the TLS data. // // Credit goes to https://github.com/mastercactapus/caddy2-proxyprotocol for having // initially implemented this as a plugin. type ListenerWrapper struct { // Timeout specifies an optional maximum time for // the PROXY header to be received. // If zero, timeout is disabled. Default is 5s. Timeout caddy.Duration `json:"timeout,omitempty"` // Allow is an optional list of CIDR ranges to // allow/require PROXY headers from. Allow []string `json:"allow,omitempty"` allow []netip.Prefix // Deny is an optional list of CIDR ranges to // deny PROXY headers from. Deny []string `json:"deny,omitempty"` deny []netip.Prefix // FallbackPolicy specifies the policy to use if the downstream // IP address is not in the Allow list nor is in the Deny list. // // NOTE: The generated docs which describe the value of this // field is wrong because of how this type unmarshals JSON in a // custom way. The field expects a string, not a number. // // Accepted values are: IGNORE, USE, REJECT, REQUIRE, SKIP // // - IGNORE: address from PROXY header, but accept connection // // - USE: address from PROXY header // // - REJECT: connection when PROXY header is sent // Note: even though the first read on the connection returns an error if // a PROXY header is present, subsequent reads do not. It is the task of // the code using the connection to handle that case properly. // // - REQUIRE: connection to send PROXY header, reject if not present // Note: even though the first read on the connection returns an error if // a PROXY header is not present, subsequent reads do not. It is the task // of the code using the connection to handle that case properly. // // - SKIP: accepts a connection without requiring the PROXY header. // Note: an example usage can be found in the SkipProxyHeaderForCIDR // function. // // Default: IGNORE // // Policy definitions are here: https://pkg.go.dev/github.com/pires/go-proxyproto@v0.7.0#Policy FallbackPolicy Policy `json:"fallback_policy,omitempty"` policy goproxy.ConnPolicyFunc } // Provision sets up the listener wrapper. func (pp *ListenerWrapper) Provision(ctx caddy.Context) error { for _, cidr := range pp.Allow { ipnet, err := netip.ParsePrefix(cidr) if err != nil { return err } pp.allow = append(pp.allow, ipnet) } for _, cidr := range pp.Deny { ipnet, err := netip.ParsePrefix(cidr) if err != nil { return err } pp.deny = append(pp.deny, ipnet) } pp.policy = func(options goproxy.ConnPolicyOptions) (goproxy.Policy, error) { // trust unix sockets if network := options.Upstream.Network(); caddy.IsUnixNetwork(network) || caddy.IsFdNetwork(network) { return goproxy.USE, nil } ret := pp.FallbackPolicy host, _, err := net.SplitHostPort(options.Upstream.String()) if err != nil { return goproxy.REJECT, err } ip, err := netip.ParseAddr(host) if err != nil { return goproxy.REJECT, err } for _, ipnet := range pp.deny { if ipnet.Contains(ip) { return goproxy.REJECT, nil } } for _, ipnet := range pp.allow { if ipnet.Contains(ip) { ret = PolicyUSE break } } return policyToGoProxyPolicy[ret], nil } return nil } // WrapListener adds PROXY protocol support to the listener. func (pp *ListenerWrapper) WrapListener(l net.Listener) net.Listener { pl := &goproxy.Listener{ Listener: l, ReadHeaderTimeout: time.Duration(pp.Timeout), } pl.ConnPolicy = pp.policy return pl }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/logging/caddyfile.go
modules/caddyhttp/logging/caddyfile.go
// Copyright 2015 Matthew Holt and The Caddy 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 logging import ( "strings" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func init() { httpcaddyfile.RegisterHandlerDirective("log_append", parseCaddyfile) } // parseCaddyfile sets up the log_append handler from Caddyfile tokens. Syntax: // // log_append [<matcher>] [<]<key> <value> func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) { handler := new(LogAppend) err := handler.UnmarshalCaddyfile(h.Dispenser) return handler, err } // UnmarshalCaddyfile implements caddyfile.Unmarshaler. func (h *LogAppend) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume directive name if !d.NextArg() { return d.ArgErr() } h.Key = d.Val() if !d.NextArg() { return d.ArgErr() } if strings.HasPrefix(h.Key, "<") && len(h.Key) > 1 { h.Early = true h.Key = h.Key[1:] } h.Value = d.Val() return nil } // Interface guards var ( _ caddyfile.Unmarshaler = (*LogAppend)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/logging/logappend.go
modules/caddyhttp/logging/logappend.go
// Copyright 2015 Matthew Holt and The Caddy 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 logging import ( "bytes" "encoding/base64" "net/http" "strings" "go.uber.org/zap" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func init() { caddy.RegisterModule(LogAppend{}) } // LogAppend implements a middleware that takes a key and value, where // the key is the name of a log field and the value is a placeholder, // or variable key, or constant value to use for that field. type LogAppend struct { // Key is the name of the log field. Key string `json:"key,omitempty"` // Value is the value to use for the log field. // If it is a placeholder (with surrounding `{}`), // it will be evaluated when the log is written. // If the value is a key that exists in the `vars` // map, the value of that key will be used. Otherwise // the value will be used as-is as a constant string. Value string `json:"value,omitempty"` // Early, if true, adds the log field before calling // the next handler in the chain. By default, the log // field is added on the way back up the middleware chain, // after all subsequent handlers have completed. Early bool `json:"early,omitempty"` } // CaddyModule returns the Caddy module information. func (LogAppend) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.handlers.log_append", New: func() caddy.Module { return new(LogAppend) }, } } func (h LogAppend) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { // Determine if we need to add the log field early. // We do if the Early flag is set, or for convenience, // if the value is a special placeholder for the request body. needsEarly := h.Early || h.Value == placeholderRequestBody || h.Value == placeholderRequestBodyBase64 // Check if we need to buffer the response for special placeholders needsResponseBody := h.Value == placeholderResponseBody || h.Value == placeholderResponseBodyBase64 if needsEarly && !needsResponseBody { // Add the log field before calling the next handler // (but not if we need the response body, which isn't available yet) h.addLogField(r, nil) } var rec caddyhttp.ResponseRecorder var buf *bytes.Buffer if needsResponseBody { // Wrap the response writer with a recorder to capture the response body buf = new(bytes.Buffer) rec = caddyhttp.NewResponseRecorder(w, buf, func(status int, header http.Header) bool { // Always buffer the response when we need to log the body return true }) w = rec } // Run the next handler in the chain. // If an error occurs, we still want to add // any extra log fields that we can, so we // hold onto the error and return it later. handlerErr := next.ServeHTTP(w, r) if needsResponseBody { // Write the buffered response to the client if rec.Buffered() { h.addLogField(r, buf) err := rec.WriteResponse() if err != nil { return err } } return handlerErr } if !h.Early { // Add the log field after the handler completes h.addLogField(r, buf) } return handlerErr } // addLogField adds the log field to the request's extra log fields. // If buf is not nil, it contains the buffered response body for special // response body placeholders. func (h LogAppend) addLogField(r *http.Request, buf *bytes.Buffer) { ctx := r.Context() vars := ctx.Value(caddyhttp.VarsCtxKey).(map[string]any) repl := ctx.Value(caddy.ReplacerCtxKey).(*caddy.Replacer) extra := ctx.Value(caddyhttp.ExtraLogFieldsCtxKey).(*caddyhttp.ExtraLogFields) var varValue any // Handle special case placeholders for response body if h.Value == placeholderResponseBody { if buf != nil { varValue = buf.String() } else { varValue = "" } } else if h.Value == placeholderResponseBodyBase64 { if buf != nil { varValue = base64.StdEncoding.EncodeToString(buf.Bytes()) } else { varValue = "" } } else if strings.HasPrefix(h.Value, "{") && strings.HasSuffix(h.Value, "}") && strings.Count(h.Value, "{") == 1 { // the value looks like a placeholder, so get its value varValue, _ = repl.Get(strings.Trim(h.Value, "{}")) } else if val, ok := vars[h.Value]; ok { // the value is a key in the vars map varValue = val } else { // the value is a constant string varValue = h.Value } // Add the field to the extra log fields. // We use zap.Any because it will reflect // to the correct type for us. extra.Add(zap.Any(h.Key, varValue)) } const ( // Special placeholder values that are handled by log_append // rather than by the replacer. placeholderRequestBody = "{http.request.body}" placeholderRequestBodyBase64 = "{http.request.body_base64}" placeholderResponseBody = "{http.response.body}" placeholderResponseBodyBase64 = "{http.response.body_base64}" ) // Interface guards var ( _ caddyhttp.MiddlewareHandler = (*LogAppend)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/tracing/tracer.go
modules/caddyhttp/tracing/tracer.go
package tracing import ( "context" "fmt" "net/http" "go.opentelemetry.io/contrib/exporters/autoexport" "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" "go.opentelemetry.io/contrib/propagators/autoprop" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/propagation" "go.opentelemetry.io/otel/sdk/resource" sdktrace "go.opentelemetry.io/otel/sdk/trace" semconv "go.opentelemetry.io/otel/semconv/v1.17.0" "go.opentelemetry.io/otel/trace" "go.uber.org/zap" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) const ( webEngineName = "Caddy" defaultSpanName = "handler" nextCallCtxKey caddy.CtxKey = "nextCall" ) // nextCall store the next handler, and the error value return on calling it (if any) type nextCall struct { next caddyhttp.Handler err error } // openTelemetryWrapper is responsible for the tracing injection, extraction and propagation. type openTelemetryWrapper struct { propagators propagation.TextMapPropagator handler http.Handler spanName string spanAttributes map[string]string } // newOpenTelemetryWrapper is responsible for the openTelemetryWrapper initialization using provided configuration. func newOpenTelemetryWrapper( ctx context.Context, spanName string, spanAttributes map[string]string, ) (openTelemetryWrapper, error) { if spanName == "" { spanName = defaultSpanName } ot := openTelemetryWrapper{ spanName: spanName, spanAttributes: spanAttributes, } version, _ := caddy.Version() res, err := ot.newResource(webEngineName, version) if err != nil { return ot, fmt.Errorf("creating resource error: %w", err) } traceExporter, err := autoexport.NewSpanExporter(ctx) if err != nil { return ot, fmt.Errorf("creating trace exporter error: %w", err) } ot.propagators = autoprop.NewTextMapPropagator() tracerProvider := globalTracerProvider.getTracerProvider( sdktrace.WithBatcher(traceExporter), sdktrace.WithResource(res), ) ot.handler = otelhttp.NewHandler(http.HandlerFunc(ot.serveHTTP), ot.spanName, otelhttp.WithTracerProvider(tracerProvider), otelhttp.WithPropagators(ot.propagators), otelhttp.WithSpanNameFormatter(ot.spanNameFormatter), ) return ot, nil } // serveHTTP injects a tracing context and call the next handler. func (ot *openTelemetryWrapper) serveHTTP(w http.ResponseWriter, r *http.Request) { ctx := r.Context() ot.propagators.Inject(ctx, propagation.HeaderCarrier(r.Header)) spanCtx := trace.SpanContextFromContext(ctx) if spanCtx.IsValid() { traceID := spanCtx.TraceID().String() spanID := spanCtx.SpanID().String() // Add a trace_id placeholder, accessible via `{http.vars.trace_id}`. caddyhttp.SetVar(ctx, "trace_id", traceID) // Add a span_id placeholder, accessible via `{http.vars.span_id}`. caddyhttp.SetVar(ctx, "span_id", spanID) // Add the traceID and spanID to the log fields for the request. if extra, ok := ctx.Value(caddyhttp.ExtraLogFieldsCtxKey).(*caddyhttp.ExtraLogFields); ok { extra.Add(zap.String("traceID", traceID)) extra.Add(zap.String("spanID", spanID)) } } next := ctx.Value(nextCallCtxKey).(*nextCall) next.err = next.next.ServeHTTP(w, r) // Add custom span attributes to the current span span := trace.SpanFromContext(ctx) if span.IsRecording() && len(ot.spanAttributes) > 0 { replacer := ctx.Value(caddy.ReplacerCtxKey).(*caddy.Replacer) attributes := make([]attribute.KeyValue, 0, len(ot.spanAttributes)) for key, value := range ot.spanAttributes { // Allow placeholder replacement in attribute values replacedValue := replacer.ReplaceAll(value, "") attributes = append(attributes, attribute.String(key, replacedValue)) } span.SetAttributes(attributes...) } } // ServeHTTP propagates call to the by wrapped by `otelhttp` next handler. func (ot *openTelemetryWrapper) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { n := &nextCall{ next: next, err: nil, } ot.handler.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), nextCallCtxKey, n))) return n.err } // cleanup flush all remaining data and shutdown a tracerProvider func (ot *openTelemetryWrapper) cleanup(logger *zap.Logger) error { return globalTracerProvider.cleanupTracerProvider(logger) } // newResource creates a resource that describe current handler instance and merge it with a default attributes value. func (ot *openTelemetryWrapper) newResource( webEngineName, webEngineVersion string, ) (*resource.Resource, error) { return resource.Merge(resource.Default(), resource.NewSchemaless( semconv.WebEngineName(webEngineName), semconv.WebEngineVersion(webEngineVersion), )) } // spanNameFormatter performs the replacement of placeholders in the span name func (ot *openTelemetryWrapper) spanNameFormatter(operation string, r *http.Request) string { return r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer).ReplaceAll(operation, "") }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/tracing/tracerprovider_test.go
modules/caddyhttp/tracing/tracerprovider_test.go
package tracing import ( "testing" "go.uber.org/zap" ) func Test_tracersProvider_getTracerProvider(t *testing.T) { tp := tracerProvider{} tp.getTracerProvider() tp.getTracerProvider() if tp.tracerProvider == nil { t.Errorf("There should be tracer provider") } if tp.tracerProvidersCounter != 2 { t.Errorf("Tracer providers counter should equal to 2") } } func Test_tracersProvider_cleanupTracerProvider(t *testing.T) { tp := tracerProvider{} tp.getTracerProvider() tp.getTracerProvider() err := tp.cleanupTracerProvider(zap.NewNop()) if err != nil { t.Errorf("There should be no error: %v", err) } if tp.tracerProvider == nil { t.Errorf("There should be tracer provider") } if tp.tracerProvidersCounter != 1 { t.Errorf("Tracer providers counter should equal to 1") } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/tracing/module_test.go
modules/caddyhttp/tracing/module_test.go
package tracing import ( "context" "encoding/json" "errors" "net/http" "net/http/httptest" "strings" "testing" "go.opentelemetry.io/otel/sdk/trace" "go.opentelemetry.io/otel/sdk/trace/tracetest" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func TestTracing_UnmarshalCaddyfile(t *testing.T) { tests := []struct { name string spanName string spanAttributes map[string]string d *caddyfile.Dispenser wantErr bool }{ { name: "Full config", spanName: "my-span", spanAttributes: map[string]string{ "attr1": "value1", "attr2": "value2", }, d: caddyfile.NewTestDispenser(` tracing { span my-span span_attributes { attr1 value1 attr2 value2 } }`), wantErr: false, }, { name: "Only span name in the config", spanName: "my-span", d: caddyfile.NewTestDispenser(` tracing { span my-span }`), wantErr: false, }, { name: "Empty config", d: caddyfile.NewTestDispenser(` tracing { }`), wantErr: false, }, { name: "Only span attributes", spanAttributes: map[string]string{ "service.name": "my-service", "service.version": "1.0.0", }, d: caddyfile.NewTestDispenser(` tracing { span_attributes { service.name my-service service.version 1.0.0 } }`), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ot := &Tracing{} if err := ot.UnmarshalCaddyfile(tt.d); (err != nil) != tt.wantErr { t.Errorf("UnmarshalCaddyfile() error = %v, wantErrType %v", err, tt.wantErr) } if ot.SpanName != tt.spanName { t.Errorf("UnmarshalCaddyfile() SpanName = %v, want SpanName %v", ot.SpanName, tt.spanName) } if len(tt.spanAttributes) > 0 { if ot.SpanAttributes == nil { t.Errorf("UnmarshalCaddyfile() SpanAttributes is nil, expected %v", tt.spanAttributes) } else { for key, expectedValue := range tt.spanAttributes { if actualValue, exists := ot.SpanAttributes[key]; !exists { t.Errorf("UnmarshalCaddyfile() SpanAttributes missing key %v", key) } else if actualValue != expectedValue { t.Errorf("UnmarshalCaddyfile() SpanAttributes[%v] = %v, want %v", key, actualValue, expectedValue) } } } } }) } } func TestTracing_UnmarshalCaddyfile_Error(t *testing.T) { tests := []struct { name string d *caddyfile.Dispenser wantErr bool }{ { name: "Unknown parameter", d: caddyfile.NewTestDispenser(` tracing { foo bar }`), wantErr: true, }, { name: "Missed argument", d: caddyfile.NewTestDispenser(` tracing { span }`), wantErr: true, }, { name: "Span attributes missing value", d: caddyfile.NewTestDispenser(` tracing { span_attributes { key } }`), wantErr: true, }, { name: "Span attributes too many arguments", d: caddyfile.NewTestDispenser(` tracing { span_attributes { key value extra } }`), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ot := &Tracing{} if err := ot.UnmarshalCaddyfile(tt.d); (err != nil) != tt.wantErr { t.Errorf("UnmarshalCaddyfile() error = %v, wantErrType %v", err, tt.wantErr) } }) } } func TestTracing_ServeHTTP_Propagation_Without_Initial_Headers(t *testing.T) { ot := &Tracing{ SpanName: "mySpan", } req := createRequestWithContext("GET", "https://example.com/foo") w := httptest.NewRecorder() var handler caddyhttp.HandlerFunc = func(writer http.ResponseWriter, request *http.Request) error { traceparent := request.Header.Get("Traceparent") if traceparent == "" || strings.HasPrefix(traceparent, "00-00000000000000000000000000000000-0000000000000000") { t.Errorf("Invalid traceparent: %v", traceparent) } return nil } ctx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()}) defer cancel() if err := ot.Provision(ctx); err != nil { t.Errorf("Provision error: %v", err) t.FailNow() } if err := ot.ServeHTTP(w, req, handler); err != nil { t.Errorf("ServeHTTP error: %v", err) } } func TestTracing_ServeHTTP_Propagation_With_Initial_Headers(t *testing.T) { ot := &Tracing{ SpanName: "mySpan", } req := createRequestWithContext("GET", "https://example.com/foo") req.Header.Set("traceparent", "00-11111111111111111111111111111111-1111111111111111-01") w := httptest.NewRecorder() var handler caddyhttp.HandlerFunc = func(writer http.ResponseWriter, request *http.Request) error { traceparent := request.Header.Get("Traceparent") if !strings.HasPrefix(traceparent, "00-11111111111111111111111111111111") { t.Errorf("Invalid traceparent: %v", traceparent) } return nil } ctx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()}) defer cancel() if err := ot.Provision(ctx); err != nil { t.Errorf("Provision error: %v", err) t.FailNow() } if err := ot.ServeHTTP(w, req, handler); err != nil { t.Errorf("ServeHTTP error: %v", err) } } func TestTracing_ServeHTTP_Next_Error(t *testing.T) { ot := &Tracing{ SpanName: "mySpan", } req := createRequestWithContext("GET", "https://example.com/foo") w := httptest.NewRecorder() expectErr := errors.New("test error") var handler caddyhttp.HandlerFunc = func(writer http.ResponseWriter, request *http.Request) error { return expectErr } ctx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()}) defer cancel() if err := ot.Provision(ctx); err != nil { t.Errorf("Provision error: %v", err) t.FailNow() } if err := ot.ServeHTTP(w, req, handler); err == nil || !errors.Is(err, expectErr) { t.Errorf("expected error, got: %v", err) } } func TestTracing_JSON_Configuration(t *testing.T) { // Test that our struct correctly marshals to and from JSON original := &Tracing{ SpanName: "test-span", SpanAttributes: map[string]string{ "service.name": "test-service", "service.version": "1.0.0", "env": "test", }, } jsonData, err := json.Marshal(original) if err != nil { t.Fatalf("Failed to marshal to JSON: %v", err) } var unmarshaled Tracing if err := json.Unmarshal(jsonData, &unmarshaled); err != nil { t.Fatalf("Failed to unmarshal from JSON: %v", err) } if unmarshaled.SpanName != original.SpanName { t.Errorf("Expected SpanName %s, got %s", original.SpanName, unmarshaled.SpanName) } if len(unmarshaled.SpanAttributes) != len(original.SpanAttributes) { t.Errorf("Expected %d span attributes, got %d", len(original.SpanAttributes), len(unmarshaled.SpanAttributes)) } for key, expectedValue := range original.SpanAttributes { if actualValue, exists := unmarshaled.SpanAttributes[key]; !exists { t.Errorf("Expected span attribute %s to exist", key) } else if actualValue != expectedValue { t.Errorf("Expected span attribute %s = %s, got %s", key, expectedValue, actualValue) } } t.Logf("JSON representation: %s", string(jsonData)) } func TestTracing_OpenTelemetry_Span_Attributes(t *testing.T) { // Create an in-memory span recorder to capture actual span data spanRecorder := tracetest.NewSpanRecorder() provider := trace.NewTracerProvider( trace.WithSpanProcessor(spanRecorder), ) // Create our tracing module with span attributes that include placeholders ot := &Tracing{ SpanName: "test-span", SpanAttributes: map[string]string{ "static": "test-service", "request-placeholder": "{http.request.method}", "response-placeholder": "{http.response.header.X-Some-Header}", "mixed": "prefix-{http.request.method}-{http.response.header.X-Some-Header}", }, } // Create a specific request to test against req, _ := http.NewRequest("POST", "https://api.example.com/v1/users?id=123", nil) req.Host = "api.example.com" w := httptest.NewRecorder() // Set up the replacer repl := caddy.NewReplacer() ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl) ctx = context.WithValue(ctx, caddyhttp.VarsCtxKey, make(map[string]any)) req = req.WithContext(ctx) // Set up request placeholders repl.Set("http.request.method", req.Method) repl.Set("http.request.uri", req.URL.RequestURI()) // Handler to generate the response var handler caddyhttp.HandlerFunc = func(writer http.ResponseWriter, request *http.Request) error { writer.Header().Set("X-Some-Header", "some-value") writer.WriteHeader(200) // Make response headers available to replacer repl.Set("http.response.header.X-Some-Header", writer.Header().Get("X-Some-Header")) return nil } // Set up Caddy context caddyCtx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()}) defer cancel() // Override the global tracer provider with our test provider // This is a bit hacky but necessary to capture the actual spans originalProvider := globalTracerProvider globalTracerProvider = &tracerProvider{ tracerProvider: provider, tracerProvidersCounter: 1, // Simulate one user } defer func() { globalTracerProvider = originalProvider }() // Provision the tracing module if err := ot.Provision(caddyCtx); err != nil { t.Errorf("Provision error: %v", err) t.FailNow() } // Execute the request if err := ot.ServeHTTP(w, req, handler); err != nil { t.Errorf("ServeHTTP error: %v", err) } // Get the recorded spans spans := spanRecorder.Ended() if len(spans) == 0 { t.Fatal("Expected at least one span to be recorded") } // Find our span (should be the one with our test span name) var testSpan trace.ReadOnlySpan for _, span := range spans { if span.Name() == "test-span" { testSpan = span break } } if testSpan == nil { t.Fatal("Could not find test span in recorded spans") } // Verify that the span attributes were set correctly with placeholder replacement expectedAttributes := map[string]string{ "static": "test-service", "request-placeholder": "POST", "response-placeholder": "some-value", "mixed": "prefix-POST-some-value", } actualAttributes := make(map[string]string) for _, attr := range testSpan.Attributes() { actualAttributes[string(attr.Key)] = attr.Value.AsString() } for key, expectedValue := range expectedAttributes { if actualValue, exists := actualAttributes[key]; !exists { t.Errorf("Expected span attribute %s to be set", key) } else if actualValue != expectedValue { t.Errorf("Expected span attribute %s = %s, got %s", key, expectedValue, actualValue) } } t.Logf("Recorded span attributes: %+v", actualAttributes) } func createRequestWithContext(method string, url string) *http.Request { r, _ := http.NewRequest(method, url, nil) repl := caddy.NewReplacer() ctx := context.WithValue(r.Context(), caddy.ReplacerCtxKey, repl) r = r.WithContext(ctx) return r }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/tracing/module.go
modules/caddyhttp/tracing/module.go
package tracing import ( "fmt" "net/http" "go.uber.org/zap" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func init() { caddy.RegisterModule(Tracing{}) httpcaddyfile.RegisterHandlerDirective("tracing", parseCaddyfile) } // Tracing implements an HTTP handler that adds support for distributed tracing, // using OpenTelemetry. This module is responsible for the injection and // propagation of the trace context. Configure this module via environment // variables (see https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/sdk-environment-variables.md). // Some values can be overwritten in the configuration file. type Tracing struct { // SpanName is a span name. It should follow the naming guidelines here: // https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/api.md#span SpanName string `json:"span"` // SpanAttributes are custom key-value pairs to be added to spans SpanAttributes map[string]string `json:"span_attributes,omitempty"` // otel implements opentelemetry related logic. otel openTelemetryWrapper logger *zap.Logger } // CaddyModule returns the Caddy module information. func (Tracing) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.handlers.tracing", New: func() caddy.Module { return new(Tracing) }, } } // Provision implements caddy.Provisioner. func (ot *Tracing) Provision(ctx caddy.Context) error { ot.logger = ctx.Logger() var err error ot.otel, err = newOpenTelemetryWrapper(ctx, ot.SpanName, ot.SpanAttributes) return err } // Cleanup implements caddy.CleanerUpper and closes any idle connections. It // calls Shutdown method for a trace provider https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/sdk.md#shutdown. func (ot *Tracing) Cleanup() error { if err := ot.otel.cleanup(ot.logger); err != nil { return fmt.Errorf("tracerProvider shutdown: %w", err) } return nil } // ServeHTTP implements caddyhttp.MiddlewareHandler. func (ot *Tracing) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { return ot.otel.ServeHTTP(w, r, next) } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. Syntax: // // tracing { // [span <span_name>] // [span_attributes { // attr1 value1 // attr2 value2 // }] // } func (ot *Tracing) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { setParameter := func(d *caddyfile.Dispenser, val *string) error { if d.NextArg() { *val = d.Val() } else { return d.ArgErr() } if d.NextArg() { return d.ArgErr() } return nil } // paramsMap is a mapping between "string" parameter from the Caddyfile and its destination within the module paramsMap := map[string]*string{ "span": &ot.SpanName, } d.Next() // consume directive name if d.NextArg() { return d.ArgErr() } for d.NextBlock(0) { switch d.Val() { case "span_attributes": if ot.SpanAttributes == nil { ot.SpanAttributes = make(map[string]string) } for d.NextBlock(1) { key := d.Val() if !d.NextArg() { return d.ArgErr() } value := d.Val() if d.NextArg() { return d.ArgErr() } ot.SpanAttributes[key] = value } default: if dst, ok := paramsMap[d.Val()]; ok { if err := setParameter(d, dst); err != nil { return err } } else { return d.ArgErr() } } } return nil } func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) { var m Tracing err := m.UnmarshalCaddyfile(h.Dispenser) return &m, err } // Interface guards var ( _ caddy.Provisioner = (*Tracing)(nil) _ caddyhttp.MiddlewareHandler = (*Tracing)(nil) _ caddyfile.Unmarshaler = (*Tracing)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/tracing/tracer_test.go
modules/caddyhttp/tracing/tracer_test.go
package tracing import ( "context" "testing" "github.com/caddyserver/caddy/v2" ) func TestOpenTelemetryWrapper_newOpenTelemetryWrapper(t *testing.T) { ctx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()}) defer cancel() var otw openTelemetryWrapper var err error if otw, err = newOpenTelemetryWrapper(ctx, "", nil, ); err != nil { t.Errorf("newOpenTelemetryWrapper() error = %v", err) t.FailNow() } if otw.propagators == nil { t.Errorf("Propagators should not be empty") } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/tracing/tracerprovider.go
modules/caddyhttp/tracing/tracerprovider.go
package tracing import ( "context" "fmt" "sync" sdktrace "go.opentelemetry.io/otel/sdk/trace" "go.uber.org/zap" "go.uber.org/zap/zapcore" ) // globalTracerProvider stores global tracer provider and is responsible for graceful shutdown when nobody is using it. var globalTracerProvider = &tracerProvider{} type tracerProvider struct { mu sync.Mutex tracerProvider *sdktrace.TracerProvider tracerProvidersCounter int } // getTracerProvider create or return an existing global TracerProvider func (t *tracerProvider) getTracerProvider(opts ...sdktrace.TracerProviderOption) *sdktrace.TracerProvider { t.mu.Lock() defer t.mu.Unlock() t.tracerProvidersCounter++ if t.tracerProvider == nil { t.tracerProvider = sdktrace.NewTracerProvider( opts..., ) } return t.tracerProvider } // cleanupTracerProvider gracefully shutdown a TracerProvider func (t *tracerProvider) cleanupTracerProvider(logger *zap.Logger) error { t.mu.Lock() defer t.mu.Unlock() if t.tracerProvidersCounter > 0 { t.tracerProvidersCounter-- } if t.tracerProvidersCounter == 0 { if t.tracerProvider != nil { // tracerProvider.ForceFlush SHOULD be invoked according to https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/sdk.md#forceflush if err := t.tracerProvider.ForceFlush(context.Background()); err != nil { if c := logger.Check(zapcore.ErrorLevel, "forcing flush"); c != nil { c.Write(zap.Error(err)) } } // tracerProvider.Shutdown MUST be invoked according to https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/sdk.md#shutdown if err := t.tracerProvider.Shutdown(context.Background()); err != nil { return fmt.Errorf("tracerProvider shutdown error: %w", err) } } t.tracerProvider = nil } return nil }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/reverseproxy/addresses.go
modules/caddyhttp/reverseproxy/addresses.go
// Copyright 2015 Matthew Holt and The Caddy 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 reverseproxy import ( "fmt" "net" "net/url" "strings" "github.com/caddyserver/caddy/v2" ) type parsedAddr struct { network, scheme, host, port string valid bool } func (p parsedAddr) dialAddr() string { if !p.valid { return "" } // for simplest possible config, we only need to include // the network portion if the user specified one if p.network != "" { return caddy.JoinNetworkAddress(p.network, p.host, p.port) } // if the host is a placeholder, then we don't want to join with an empty port, // because that would just append an extra ':' at the end of the address. if p.port == "" && strings.Contains(p.host, "{") { return p.host } return net.JoinHostPort(p.host, p.port) } func (p parsedAddr) rangedPort() bool { return strings.Contains(p.port, "-") } func (p parsedAddr) replaceablePort() bool { return strings.Contains(p.port, "{") && strings.Contains(p.port, "}") } func (p parsedAddr) isUnix() bool { return caddy.IsUnixNetwork(p.network) } // parseUpstreamDialAddress parses configuration inputs for // the dial address, including support for a scheme in front // as a shortcut for the port number, and a network type, // for example 'unix' to dial a unix socket. func parseUpstreamDialAddress(upstreamAddr string) (parsedAddr, error) { var network, scheme, host, port string if strings.Contains(upstreamAddr, "://") { // we get a parsing error if a placeholder is specified // so we return a more user-friendly error message instead // to explain what to do instead if strings.Contains(upstreamAddr, "{") { return parsedAddr{}, fmt.Errorf("due to parsing difficulties, placeholders are not allowed when an upstream address contains a scheme") } toURL, err := url.Parse(upstreamAddr) if err != nil { // if the error seems to be due to a port range, // try to replace the port range with a dummy // single port so that url.Parse() will succeed if strings.Contains(err.Error(), "invalid port") && strings.Contains(err.Error(), "-") { index := strings.LastIndex(upstreamAddr, ":") if index == -1 { return parsedAddr{}, fmt.Errorf("parsing upstream URL: %v", err) } portRange := upstreamAddr[index+1:] if strings.Count(portRange, "-") != 1 { return parsedAddr{}, fmt.Errorf("parsing upstream URL: parse \"%v\": port range invalid: %v", upstreamAddr, portRange) } toURL, err = url.Parse(strings.ReplaceAll(upstreamAddr, portRange, "0")) if err != nil { return parsedAddr{}, fmt.Errorf("parsing upstream URL: %v", err) } port = portRange } else { return parsedAddr{}, fmt.Errorf("parsing upstream URL: %v", err) } } if port == "" { port = toURL.Port() } // there is currently no way to perform a URL rewrite between choosing // a backend and proxying to it, so we cannot allow extra components // in backend URLs if toURL.Path != "" || toURL.RawQuery != "" || toURL.Fragment != "" { return parsedAddr{}, fmt.Errorf("for now, URLs for proxy upstreams only support scheme, host, and port components") } // ensure the port and scheme aren't in conflict if toURL.Scheme == "http" && port == "443" { return parsedAddr{}, fmt.Errorf("upstream address has conflicting scheme (http://) and port (:443, the HTTPS port)") } if toURL.Scheme == "https" && port == "80" { return parsedAddr{}, fmt.Errorf("upstream address has conflicting scheme (https://) and port (:80, the HTTP port)") } if toURL.Scheme == "h2c" && port == "443" { return parsedAddr{}, fmt.Errorf("upstream address has conflicting scheme (h2c://) and port (:443, the HTTPS port)") } // if port is missing, attempt to infer from scheme if port == "" { switch toURL.Scheme { case "", "http", "h2c": port = "80" case "https": port = "443" } } scheme, host = toURL.Scheme, toURL.Hostname() } else { var err error network, host, port, err = caddy.SplitNetworkAddress(upstreamAddr) if err != nil { host = upstreamAddr } // we can assume a port if only a hostname is specified, but use of a // placeholder without a port likely means a port will be filled in if port == "" && !strings.Contains(host, "{") && !caddy.IsUnixNetwork(network) && !caddy.IsFdNetwork(network) { port = "80" } } // special case network to support both unix and h2c at the same time if network == "unix+h2c" { network = "unix" scheme = "h2c" } return parsedAddr{network, scheme, host, port, true}, nil }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/reverseproxy/admin.go
modules/caddyhttp/reverseproxy/admin.go
// Copyright 2015 Matthew Holt and The Caddy 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 reverseproxy import ( "encoding/json" "fmt" "net/http" "github.com/caddyserver/caddy/v2" ) func init() { caddy.RegisterModule(adminUpstreams{}) } // adminUpstreams is a module that provides the // /reverse_proxy/upstreams endpoint for the Caddy admin // API. This allows for checking the health of configured // reverse proxy upstreams in the pool. type adminUpstreams struct{} // upstreamStatus holds the status of a particular upstream type upstreamStatus struct { Address string `json:"address"` NumRequests int `json:"num_requests"` Fails int `json:"fails"` } // CaddyModule returns the Caddy module information. func (adminUpstreams) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "admin.api.reverse_proxy", New: func() caddy.Module { return new(adminUpstreams) }, } } // Routes returns a route for the /reverse_proxy/upstreams endpoint. func (al adminUpstreams) Routes() []caddy.AdminRoute { return []caddy.AdminRoute{ { Pattern: "/reverse_proxy/upstreams", Handler: caddy.AdminHandlerFunc(al.handleUpstreams), }, } } // handleUpstreams reports the status of the reverse proxy // upstream pool. func (adminUpstreams) handleUpstreams(w http.ResponseWriter, r *http.Request) error { if r.Method != http.MethodGet { return caddy.APIError{ HTTPStatus: http.StatusMethodNotAllowed, Err: fmt.Errorf("method not allowed"), } } // Prep for a JSON response w.Header().Set("Content-Type", "application/json") enc := json.NewEncoder(w) // Collect the results to respond with results := []upstreamStatus{} // Iterate over the upstream pool (needs to be fast) var rangeErr error hosts.Range(func(key, val any) bool { address, ok := key.(string) if !ok { rangeErr = caddy.APIError{ HTTPStatus: http.StatusInternalServerError, Err: fmt.Errorf("could not type assert upstream address"), } return false } upstream, ok := val.(*Host) if !ok { rangeErr = caddy.APIError{ HTTPStatus: http.StatusInternalServerError, Err: fmt.Errorf("could not type assert upstream struct"), } return false } results = append(results, upstreamStatus{ Address: address, NumRequests: upstream.NumRequests(), Fails: upstream.Fails(), }) return true }) // If an error happened during the range, return it if rangeErr != nil { return rangeErr } err := enc.Encode(results) if err != nil { return caddy.APIError{ HTTPStatus: http.StatusInternalServerError, Err: err, } } return nil }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/reverseproxy/metrics.go
modules/caddyhttp/reverseproxy/metrics.go
package reverseproxy import ( "errors" "runtime/debug" "sync" "time" "github.com/prometheus/client_golang/prometheus" "go.uber.org/zap" "go.uber.org/zap/zapcore" "github.com/caddyserver/caddy/v2" ) var reverseProxyMetrics = struct { once sync.Once upstreamsHealthy *prometheus.GaugeVec logger *zap.Logger }{} func initReverseProxyMetrics(handler *Handler, registry *prometheus.Registry) { const ns, sub = "caddy", "reverse_proxy" upstreamsLabels := []string{"upstream"} reverseProxyMetrics.once.Do(func() { reverseProxyMetrics.upstreamsHealthy = prometheus.NewGaugeVec(prometheus.GaugeOpts{ Namespace: ns, Subsystem: sub, Name: "upstreams_healthy", Help: "Health status of reverse proxy upstreams.", }, upstreamsLabels) }) // duplicate registration could happen if multiple sites with reverse proxy are configured; so ignore the error because // there's no good way to capture having multiple sites with reverse proxy. If this happens, the metrics will be // registered twice, but the second registration will be ignored. if err := registry.Register(reverseProxyMetrics.upstreamsHealthy); err != nil && !errors.Is(err, prometheus.AlreadyRegisteredError{ ExistingCollector: reverseProxyMetrics.upstreamsHealthy, NewCollector: reverseProxyMetrics.upstreamsHealthy, }) { panic(err) } reverseProxyMetrics.logger = handler.logger.Named("reverse_proxy.metrics") } type metricsUpstreamsHealthyUpdater struct { handler *Handler } func newMetricsUpstreamsHealthyUpdater(handler *Handler, ctx caddy.Context) *metricsUpstreamsHealthyUpdater { initReverseProxyMetrics(handler, ctx.GetMetricsRegistry()) reverseProxyMetrics.upstreamsHealthy.Reset() return &metricsUpstreamsHealthyUpdater{handler} } func (m *metricsUpstreamsHealthyUpdater) init() { go func() { defer func() { if err := recover(); err != nil { if c := reverseProxyMetrics.logger.Check(zapcore.ErrorLevel, "upstreams healthy metrics updater panicked"); c != nil { c.Write( zap.Any("error", err), zap.ByteString("stack", debug.Stack()), ) } } }() m.update() ticker := time.NewTicker(10 * time.Second) for { select { case <-ticker.C: m.update() case <-m.handler.ctx.Done(): ticker.Stop() return } } }() } func (m *metricsUpstreamsHealthyUpdater) update() { for _, upstream := range m.handler.Upstreams { labels := prometheus.Labels{"upstream": upstream.Dial} gaugeValue := 0.0 if upstream.Healthy() { gaugeValue = 1.0 } reverseProxyMetrics.upstreamsHealthy.With(labels).Set(gaugeValue) } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/reverseproxy/healthchecks.go
modules/caddyhttp/reverseproxy/healthchecks.go
// Copyright 2015 Matthew Holt and The Caddy 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 reverseproxy import ( "context" "fmt" "io" "net" "net/http" "net/url" "regexp" "runtime/debug" "strconv" "strings" "time" "go.uber.org/zap" "go.uber.org/zap/zapcore" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) // HealthChecks configures active and passive health checks. type HealthChecks struct { // Active health checks run in the background on a timer. To // minimally enable active health checks, set either path or // port (or both). Note that active health check status // (healthy/unhealthy) is stored per-proxy-handler, not // globally; this allows different handlers to use different // criteria to decide what defines a healthy backend. // // Active health checks do not run for dynamic upstreams. Active *ActiveHealthChecks `json:"active,omitempty"` // Passive health checks monitor proxied requests for errors or timeouts. // To minimally enable passive health checks, specify at least an empty // config object with fail_duration > 0. Passive health check state is // shared (stored globally), so a failure from one handler will be counted // by all handlers; but the tolerances or standards for what defines // healthy/unhealthy backends is configured per-proxy-handler. // // Passive health checks technically do operate on dynamic upstreams, // but are only effective for very busy proxies where the list of // upstreams is mostly stable. This is because the shared/global // state of upstreams is cleaned up when the upstreams are no longer // used. Since dynamic upstreams are allocated dynamically at each // request (specifically, each iteration of the proxy loop per request), // they are also cleaned up after every request. Thus, if there is a // moment when no requests are actively referring to a particular // upstream host, the passive health check state will be reset because // it will be garbage-collected. It is usually better for the dynamic // upstream module to only return healthy, available backends instead. Passive *PassiveHealthChecks `json:"passive,omitempty"` } // ActiveHealthChecks holds configuration related to active // health checks (that is, health checks which occur in a // background goroutine independently). type ActiveHealthChecks struct { // Deprecated: Use 'uri' instead. This field will be removed. TODO: remove this field Path string `json:"path,omitempty"` // The URI (path and query) to use for health checks URI string `json:"uri,omitempty"` // The host:port to use (if different from the upstream's dial address) // for health checks. This should be used in tandem with `health_header` and // `{http.reverse_proxy.active.target_upstream}`. This can be helpful when // creating an intermediate service to do a more thorough health check. // If upstream is set, the active health check port is ignored. Upstream string `json:"upstream,omitempty"` // The port to use (if different from the upstream's dial // address) for health checks. If active upstream is set, // this value is ignored. Port int `json:"port,omitempty"` // HTTP headers to set on health check requests. Headers http.Header `json:"headers,omitempty"` // The HTTP method to use for health checks (default "GET"). Method string `json:"method,omitempty"` // The body to send with the health check request. Body string `json:"body,omitempty"` // Whether to follow HTTP redirects in response to active health checks (default off). FollowRedirects bool `json:"follow_redirects,omitempty"` // How frequently to perform active health checks (default 30s). Interval caddy.Duration `json:"interval,omitempty"` // How long to wait for a response from a backend before // considering it unhealthy (default 5s). Timeout caddy.Duration `json:"timeout,omitempty"` // Number of consecutive health check passes before marking // a previously unhealthy backend as healthy again (default 1). Passes int `json:"passes,omitempty"` // Number of consecutive health check failures before marking // a previously healthy backend as unhealthy (default 1). Fails int `json:"fails,omitempty"` // The maximum response body to download from the backend // during a health check. MaxSize int64 `json:"max_size,omitempty"` // The HTTP status code to expect from a healthy backend. ExpectStatus int `json:"expect_status,omitempty"` // A regular expression against which to match the response // body of a healthy backend. ExpectBody string `json:"expect_body,omitempty"` uri *url.URL httpClient *http.Client bodyRegexp *regexp.Regexp logger *zap.Logger } // Provision ensures that a is set up properly before use. func (a *ActiveHealthChecks) Provision(ctx caddy.Context, h *Handler) error { if !a.IsEnabled() { return nil } // Canonicalize the header keys ahead of time, since // JSON unmarshaled headers may be incorrect cleaned := http.Header{} for key, hdrs := range a.Headers { for _, val := range hdrs { cleaned.Add(key, val) } } a.Headers = cleaned // If Method is not set, default to GET if a.Method == "" { a.Method = http.MethodGet } h.HealthChecks.Active.logger = h.logger.Named("health_checker.active") timeout := time.Duration(a.Timeout) if timeout == 0 { timeout = 5 * time.Second } if a.Path != "" { a.logger.Warn("the 'path' option is deprecated, please use 'uri' instead!") } // parse the URI string (supports path and query) if a.URI != "" { parsedURI, err := url.Parse(a.URI) if err != nil { return err } a.uri = parsedURI } a.httpClient = &http.Client{ Timeout: timeout, Transport: h.Transport, CheckRedirect: func(req *http.Request, via []*http.Request) error { if !a.FollowRedirects { return http.ErrUseLastResponse } return nil }, } for _, upstream := range h.Upstreams { // if there's an alternative upstream for health-check provided in the config, // then use it, otherwise use the upstream's dial address. if upstream is used, // then the port is ignored. if a.Upstream != "" { upstream.activeHealthCheckUpstream = a.Upstream } else if a.Port != 0 { // if there's an alternative port for health-check provided in the config, // then use it, otherwise use the port of upstream. upstream.activeHealthCheckPort = a.Port } } if a.Interval == 0 { a.Interval = caddy.Duration(30 * time.Second) } if a.ExpectBody != "" { var err error a.bodyRegexp, err = regexp.Compile(a.ExpectBody) if err != nil { return fmt.Errorf("expect_body: compiling regular expression: %v", err) } } if a.Passes < 1 { a.Passes = 1 } if a.Fails < 1 { a.Fails = 1 } return nil } // IsEnabled checks if the active health checks have // the minimum config necessary to be enabled. func (a *ActiveHealthChecks) IsEnabled() bool { return a.Path != "" || a.URI != "" || a.Port != 0 } // PassiveHealthChecks holds configuration related to passive // health checks (that is, health checks which occur during // the normal flow of request proxying). type PassiveHealthChecks struct { // How long to remember a failed request to a backend. A duration > 0 // enables passive health checking. Default is 0. FailDuration caddy.Duration `json:"fail_duration,omitempty"` // The number of failed requests within the FailDuration window to // consider a backend as "down". Must be >= 1; default is 1. Requires // that FailDuration be > 0. MaxFails int `json:"max_fails,omitempty"` // Limits the number of simultaneous requests to a backend by // marking the backend as "down" if it has this many concurrent // requests or more. UnhealthyRequestCount int `json:"unhealthy_request_count,omitempty"` // Count the request as failed if the response comes back with // one of these status codes. UnhealthyStatus []int `json:"unhealthy_status,omitempty"` // Count the request as failed if the response takes at least this // long to receive. UnhealthyLatency caddy.Duration `json:"unhealthy_latency,omitempty"` logger *zap.Logger } // CircuitBreaker is a type that can act as an early-warning // system for the health checker when backends are getting // overloaded. This interface is still experimental and is // subject to change. type CircuitBreaker interface { OK() bool RecordMetric(statusCode int, latency time.Duration) } // activeHealthChecker runs active health checks on a // regular basis and blocks until // h.HealthChecks.Active.stopChan is closed. func (h *Handler) activeHealthChecker() { defer func() { if err := recover(); err != nil { if c := h.HealthChecks.Active.logger.Check(zapcore.ErrorLevel, "active health checker panicked"); c != nil { c.Write( zap.Any("error", err), zap.ByteString("stack", debug.Stack()), ) } } }() ticker := time.NewTicker(time.Duration(h.HealthChecks.Active.Interval)) h.doActiveHealthCheckForAllHosts() for { select { case <-ticker.C: h.doActiveHealthCheckForAllHosts() case <-h.ctx.Done(): ticker.Stop() return } } } // doActiveHealthCheckForAllHosts immediately performs a // health checks for all upstream hosts configured by h. func (h *Handler) doActiveHealthCheckForAllHosts() { for _, upstream := range h.Upstreams { go func(upstream *Upstream) { defer func() { if err := recover(); err != nil { if c := h.HealthChecks.Active.logger.Check(zapcore.ErrorLevel, "active health checker panicked"); c != nil { c.Write( zap.Any("error", err), zap.ByteString("stack", debug.Stack()), ) } } }() repl := caddy.NewReplacer() networkAddr, err := repl.ReplaceOrErr(upstream.Dial, true, true) if err != nil { if c := h.HealthChecks.Active.logger.Check(zapcore.ErrorLevel, "invalid use of placeholders in dial address for active health checks"); c != nil { c.Write( zap.String("address", networkAddr), zap.Error(err), ) } return } addr, err := caddy.ParseNetworkAddress(networkAddr) if err != nil { if c := h.HealthChecks.Active.logger.Check(zapcore.ErrorLevel, "bad network address"); c != nil { c.Write( zap.String("address", networkAddr), zap.Error(err), ) } return } if hcp := uint(upstream.activeHealthCheckPort); hcp != 0 { if addr.IsUnixNetwork() || addr.IsFdNetwork() { addr.Network = "tcp" // I guess we just assume TCP since we are using a port?? } addr.StartPort, addr.EndPort = hcp, hcp } if addr.PortRangeSize() != 1 { if c := h.HealthChecks.Active.logger.Check(zapcore.ErrorLevel, "multiple addresses (upstream must map to only one address)"); c != nil { c.Write( zap.String("address", networkAddr), ) } return } hostAddr := addr.JoinHostPort(0) if addr.IsUnixNetwork() || addr.IsFdNetwork() { // this will be used as the Host portion of a http.Request URL, and // paths to socket files would produce an error when creating URL, // so use a fake Host value instead; unix sockets are usually local hostAddr = "localhost" } // Fill in the dial info for the upstream // If the upstream is set, use that instead dialInfoUpstream := upstream if h.HealthChecks.Active.Upstream != "" { dialInfoUpstream = &Upstream{ Dial: h.HealthChecks.Active.Upstream, } } dialInfo, _ := dialInfoUpstream.fillDialInfo(repl) err = h.doActiveHealthCheck(dialInfo, hostAddr, networkAddr, upstream) if err != nil { if c := h.HealthChecks.Active.logger.Check(zapcore.ErrorLevel, "active health check failed"); c != nil { c.Write( zap.String("address", hostAddr), zap.Error(err), ) } } }(upstream) } } // doActiveHealthCheck performs a health check to upstream which // can be reached at address hostAddr. The actual address for // the request will be built according to active health checker // config. The health status of the host will be updated // according to whether it passes the health check. An error is // returned only if the health check fails to occur or if marking // the host's health status fails. func (h *Handler) doActiveHealthCheck(dialInfo DialInfo, hostAddr string, networkAddr string, upstream *Upstream) error { // create the URL for the request that acts as a health check u := &url.URL{ Scheme: "http", Host: hostAddr, } // split the host and port if possible, override the port if configured host, port, err := net.SplitHostPort(hostAddr) if err != nil { host = hostAddr } // ignore active health check port if active upstream is provided as the // active upstream already contains the replacement port if h.HealthChecks.Active.Upstream != "" { u.Host = h.HealthChecks.Active.Upstream } else if h.HealthChecks.Active.Port != 0 { port := strconv.Itoa(h.HealthChecks.Active.Port) u.Host = net.JoinHostPort(host, port) } // override health check schemes if applicable if hcsot, ok := h.Transport.(HealthCheckSchemeOverriderTransport); ok { hcsot.OverrideHealthCheckScheme(u, port) } // if we have a provisioned uri, use that, otherwise use // the deprecated Path option if h.HealthChecks.Active.uri != nil { u.Path = h.HealthChecks.Active.uri.Path u.RawQuery = h.HealthChecks.Active.uri.RawQuery } else { u.Path = h.HealthChecks.Active.Path } // replacer used for both body and headers. Only globals (env vars, system info, etc.) are available repl := caddy.NewReplacer() // if body is provided, create a reader for it, otherwise nil var requestBody io.Reader if h.HealthChecks.Active.Body != "" { // set body, using replacer requestBody = strings.NewReader(repl.ReplaceAll(h.HealthChecks.Active.Body, "")) } // attach dialing information to this request, as well as context values that // may be expected by handlers of this request ctx := h.ctx.Context ctx = context.WithValue(ctx, caddy.ReplacerCtxKey, caddy.NewReplacer()) ctx = context.WithValue(ctx, caddyhttp.VarsCtxKey, map[string]any{ dialInfoVarKey: dialInfo, }) req, err := http.NewRequestWithContext(ctx, h.HealthChecks.Active.Method, u.String(), requestBody) if err != nil { return fmt.Errorf("making request: %v", err) } ctx = context.WithValue(ctx, caddyhttp.OriginalRequestCtxKey, *req) req = req.WithContext(ctx) // set headers, using replacer repl.Set("http.reverse_proxy.active.target_upstream", networkAddr) for key, vals := range h.HealthChecks.Active.Headers { key = repl.ReplaceAll(key, "") if key == "Host" { req.Host = repl.ReplaceAll(h.HealthChecks.Active.Headers.Get(key), "") continue } for _, val := range vals { req.Header.Add(key, repl.ReplaceKnown(val, "")) } } markUnhealthy := func() { // increment failures and then check if it has reached the threshold to mark unhealthy err := upstream.Host.countHealthFail(1) if err != nil { if c := h.HealthChecks.Active.logger.Check(zapcore.ErrorLevel, "could not count active health failure"); c != nil { c.Write( zap.String("host", upstream.Dial), zap.Error(err), ) } return } if upstream.Host.activeHealthFails() >= h.HealthChecks.Active.Fails { // dispatch an event that the host newly became unhealthy if upstream.setHealthy(false) { h.events.Emit(h.ctx, "unhealthy", map[string]any{"host": hostAddr}) upstream.Host.resetHealth() } } } markHealthy := func() { // increment passes and then check if it has reached the threshold to be healthy err := upstream.countHealthPass(1) if err != nil { if c := h.HealthChecks.Active.logger.Check(zapcore.ErrorLevel, "could not count active health pass"); c != nil { c.Write( zap.String("host", upstream.Dial), zap.Error(err), ) } return } if upstream.Host.activeHealthPasses() >= h.HealthChecks.Active.Passes { if upstream.setHealthy(true) { if c := h.HealthChecks.Active.logger.Check(zapcore.InfoLevel, "host is up"); c != nil { c.Write(zap.String("host", hostAddr)) } h.events.Emit(h.ctx, "healthy", map[string]any{"host": hostAddr}) upstream.Host.resetHealth() } } } // do the request, being careful to tame the response body resp, err := h.HealthChecks.Active.httpClient.Do(req) if err != nil { if c := h.HealthChecks.Active.logger.Check(zapcore.InfoLevel, "HTTP request failed"); c != nil { c.Write( zap.String("host", hostAddr), zap.Error(err), ) } markUnhealthy() return nil } var body io.Reader = resp.Body if h.HealthChecks.Active.MaxSize > 0 { body = io.LimitReader(body, h.HealthChecks.Active.MaxSize) } defer func() { // drain any remaining body so connection could be re-used _, _ = io.Copy(io.Discard, body) resp.Body.Close() }() // if status code is outside criteria, mark down if h.HealthChecks.Active.ExpectStatus > 0 { if !caddyhttp.StatusCodeMatches(resp.StatusCode, h.HealthChecks.Active.ExpectStatus) { if c := h.HealthChecks.Active.logger.Check(zapcore.InfoLevel, "unexpected status code"); c != nil { c.Write( zap.Int("status_code", resp.StatusCode), zap.String("host", hostAddr), ) } markUnhealthy() return nil } } else if resp.StatusCode < 200 || resp.StatusCode >= 300 { if c := h.HealthChecks.Active.logger.Check(zapcore.InfoLevel, "status code out of tolerances"); c != nil { c.Write( zap.Int("status_code", resp.StatusCode), zap.String("host", hostAddr), ) } markUnhealthy() return nil } // if body does not match regex, mark down if h.HealthChecks.Active.bodyRegexp != nil { bodyBytes, err := io.ReadAll(body) if err != nil { if c := h.HealthChecks.Active.logger.Check(zapcore.InfoLevel, "failed to read response body"); c != nil { c.Write( zap.String("host", hostAddr), zap.Error(err), ) } markUnhealthy() return nil } if !h.HealthChecks.Active.bodyRegexp.Match(bodyBytes) { if c := h.HealthChecks.Active.logger.Check(zapcore.InfoLevel, "response body failed expectations"); c != nil { c.Write( zap.String("host", hostAddr), ) } markUnhealthy() return nil } } // passed health check parameters, so mark as healthy markHealthy() return nil } // countFailure is used with passive health checks. It // remembers 1 failure for upstream for the configured // duration. If passive health checks are disabled or // failure expiry is 0, this is a no-op. func (h *Handler) countFailure(upstream *Upstream) { // only count failures if passive health checking is enabled // and if failures are configured have a non-zero expiry if h.HealthChecks == nil || h.HealthChecks.Passive == nil { return } failDuration := time.Duration(h.HealthChecks.Passive.FailDuration) if failDuration == 0 { return } // count failure immediately err := upstream.Host.countFail(1) if err != nil { if c := h.HealthChecks.Active.logger.Check(zapcore.ErrorLevel, "could not count failure"); c != nil { c.Write( zap.String("host", upstream.Dial), zap.Error(err), ) } return } // forget it later go func(host *Host, failDuration time.Duration) { defer func() { if err := recover(); err != nil { if c := h.HealthChecks.Active.logger.Check(zapcore.ErrorLevel, "passive health check failure forgetter panicked"); c != nil { c.Write( zap.Any("error", err), zap.ByteString("stack", debug.Stack()), ) } } }() timer := time.NewTimer(failDuration) select { case <-h.ctx.Done(): if !timer.Stop() { <-timer.C } case <-timer.C: } err := host.countFail(-1) if err != nil { if c := h.HealthChecks.Active.logger.Check(zapcore.ErrorLevel, "could not forget failure"); c != nil { c.Write( zap.String("host", upstream.Dial), zap.Error(err), ) } } }(upstream.Host, failDuration) }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/reverseproxy/httptransport_test.go
modules/caddyhttp/reverseproxy/httptransport_test.go
package reverseproxy import ( "encoding/json" "fmt" "reflect" "testing" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func TestHTTPTransportUnmarshalCaddyFileWithCaPools(t *testing.T) { const test_der_1 = `MIIDSzCCAjOgAwIBAgIUfIRObjWNUA4jxQ/0x8BOCvE2Vw4wDQYJKoZIhvcNAQELBQAwFjEUMBIGA1UEAwwLRWFzeS1SU0EgQ0EwHhcNMTkwODI4MTYyNTU5WhcNMjkwODI1MTYyNTU5WjAWMRQwEgYDVQQDDAtFYXN5LVJTQSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK5m5elxhQfMp/3aVJ4JnpN9PUSz6LlP6LePAPFU7gqohVVFVtDkChJAG3FNkNQNlieVTja/bgH9IcC6oKbROwdY1h0MvNV8AHHigvl03WuJD8g2ReVFXXwsnrPmKXCFzQyMI6TYk3m2gYrXsZOU1GLnfMRC3KAMRgE2F45twOs9hqG169YJ6mM2eQjzjCHWI6S2/iUYvYxRkCOlYUbLsMD/AhgAf1plzg6LPqNxtdlwxZnA0ytgkmhK67HtzJu0+ovUCsMv0RwcMhsEo9T8nyFAGt9XLZ63X5WpBCTUApaAUhnG0XnerjmUWb6eUWw4zev54sEfY5F3x002iQaW6cECAwEAAaOBkDCBjTAdBgNVHQ4EFgQU4CBUbZsS2GaNIkGRz/cBsD5ivjswUQYDVR0jBEowSIAU4CBUbZsS2GaNIkGRz/cBsD5ivjuhGqQYMBYxFDASBgNVBAMMC0Vhc3ktUlNBIENBghR8hE5uNY1QDiPFD/THwE4K8TZXDjAMBgNVHRMEBTADAQH/MAsGA1UdDwQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAQEAKB3V4HIzoiO/Ch6WMj9bLJ2FGbpkMrcb/Eq01hT5zcfKD66lVS1MlK+cRL446Z2b2KDP1oFyVs+qmrmtdwrWgD+nfe2sBmmIHo9m9KygMkEOfG3MghGTEcS+0cTKEcoHYWYyOqQh6jnedXY8Cdm4GM1hAc9MiL3/sqV8YCVSLNnkoNysmr06/rZ0MCUZPGUtRmfd0heWhrfzAKw2HLgX+RAmpOE2MZqWcjvqKGyaRiaZks4nJkP6521aC2Lgp0HhCz1j8/uQ5ldoDszCnu/iro0NAsNtudTMD+YoLQxLqdleIh6CW+illc2VdXwj7mn6J04yns9jfE2jRjW/yTLFuQ==` type args struct { d *caddyfile.Dispenser } tests := []struct { name string args args expectedTLSConfig TLSConfig wantErr bool }{ { name: "tls_trust_pool without a module argument returns an error", args: args{ d: caddyfile.NewTestDispenser( `http { tls_trust_pool }`), }, wantErr: true, }, { name: "providing both 'tls_trust_pool' and 'tls_trusted_ca_certs' returns an error", args: args{ d: caddyfile.NewTestDispenser(fmt.Sprintf( `http { tls_trust_pool inline %s tls_trusted_ca_certs %s }`, test_der_1, test_der_1)), }, wantErr: true, }, { name: "setting 'tls_trust_pool' and 'tls_trusted_ca_certs' produces an error", args: args{ d: caddyfile.NewTestDispenser(fmt.Sprintf( `http { tls_trust_pool inline { trust_der %s } tls_trusted_ca_certs %s }`, test_der_1, test_der_1)), }, wantErr: true, }, { name: "using 'inline' tls_trust_pool loads the module successfully", args: args{ d: caddyfile.NewTestDispenser(fmt.Sprintf( `http { tls_trust_pool inline { trust_der %s } } `, test_der_1)), }, expectedTLSConfig: TLSConfig{CARaw: json.RawMessage(fmt.Sprintf(`{"provider":"inline","trusted_ca_certs":["%s"]}`, test_der_1))}, }, { name: "setting 'tls_trusted_ca_certs' and 'tls_trust_pool' produces an error", args: args{ d: caddyfile.NewTestDispenser(fmt.Sprintf( `http { tls_trusted_ca_certs %s tls_trust_pool inline { trust_der %s } }`, test_der_1, test_der_1)), }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ht := &HTTPTransport{} if err := ht.UnmarshalCaddyfile(tt.args.d); (err != nil) != tt.wantErr { t.Errorf("HTTPTransport.UnmarshalCaddyfile() error = %v, wantErr %v", err, tt.wantErr) return } if !tt.wantErr && !reflect.DeepEqual(&tt.expectedTLSConfig, ht.TLS) { t.Errorf("HTTPTransport.UnmarshalCaddyfile() = %v, want %v", ht, tt.expectedTLSConfig) } }) } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/reverseproxy/selectionpolicies.go
modules/caddyhttp/reverseproxy/selectionpolicies.go
// Copyright 2015 Matthew Holt and The Caddy 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 reverseproxy import ( "crypto/hmac" "crypto/sha256" "encoding/hex" "encoding/json" "fmt" weakrand "math/rand" "net" "net/http" "strconv" "strings" "sync/atomic" "time" "github.com/cespare/xxhash/v2" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func init() { caddy.RegisterModule(RandomSelection{}) caddy.RegisterModule(RandomChoiceSelection{}) caddy.RegisterModule(LeastConnSelection{}) caddy.RegisterModule(RoundRobinSelection{}) caddy.RegisterModule(WeightedRoundRobinSelection{}) caddy.RegisterModule(FirstSelection{}) caddy.RegisterModule(IPHashSelection{}) caddy.RegisterModule(ClientIPHashSelection{}) caddy.RegisterModule(URIHashSelection{}) caddy.RegisterModule(QueryHashSelection{}) caddy.RegisterModule(HeaderHashSelection{}) caddy.RegisterModule(CookieHashSelection{}) } // RandomSelection is a policy that selects // an available host at random. type RandomSelection struct{} // CaddyModule returns the Caddy module information. func (RandomSelection) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.reverse_proxy.selection_policies.random", New: func() caddy.Module { return new(RandomSelection) }, } } // Select returns an available host, if any. func (r RandomSelection) Select(pool UpstreamPool, request *http.Request, _ http.ResponseWriter) *Upstream { return selectRandomHost(pool) } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. func (r *RandomSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume policy name if d.NextArg() { return d.ArgErr() } return nil } // WeightedRoundRobinSelection is a policy that selects // a host based on weighted round-robin ordering. type WeightedRoundRobinSelection struct { // The weight of each upstream in order, // corresponding with the list of upstreams configured. Weights []int `json:"weights,omitempty"` index uint32 totalWeight int } // CaddyModule returns the Caddy module information. func (WeightedRoundRobinSelection) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.reverse_proxy.selection_policies.weighted_round_robin", New: func() caddy.Module { return new(WeightedRoundRobinSelection) }, } } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. func (r *WeightedRoundRobinSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume policy name args := d.RemainingArgs() if len(args) == 0 { return d.ArgErr() } for _, weight := range args { weightInt, err := strconv.Atoi(weight) if err != nil { return d.Errf("invalid weight value '%s': %v", weight, err) } if weightInt < 0 { return d.Errf("invalid weight value '%s': weight should be non-negative", weight) } r.Weights = append(r.Weights, weightInt) } return nil } // Provision sets up r. func (r *WeightedRoundRobinSelection) Provision(ctx caddy.Context) error { for _, weight := range r.Weights { r.totalWeight += weight } return nil } // Select returns an available host, if any. func (r *WeightedRoundRobinSelection) Select(pool UpstreamPool, _ *http.Request, _ http.ResponseWriter) *Upstream { if len(pool) == 0 { return nil } if len(r.Weights) < 2 { return pool[0] } var index, totalWeight int var weights []int for _, w := range r.Weights { if w > 0 { weights = append(weights, w) } } currentWeight := int(atomic.AddUint32(&r.index, 1)) % r.totalWeight for i, weight := range weights { totalWeight += weight if currentWeight < totalWeight { index = i break } } upstreams := make([]*Upstream, 0, len(weights)) for i, upstream := range pool { if !upstream.Available() || r.Weights[i] == 0 { continue } upstreams = append(upstreams, upstream) if len(upstreams) == cap(upstreams) { break } } if len(upstreams) == 0 { return nil } return upstreams[index%len(upstreams)] } // RandomChoiceSelection is a policy that selects // two or more available hosts at random, then // chooses the one with the least load. type RandomChoiceSelection struct { // The size of the sub-pool created from the larger upstream pool. The default value // is 2 and the maximum at selection time is the size of the upstream pool. Choose int `json:"choose,omitempty"` } // CaddyModule returns the Caddy module information. func (RandomChoiceSelection) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.reverse_proxy.selection_policies.random_choose", New: func() caddy.Module { return new(RandomChoiceSelection) }, } } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. func (r *RandomChoiceSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume policy name if !d.NextArg() { return d.ArgErr() } chooseStr := d.Val() choose, err := strconv.Atoi(chooseStr) if err != nil { return d.Errf("invalid choice value '%s': %v", chooseStr, err) } r.Choose = choose return nil } // Provision sets up r. func (r *RandomChoiceSelection) Provision(ctx caddy.Context) error { if r.Choose == 0 { r.Choose = 2 } return nil } // Validate ensures that r's configuration is valid. func (r RandomChoiceSelection) Validate() error { if r.Choose < 2 { return fmt.Errorf("choose must be at least 2") } return nil } // Select returns an available host, if any. func (r RandomChoiceSelection) Select(pool UpstreamPool, _ *http.Request, _ http.ResponseWriter) *Upstream { k := min(r.Choose, len(pool)) choices := make([]*Upstream, k) for i, upstream := range pool { if !upstream.Available() { continue } j := weakrand.Intn(i + 1) //nolint:gosec if j < k { choices[j] = upstream } } return leastRequests(choices) } // LeastConnSelection is a policy that selects the // host with the least active requests. If multiple // hosts have the same fewest number, one is chosen // randomly. The term "conn" or "connection" is used // in this policy name due to its similar meaning in // other software, but our load balancer actually // counts active requests rather than connections, // since these days requests are multiplexed onto // shared connections. type LeastConnSelection struct{} // CaddyModule returns the Caddy module information. func (LeastConnSelection) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.reverse_proxy.selection_policies.least_conn", New: func() caddy.Module { return new(LeastConnSelection) }, } } // Select selects the up host with the least number of connections in the // pool. If more than one host has the same least number of connections, // one of the hosts is chosen at random. func (LeastConnSelection) Select(pool UpstreamPool, _ *http.Request, _ http.ResponseWriter) *Upstream { var bestHost *Upstream var count int leastReqs := -1 for _, host := range pool { if !host.Available() { continue } numReqs := host.NumRequests() if leastReqs == -1 || numReqs < leastReqs { leastReqs = numReqs count = 0 } // among hosts with same least connections, perform a reservoir // sample: https://en.wikipedia.org/wiki/Reservoir_sampling if numReqs == leastReqs { count++ if count == 1 || (weakrand.Int()%count) == 0 { //nolint:gosec bestHost = host } } } return bestHost } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. func (r *LeastConnSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume policy name if d.NextArg() { return d.ArgErr() } return nil } // RoundRobinSelection is a policy that selects // a host based on round-robin ordering. type RoundRobinSelection struct { robin uint32 } // CaddyModule returns the Caddy module information. func (RoundRobinSelection) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.reverse_proxy.selection_policies.round_robin", New: func() caddy.Module { return new(RoundRobinSelection) }, } } // Select returns an available host, if any. func (r *RoundRobinSelection) Select(pool UpstreamPool, _ *http.Request, _ http.ResponseWriter) *Upstream { n := uint32(len(pool)) if n == 0 { return nil } for i := uint32(0); i < n; i++ { robin := atomic.AddUint32(&r.robin, 1) host := pool[robin%n] if host.Available() { return host } } return nil } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. func (r *RoundRobinSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume policy name if d.NextArg() { return d.ArgErr() } return nil } // FirstSelection is a policy that selects // the first available host. type FirstSelection struct{} // CaddyModule returns the Caddy module information. func (FirstSelection) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.reverse_proxy.selection_policies.first", New: func() caddy.Module { return new(FirstSelection) }, } } // Select returns an available host, if any. func (FirstSelection) Select(pool UpstreamPool, _ *http.Request, _ http.ResponseWriter) *Upstream { for _, host := range pool { if host.Available() { return host } } return nil } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. func (r *FirstSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume policy name if d.NextArg() { return d.ArgErr() } return nil } // IPHashSelection is a policy that selects a host // based on hashing the remote IP of the request. type IPHashSelection struct{} // CaddyModule returns the Caddy module information. func (IPHashSelection) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.reverse_proxy.selection_policies.ip_hash", New: func() caddy.Module { return new(IPHashSelection) }, } } // Select returns an available host, if any. func (IPHashSelection) Select(pool UpstreamPool, req *http.Request, _ http.ResponseWriter) *Upstream { clientIP, _, err := net.SplitHostPort(req.RemoteAddr) if err != nil { clientIP = req.RemoteAddr } return hostByHashing(pool, clientIP) } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. func (r *IPHashSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume policy name if d.NextArg() { return d.ArgErr() } return nil } // ClientIPHashSelection is a policy that selects a host // based on hashing the client IP of the request, as determined // by the HTTP app's trusted proxies settings. type ClientIPHashSelection struct{} // CaddyModule returns the Caddy module information. func (ClientIPHashSelection) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.reverse_proxy.selection_policies.client_ip_hash", New: func() caddy.Module { return new(ClientIPHashSelection) }, } } // Select returns an available host, if any. func (ClientIPHashSelection) Select(pool UpstreamPool, req *http.Request, _ http.ResponseWriter) *Upstream { address := caddyhttp.GetVar(req.Context(), caddyhttp.ClientIPVarKey).(string) clientIP, _, err := net.SplitHostPort(address) if err != nil { clientIP = address // no port } return hostByHashing(pool, clientIP) } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. func (r *ClientIPHashSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume policy name if d.NextArg() { return d.ArgErr() } return nil } // URIHashSelection is a policy that selects a // host by hashing the request URI. type URIHashSelection struct{} // CaddyModule returns the Caddy module information. func (URIHashSelection) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.reverse_proxy.selection_policies.uri_hash", New: func() caddy.Module { return new(URIHashSelection) }, } } // Select returns an available host, if any. func (URIHashSelection) Select(pool UpstreamPool, req *http.Request, _ http.ResponseWriter) *Upstream { return hostByHashing(pool, req.RequestURI) } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. func (r *URIHashSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume policy name if d.NextArg() { return d.ArgErr() } return nil } // QueryHashSelection is a policy that selects // a host based on a given request query parameter. type QueryHashSelection struct { // The query key whose value is to be hashed and used for upstream selection. Key string `json:"key,omitempty"` // The fallback policy to use if the query key is not present. Defaults to `random`. FallbackRaw json.RawMessage `json:"fallback,omitempty" caddy:"namespace=http.reverse_proxy.selection_policies inline_key=policy"` fallback Selector } // CaddyModule returns the Caddy module information. func (QueryHashSelection) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.reverse_proxy.selection_policies.query", New: func() caddy.Module { return new(QueryHashSelection) }, } } // Provision sets up the module. func (s *QueryHashSelection) Provision(ctx caddy.Context) error { if s.Key == "" { return fmt.Errorf("query key is required") } if s.FallbackRaw == nil { s.FallbackRaw = caddyconfig.JSONModuleObject(RandomSelection{}, "policy", "random", nil) } mod, err := ctx.LoadModule(s, "FallbackRaw") if err != nil { return fmt.Errorf("loading fallback selection policy: %s", err) } s.fallback = mod.(Selector) return nil } // Select returns an available host, if any. func (s QueryHashSelection) Select(pool UpstreamPool, req *http.Request, _ http.ResponseWriter) *Upstream { // Since the query may have multiple values for the same key, // we'll join them to avoid a problem where the user can control // the upstream that the request goes to by sending multiple values // for the same key, when the upstream only considers the first value. // Keep in mind that a client changing the order of the values may // affect which upstream is selected, but this is a semantically // different request, because the order of the values is significant. vals := strings.Join(req.URL.Query()[s.Key], ",") if vals == "" { return s.fallback.Select(pool, req, nil) } return hostByHashing(pool, vals) } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. func (s *QueryHashSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume policy name if !d.NextArg() { return d.ArgErr() } s.Key = d.Val() for d.NextBlock(0) { switch d.Val() { case "fallback": if !d.NextArg() { return d.ArgErr() } if s.FallbackRaw != nil { return d.Err("fallback selection policy already specified") } mod, err := loadFallbackPolicy(d) if err != nil { return err } s.FallbackRaw = mod default: return d.Errf("unrecognized option '%s'", d.Val()) } } return nil } // HeaderHashSelection is a policy that selects // a host based on a given request header. type HeaderHashSelection struct { // The HTTP header field whose value is to be hashed and used for upstream selection. Field string `json:"field,omitempty"` // The fallback policy to use if the header is not present. Defaults to `random`. FallbackRaw json.RawMessage `json:"fallback,omitempty" caddy:"namespace=http.reverse_proxy.selection_policies inline_key=policy"` fallback Selector } // CaddyModule returns the Caddy module information. func (HeaderHashSelection) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.reverse_proxy.selection_policies.header", New: func() caddy.Module { return new(HeaderHashSelection) }, } } // Provision sets up the module. func (s *HeaderHashSelection) Provision(ctx caddy.Context) error { if s.Field == "" { return fmt.Errorf("header field is required") } if s.FallbackRaw == nil { s.FallbackRaw = caddyconfig.JSONModuleObject(RandomSelection{}, "policy", "random", nil) } mod, err := ctx.LoadModule(s, "FallbackRaw") if err != nil { return fmt.Errorf("loading fallback selection policy: %s", err) } s.fallback = mod.(Selector) return nil } // Select returns an available host, if any. func (s HeaderHashSelection) Select(pool UpstreamPool, req *http.Request, _ http.ResponseWriter) *Upstream { // The Host header should be obtained from the req.Host field // since net/http removes it from the header map. if s.Field == "Host" && req.Host != "" { return hostByHashing(pool, req.Host) } val := req.Header.Get(s.Field) if val == "" { return s.fallback.Select(pool, req, nil) } return hostByHashing(pool, val) } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. func (s *HeaderHashSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume policy name if !d.NextArg() { return d.ArgErr() } s.Field = d.Val() for d.NextBlock(0) { switch d.Val() { case "fallback": if !d.NextArg() { return d.ArgErr() } if s.FallbackRaw != nil { return d.Err("fallback selection policy already specified") } mod, err := loadFallbackPolicy(d) if err != nil { return err } s.FallbackRaw = mod default: return d.Errf("unrecognized option '%s'", d.Val()) } } return nil } // CookieHashSelection is a policy that selects // a host based on a given cookie name. type CookieHashSelection struct { // The HTTP cookie name whose value is to be hashed and used for upstream selection. Name string `json:"name,omitempty"` // Secret to hash (Hmac256) chosen upstream in cookie Secret string `json:"secret,omitempty"` // The cookie's Max-Age before it expires. Default is no expiry. MaxAge caddy.Duration `json:"max_age,omitempty"` // The fallback policy to use if the cookie is not present. Defaults to `random`. FallbackRaw json.RawMessage `json:"fallback,omitempty" caddy:"namespace=http.reverse_proxy.selection_policies inline_key=policy"` fallback Selector } // CaddyModule returns the Caddy module information. func (CookieHashSelection) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.reverse_proxy.selection_policies.cookie", New: func() caddy.Module { return new(CookieHashSelection) }, } } // Provision sets up the module. func (s *CookieHashSelection) Provision(ctx caddy.Context) error { if s.Name == "" { s.Name = "lb" } if s.FallbackRaw == nil { s.FallbackRaw = caddyconfig.JSONModuleObject(RandomSelection{}, "policy", "random", nil) } mod, err := ctx.LoadModule(s, "FallbackRaw") if err != nil { return fmt.Errorf("loading fallback selection policy: %s", err) } s.fallback = mod.(Selector) return nil } // Select returns an available host, if any. func (s CookieHashSelection) Select(pool UpstreamPool, req *http.Request, w http.ResponseWriter) *Upstream { // selects a new Host using the fallback policy (typically random) // and write a sticky session cookie to the response. selectNewHost := func() *Upstream { upstream := s.fallback.Select(pool, req, w) if upstream == nil { return nil } sha, err := hashCookie(s.Secret, upstream.Dial) if err != nil { return upstream } cookie := &http.Cookie{ Name: s.Name, Value: sha, Path: "/", Secure: false, } isProxyHttps := false if trusted, ok := caddyhttp.GetVar(req.Context(), caddyhttp.TrustedProxyVarKey).(bool); ok && trusted { xfp, xfpOk, _ := lastHeaderValue(req.Header, "X-Forwarded-Proto") isProxyHttps = xfpOk && xfp == "https" } if req.TLS != nil || isProxyHttps { cookie.Secure = true cookie.SameSite = http.SameSiteNoneMode } if s.MaxAge > 0 { cookie.MaxAge = int(time.Duration(s.MaxAge).Seconds()) } http.SetCookie(w, cookie) return upstream } cookie, err := req.Cookie(s.Name) // If there's no cookie, select a host using the fallback policy if err != nil || cookie == nil { return selectNewHost() } // If the cookie is present, loop over the available upstreams until we find a match cookieValue := cookie.Value for _, upstream := range pool { if !upstream.Available() { continue } sha, err := hashCookie(s.Secret, upstream.Dial) if err == nil && sha == cookieValue { return upstream } } // If there is no matching host, select a host using the fallback policy return selectNewHost() } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. Syntax: // // lb_policy cookie [<name> [<secret>]] { // fallback <policy> // max_age <duration> // } // // By default name is `lb` func (s *CookieHashSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { args := d.RemainingArgs() switch len(args) { case 1: case 2: s.Name = args[1] case 3: s.Name = args[1] s.Secret = args[2] default: return d.ArgErr() } for d.NextBlock(0) { switch d.Val() { case "fallback": if !d.NextArg() { return d.ArgErr() } if s.FallbackRaw != nil { return d.Err("fallback selection policy already specified") } mod, err := loadFallbackPolicy(d) if err != nil { return err } s.FallbackRaw = mod case "max_age": if !d.NextArg() { return d.ArgErr() } if s.MaxAge != 0 { return d.Err("cookie max_age already specified") } maxAge, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("invalid duration: %s", d.Val()) } if maxAge <= 0 { return d.Errf("invalid duration: %s, max_age should be non-zero and positive", d.Val()) } if d.NextArg() { return d.ArgErr() } s.MaxAge = caddy.Duration(maxAge) default: return d.Errf("unrecognized option '%s'", d.Val()) } } return nil } // hashCookie hashes (HMAC 256) some data with the secret func hashCookie(secret string, data string) (string, error) { h := hmac.New(sha256.New, []byte(secret)) _, err := h.Write([]byte(data)) if err != nil { return "", err } return hex.EncodeToString(h.Sum(nil)), nil } // selectRandomHost returns a random available host func selectRandomHost(pool []*Upstream) *Upstream { // use reservoir sampling because the number of available // hosts isn't known: https://en.wikipedia.org/wiki/Reservoir_sampling var randomHost *Upstream var count int for _, upstream := range pool { if !upstream.Available() { continue } // (n % 1 == 0) holds for all n, therefore a // upstream will always be chosen if there is at // least one available count++ if (weakrand.Int() % count) == 0 { //nolint:gosec randomHost = upstream } } return randomHost } // leastRequests returns the host with the // least number of active requests to it. // If more than one host has the same // least number of active requests, then // one of those is chosen at random. func leastRequests(upstreams []*Upstream) *Upstream { if len(upstreams) == 0 { return nil } var best []*Upstream bestReqs := -1 for _, upstream := range upstreams { if upstream == nil { continue } reqs := upstream.NumRequests() if reqs == 0 { return upstream } // If bestReqs was just initialized to -1 // we need to append upstream also if reqs <= bestReqs || bestReqs == -1 { bestReqs = reqs best = append(best, upstream) } } if len(best) == 0 { return nil } if len(best) == 1 { return best[0] } return best[weakrand.Intn(len(best))] //nolint:gosec } // hostByHashing returns an available host from pool based on a hashable string s. func hostByHashing(pool []*Upstream, s string) *Upstream { // Highest Random Weight (HRW, or "Rendezvous") hashing, // guarantees stability when the list of upstreams changes; // see https://medium.com/i0exception/rendezvous-hashing-8c00e2fb58b0, // https://randorithms.com/2020/12/26/rendezvous-hashing.html, // and https://en.wikipedia.org/wiki/Rendezvous_hashing. var highestHash uint64 var upstream *Upstream for _, up := range pool { if !up.Available() { continue } h := hash(up.String() + s) // important to hash key and server together if h > highestHash { highestHash = h upstream = up } } return upstream } // hash calculates a fast hash based on s. func hash(s string) uint64 { h := xxhash.New() _, _ = h.Write([]byte(s)) return h.Sum64() } func loadFallbackPolicy(d *caddyfile.Dispenser) (json.RawMessage, error) { name := d.Val() modID := "http.reverse_proxy.selection_policies." + name unm, err := caddyfile.UnmarshalModule(d, modID) if err != nil { return nil, err } sel, ok := unm.(Selector) if !ok { return nil, d.Errf("module %s (%T) is not a reverseproxy.Selector", modID, unm) } return caddyconfig.JSONModuleObject(sel, "policy", name, nil), nil } // Interface guards var ( _ Selector = (*RandomSelection)(nil) _ Selector = (*RandomChoiceSelection)(nil) _ Selector = (*LeastConnSelection)(nil) _ Selector = (*RoundRobinSelection)(nil) _ Selector = (*WeightedRoundRobinSelection)(nil) _ Selector = (*FirstSelection)(nil) _ Selector = (*IPHashSelection)(nil) _ Selector = (*ClientIPHashSelection)(nil) _ Selector = (*URIHashSelection)(nil) _ Selector = (*QueryHashSelection)(nil) _ Selector = (*HeaderHashSelection)(nil) _ Selector = (*CookieHashSelection)(nil) _ caddy.Validator = (*RandomChoiceSelection)(nil) _ caddy.Provisioner = (*RandomChoiceSelection)(nil) _ caddy.Provisioner = (*WeightedRoundRobinSelection)(nil) _ caddyfile.Unmarshaler = (*RandomChoiceSelection)(nil) _ caddyfile.Unmarshaler = (*WeightedRoundRobinSelection)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/reverseproxy/hosts.go
modules/caddyhttp/reverseproxy/hosts.go
// Copyright 2015 Matthew Holt and The Caddy 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 reverseproxy import ( "context" "fmt" "net/netip" "strconv" "sync/atomic" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) // UpstreamPool is a collection of upstreams. type UpstreamPool []*Upstream // Upstream bridges this proxy's configuration to the // state of the backend host it is correlated with. // Upstream values must not be copied. type Upstream struct { *Host `json:"-"` // The [network address](/docs/conventions#network-addresses) // to dial to connect to the upstream. Must represent precisely // one socket (i.e. no port ranges). A valid network address // either has a host and port or is a unix socket address. // // Placeholders may be used to make the upstream dynamic, but be // aware of the health check implications of this: a single // upstream that represents numerous (perhaps arbitrary) backends // can be considered down if one or enough of the arbitrary // backends is down. Also be aware of open proxy vulnerabilities. Dial string `json:"dial,omitempty"` // The maximum number of simultaneous requests to allow to // this upstream. If set, overrides the global passive health // check UnhealthyRequestCount value. MaxRequests int `json:"max_requests,omitempty"` // TODO: This could be really useful, to bind requests // with certain properties to specific backends // HeaderAffinity string // IPAffinity string activeHealthCheckPort int activeHealthCheckUpstream string healthCheckPolicy *PassiveHealthChecks cb CircuitBreaker unhealthy int32 // accessed atomically; status from active health checker } // (pointer receiver necessary to avoid a race condition, since // copying the Upstream reads the 'unhealthy' field which is // accessed atomically) func (u *Upstream) String() string { return u.Dial } // Available returns true if the remote host // is available to receive requests. This is // the method that should be used by selection // policies, etc. to determine if a backend // should be able to be sent a request. func (u *Upstream) Available() bool { return u.Healthy() && !u.Full() } // Healthy returns true if the remote host // is currently known to be healthy or "up". // It consults the circuit breaker, if any. func (u *Upstream) Healthy() bool { healthy := u.healthy() if healthy && u.healthCheckPolicy != nil { healthy = u.Host.Fails() < u.healthCheckPolicy.MaxFails } if healthy && u.cb != nil { healthy = u.cb.OK() } return healthy } // Full returns true if the remote host // cannot receive more requests at this time. func (u *Upstream) Full() bool { return u.MaxRequests > 0 && u.Host.NumRequests() >= u.MaxRequests } // fillDialInfo returns a filled DialInfo for upstream u, using the request // context. Note that the returned value is not a pointer. func (u *Upstream) fillDialInfo(repl *caddy.Replacer) (DialInfo, error) { var addr caddy.NetworkAddress // use provided dial address var err error dial := repl.ReplaceAll(u.Dial, "") addr, err = caddy.ParseNetworkAddress(dial) if err != nil { return DialInfo{}, fmt.Errorf("upstream %s: invalid dial address %s: %v", u.Dial, dial, err) } if numPorts := addr.PortRangeSize(); numPorts != 1 { return DialInfo{}, fmt.Errorf("upstream %s: dial address must represent precisely one socket: %s represents %d", u.Dial, dial, numPorts) } return DialInfo{ Upstream: u, Network: addr.Network, Address: addr.JoinHostPort(0), Host: addr.Host, Port: strconv.Itoa(int(addr.StartPort)), }, nil } func (u *Upstream) fillHost() { host := new(Host) existingHost, loaded := hosts.LoadOrStore(u.String(), host) if loaded { host = existingHost.(*Host) } u.Host = host } // Host is the basic, in-memory representation of the state of a remote host. // Its fields are accessed atomically and Host values must not be copied. type Host struct { numRequests int64 // must be 64-bit aligned on 32-bit systems (see https://golang.org/pkg/sync/atomic/#pkg-note-BUG) fails int64 activePasses int64 activeFails int64 } // NumRequests returns the number of active requests to the upstream. func (h *Host) NumRequests() int { return int(atomic.LoadInt64(&h.numRequests)) } // Fails returns the number of recent failures with the upstream. func (h *Host) Fails() int { return int(atomic.LoadInt64(&h.fails)) } // activeHealthPasses returns the number of consecutive active health check passes with the upstream. func (h *Host) activeHealthPasses() int { return int(atomic.LoadInt64(&h.activePasses)) } // activeHealthFails returns the number of consecutive active health check failures with the upstream. func (h *Host) activeHealthFails() int { return int(atomic.LoadInt64(&h.activeFails)) } // countRequest mutates the active request count by // delta. It returns an error if the adjustment fails. func (h *Host) countRequest(delta int) error { result := atomic.AddInt64(&h.numRequests, int64(delta)) if result < 0 { return fmt.Errorf("count below 0: %d", result) } return nil } // countFail mutates the recent failures count by // delta. It returns an error if the adjustment fails. func (h *Host) countFail(delta int) error { result := atomic.AddInt64(&h.fails, int64(delta)) if result < 0 { return fmt.Errorf("count below 0: %d", result) } return nil } // countHealthPass mutates the recent passes count by // delta. It returns an error if the adjustment fails. func (h *Host) countHealthPass(delta int) error { result := atomic.AddInt64(&h.activePasses, int64(delta)) if result < 0 { return fmt.Errorf("count below 0: %d", result) } return nil } // countHealthFail mutates the recent failures count by // delta. It returns an error if the adjustment fails. func (h *Host) countHealthFail(delta int) error { result := atomic.AddInt64(&h.activeFails, int64(delta)) if result < 0 { return fmt.Errorf("count below 0: %d", result) } return nil } // resetHealth resets the health check counters. func (h *Host) resetHealth() { atomic.StoreInt64(&h.activePasses, 0) atomic.StoreInt64(&h.activeFails, 0) } // healthy returns true if the upstream is not actively marked as unhealthy. // (This returns the status only from the "active" health checks.) func (u *Upstream) healthy() bool { return atomic.LoadInt32(&u.unhealthy) == 0 } // SetHealthy sets the upstream has healthy or unhealthy // and returns true if the new value is different. This // sets the status only for the "active" health checks. func (u *Upstream) setHealthy(healthy bool) bool { var unhealthy, compare int32 = 1, 0 if healthy { unhealthy, compare = 0, 1 } return atomic.CompareAndSwapInt32(&u.unhealthy, compare, unhealthy) } // DialInfo contains information needed to dial a // connection to an upstream host. This information // may be different than that which is represented // in a URL (for example, unix sockets don't have // a host that can be represented in a URL, but // they certainly have a network name and address). type DialInfo struct { // Upstream is the Upstream associated with // this DialInfo. It may be nil. Upstream *Upstream // The network to use. This should be one of // the values that is accepted by net.Dial: // https://golang.org/pkg/net/#Dial Network string // The address to dial. Follows the same // semantics and rules as net.Dial. Address string // Host and Port are components of Address. Host, Port string } // String returns the Caddy network address form // by joining the network and address with a // forward slash. func (di DialInfo) String() string { return caddy.JoinNetworkAddress(di.Network, di.Host, di.Port) } // GetDialInfo gets the upstream dialing info out of the context, // and returns true if there was a valid value; false otherwise. func GetDialInfo(ctx context.Context) (DialInfo, bool) { dialInfo, ok := caddyhttp.GetVar(ctx, dialInfoVarKey).(DialInfo) return dialInfo, ok } // hosts is the global repository for hosts that are // currently in use by active configuration(s). This // allows the state of remote hosts to be preserved // through config reloads. var hosts = caddy.NewUsagePool() // dialInfoVarKey is the key used for the variable that holds // the dial info for the upstream connection. const dialInfoVarKey = "reverse_proxy.dial_info" // proxyProtocolInfoVarKey is the key used for the variable that holds // the proxy protocol info for the upstream connection. const proxyProtocolInfoVarKey = "reverse_proxy.proxy_protocol_info" // ProxyProtocolInfo contains information needed to write proxy protocol to a // connection to an upstream host. type ProxyProtocolInfo struct { AddrPort netip.AddrPort } // tlsH1OnlyVarKey is the key used that indicates the connection will use h1 only for TLS. // https://github.com/caddyserver/caddy/issues/7292 const tlsH1OnlyVarKey = "reverse_proxy.tls_h1_only" // proxyVarKey is the key used that indicates the proxy server used for a request. const proxyVarKey = "reverse_proxy.proxy"
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/reverseproxy/upstreams_test.go
modules/caddyhttp/reverseproxy/upstreams_test.go
package reverseproxy import "testing" func TestResolveIpVersion(t *testing.T) { falseBool := false trueBool := true tests := []struct { Versions *IPVersions expectedIpVersion string }{ { Versions: &IPVersions{IPv4: &trueBool}, expectedIpVersion: "ip4", }, { Versions: &IPVersions{IPv4: &falseBool}, expectedIpVersion: "ip", }, { Versions: &IPVersions{IPv4: &trueBool, IPv6: &falseBool}, expectedIpVersion: "ip4", }, { Versions: &IPVersions{IPv6: &trueBool}, expectedIpVersion: "ip6", }, { Versions: &IPVersions{IPv6: &falseBool}, expectedIpVersion: "ip", }, { Versions: &IPVersions{IPv6: &trueBool, IPv4: &falseBool}, expectedIpVersion: "ip6", }, { Versions: &IPVersions{}, expectedIpVersion: "ip", }, { Versions: &IPVersions{IPv4: &trueBool, IPv6: &trueBool}, expectedIpVersion: "ip", }, { Versions: &IPVersions{IPv4: &falseBool, IPv6: &falseBool}, expectedIpVersion: "ip", }, } for _, test := range tests { ipVersion := resolveIpVersion(test.Versions) if ipVersion != test.expectedIpVersion { t.Errorf("resolveIpVersion(): Expected %s got %s", test.expectedIpVersion, ipVersion) } } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/reverseproxy/upstreams.go
modules/caddyhttp/reverseproxy/upstreams.go
package reverseproxy import ( "context" "encoding/json" "fmt" weakrand "math/rand" "net" "net/http" "strconv" "sync" "time" "go.uber.org/zap" "go.uber.org/zap/zapcore" "github.com/caddyserver/caddy/v2" ) func init() { caddy.RegisterModule(SRVUpstreams{}) caddy.RegisterModule(AUpstreams{}) caddy.RegisterModule(MultiUpstreams{}) } // SRVUpstreams provides upstreams from SRV lookups. // The lookup DNS name can be configured either by // its individual parts (that is, specifying the // service, protocol, and name separately) to form // the standard "_service._proto.name" domain, or // the domain can be specified directly in name by // leaving service and proto empty. See RFC 2782. // // Lookups are cached and refreshed at the configured // refresh interval. // // Returned upstreams are sorted by priority and weight. type SRVUpstreams struct { // The service label. Service string `json:"service,omitempty"` // The protocol label; either tcp or udp. Proto string `json:"proto,omitempty"` // The name label; or, if service and proto are // empty, the entire domain name to look up. Name string `json:"name,omitempty"` // The interval at which to refresh the SRV lookup. // Results are cached between lookups. Default: 1m Refresh caddy.Duration `json:"refresh,omitempty"` // If > 0 and there is an error with the lookup, // continue to use the cached results for up to // this long before trying again, (even though they // are stale) instead of returning an error to the // client. Default: 0s. GracePeriod caddy.Duration `json:"grace_period,omitempty"` // Configures the DNS resolver used to resolve the // SRV address to SRV records. Resolver *UpstreamResolver `json:"resolver,omitempty"` // If Resolver is configured, how long to wait before // timing out trying to connect to the DNS server. DialTimeout caddy.Duration `json:"dial_timeout,omitempty"` // If Resolver is configured, how long to wait before // spawning an RFC 6555 Fast Fallback connection. // A negative value disables this. FallbackDelay caddy.Duration `json:"dial_fallback_delay,omitempty"` resolver *net.Resolver logger *zap.Logger } // CaddyModule returns the Caddy module information. func (SRVUpstreams) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.reverse_proxy.upstreams.srv", New: func() caddy.Module { return new(SRVUpstreams) }, } } func (su *SRVUpstreams) Provision(ctx caddy.Context) error { su.logger = ctx.Logger() if su.Refresh == 0 { su.Refresh = caddy.Duration(time.Minute) } if su.Resolver != nil { err := su.Resolver.ParseAddresses() if err != nil { return err } d := &net.Dialer{ Timeout: time.Duration(su.DialTimeout), FallbackDelay: time.Duration(su.FallbackDelay), } su.resolver = &net.Resolver{ PreferGo: true, Dial: func(ctx context.Context, _, _ string) (net.Conn, error) { //nolint:gosec addr := su.Resolver.netAddrs[weakrand.Intn(len(su.Resolver.netAddrs))] return d.DialContext(ctx, addr.Network, addr.JoinHostPort(0)) }, } } if su.resolver == nil { su.resolver = net.DefaultResolver } return nil } func (su SRVUpstreams) GetUpstreams(r *http.Request) ([]*Upstream, error) { suAddr, service, proto, name := su.expandedAddr(r) // first, use a cheap read-lock to return a cached result quickly srvsMu.RLock() cached := srvs[suAddr] srvsMu.RUnlock() if cached.isFresh() { return allNew(cached.upstreams), nil } // otherwise, obtain a write-lock to update the cached value srvsMu.Lock() defer srvsMu.Unlock() // check to see if it's still stale, since we're now in a different // lock from when we first checked freshness; another goroutine might // have refreshed it in the meantime before we re-obtained our lock cached = srvs[suAddr] if cached.isFresh() { return allNew(cached.upstreams), nil } if c := su.logger.Check(zapcore.DebugLevel, "refreshing SRV upstreams"); c != nil { c.Write( zap.String("service", service), zap.String("proto", proto), zap.String("name", name), ) } _, records, err := su.resolver.LookupSRV(r.Context(), service, proto, name) if err != nil { // From LookupSRV docs: "If the response contains invalid names, those records are filtered // out and an error will be returned alongside the remaining results, if any." Thus, we // only return an error if no records were also returned. if len(records) == 0 { if su.GracePeriod > 0 { if c := su.logger.Check(zapcore.ErrorLevel, "SRV lookup failed; using previously cached"); c != nil { c.Write(zap.Error(err)) } cached.freshness = time.Now().Add(time.Duration(su.GracePeriod) - time.Duration(su.Refresh)) srvs[suAddr] = cached return allNew(cached.upstreams), nil } return nil, err } if c := su.logger.Check(zapcore.WarnLevel, "SRV records filtered"); c != nil { c.Write(zap.Error(err)) } } upstreams := make([]Upstream, len(records)) for i, rec := range records { if c := su.logger.Check(zapcore.DebugLevel, "discovered SRV record"); c != nil { c.Write( zap.String("target", rec.Target), zap.Uint16("port", rec.Port), zap.Uint16("priority", rec.Priority), zap.Uint16("weight", rec.Weight), ) } addr := net.JoinHostPort(rec.Target, strconv.Itoa(int(rec.Port))) upstreams[i] = Upstream{Dial: addr} } // before adding a new one to the cache (as opposed to replacing stale one), make room if cache is full if cached.freshness.IsZero() && len(srvs) >= 100 { for randomKey := range srvs { delete(srvs, randomKey) break } } srvs[suAddr] = srvLookup{ srvUpstreams: su, freshness: time.Now(), upstreams: upstreams, } return allNew(upstreams), nil } func (su SRVUpstreams) String() string { if su.Service == "" && su.Proto == "" { return su.Name } return su.formattedAddr(su.Service, su.Proto, su.Name) } // expandedAddr expands placeholders in the configured SRV domain labels. // The return values are: addr, the RFC 2782 representation of the SRV domain; // service, the service; proto, the protocol; and name, the name. // If su.Service and su.Proto are empty, name will be returned as addr instead. func (su SRVUpstreams) expandedAddr(r *http.Request) (addr, service, proto, name string) { repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) name = repl.ReplaceAll(su.Name, "") if su.Service == "" && su.Proto == "" { addr = name return addr, service, proto, name } service = repl.ReplaceAll(su.Service, "") proto = repl.ReplaceAll(su.Proto, "") addr = su.formattedAddr(service, proto, name) return addr, service, proto, name } // formattedAddr the RFC 2782 representation of the SRV domain, in // the form "_service._proto.name". func (SRVUpstreams) formattedAddr(service, proto, name string) string { return fmt.Sprintf("_%s._%s.%s", service, proto, name) } type srvLookup struct { srvUpstreams SRVUpstreams freshness time.Time upstreams []Upstream } func (sl srvLookup) isFresh() bool { return time.Since(sl.freshness) < time.Duration(sl.srvUpstreams.Refresh) } type IPVersions struct { IPv4 *bool `json:"ipv4,omitempty"` IPv6 *bool `json:"ipv6,omitempty"` } func resolveIpVersion(versions *IPVersions) string { resolveIpv4 := versions == nil || (versions.IPv4 == nil && versions.IPv6 == nil) || (versions.IPv4 != nil && *versions.IPv4) resolveIpv6 := versions == nil || (versions.IPv6 == nil && versions.IPv4 == nil) || (versions.IPv6 != nil && *versions.IPv6) switch { case resolveIpv4 && !resolveIpv6: return "ip4" case !resolveIpv4 && resolveIpv6: return "ip6" default: return "ip" } } // AUpstreams provides upstreams from A/AAAA lookups. // Results are cached and refreshed at the configured // refresh interval. type AUpstreams struct { // The domain name to look up. Name string `json:"name,omitempty"` // The port to use with the upstreams. Default: 80 Port string `json:"port,omitempty"` // The interval at which to refresh the A lookup. // Results are cached between lookups. Default: 1m Refresh caddy.Duration `json:"refresh,omitempty"` // Configures the DNS resolver used to resolve the // domain name to A records. Resolver *UpstreamResolver `json:"resolver,omitempty"` // If Resolver is configured, how long to wait before // timing out trying to connect to the DNS server. DialTimeout caddy.Duration `json:"dial_timeout,omitempty"` // If Resolver is configured, how long to wait before // spawning an RFC 6555 Fast Fallback connection. // A negative value disables this. FallbackDelay caddy.Duration `json:"dial_fallback_delay,omitempty"` // The IP versions to resolve for. By default, both // "ipv4" and "ipv6" will be enabled, which // correspond to A and AAAA records respectively. Versions *IPVersions `json:"versions,omitempty"` resolver *net.Resolver logger *zap.Logger } // CaddyModule returns the Caddy module information. func (AUpstreams) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.reverse_proxy.upstreams.a", New: func() caddy.Module { return new(AUpstreams) }, } } func (au *AUpstreams) Provision(ctx caddy.Context) error { au.logger = ctx.Logger() if au.Refresh == 0 { au.Refresh = caddy.Duration(time.Minute) } if au.Port == "" { au.Port = "80" } if au.Resolver != nil { err := au.Resolver.ParseAddresses() if err != nil { return err } d := &net.Dialer{ Timeout: time.Duration(au.DialTimeout), FallbackDelay: time.Duration(au.FallbackDelay), } au.resolver = &net.Resolver{ PreferGo: true, Dial: func(ctx context.Context, _, _ string) (net.Conn, error) { //nolint:gosec addr := au.Resolver.netAddrs[weakrand.Intn(len(au.Resolver.netAddrs))] return d.DialContext(ctx, addr.Network, addr.JoinHostPort(0)) }, } } if au.resolver == nil { au.resolver = net.DefaultResolver } return nil } func (au AUpstreams) GetUpstreams(r *http.Request) ([]*Upstream, error) { repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) // Map ipVersion early, so we can use it as part of the cache-key. // This should be fairly inexpensive and comes and the upside of // allowing the same dynamic upstream (name + port combination) // to be used multiple times with different ip versions. // // It also forced a cache-miss if a previously cached dynamic // upstream changes its ip version, e.g. after a config reload, // while keeping the cache-invalidation as simple as it currently is. ipVersion := resolveIpVersion(au.Versions) auStr := repl.ReplaceAll(au.String()+ipVersion, "") // first, use a cheap read-lock to return a cached result quickly aAaaaMu.RLock() cached := aAaaa[auStr] aAaaaMu.RUnlock() if cached.isFresh() { return allNew(cached.upstreams), nil } // otherwise, obtain a write-lock to update the cached value aAaaaMu.Lock() defer aAaaaMu.Unlock() // check to see if it's still stale, since we're now in a different // lock from when we first checked freshness; another goroutine might // have refreshed it in the meantime before we re-obtained our lock cached = aAaaa[auStr] if cached.isFresh() { return allNew(cached.upstreams), nil } name := repl.ReplaceAll(au.Name, "") port := repl.ReplaceAll(au.Port, "") if c := au.logger.Check(zapcore.DebugLevel, "refreshing A upstreams"); c != nil { c.Write( zap.String("version", ipVersion), zap.String("name", name), zap.String("port", port), ) } ips, err := au.resolver.LookupIP(r.Context(), ipVersion, name) if err != nil { return nil, err } upstreams := make([]Upstream, len(ips)) for i, ip := range ips { if c := au.logger.Check(zapcore.DebugLevel, "discovered A record"); c != nil { c.Write(zap.String("ip", ip.String())) } upstreams[i] = Upstream{ Dial: net.JoinHostPort(ip.String(), port), } } // before adding a new one to the cache (as opposed to replacing stale one), make room if cache is full if cached.freshness.IsZero() && len(aAaaa) >= 100 { for randomKey := range aAaaa { delete(aAaaa, randomKey) break } } aAaaa[auStr] = aLookup{ aUpstreams: au, freshness: time.Now(), upstreams: upstreams, } return allNew(upstreams), nil } func (au AUpstreams) String() string { return net.JoinHostPort(au.Name, au.Port) } type aLookup struct { aUpstreams AUpstreams freshness time.Time upstreams []Upstream } func (al aLookup) isFresh() bool { return time.Since(al.freshness) < time.Duration(al.aUpstreams.Refresh) } // MultiUpstreams is a single dynamic upstream source that // aggregates the results of multiple dynamic upstream sources. // All configured sources will be queried in order, with their // results appended to the end of the list. Errors returned // from individual sources will be logged and the next source // will continue to be invoked. // // This module makes it easy to implement redundant cluster // failovers, especially in conjunction with the `first` load // balancing policy: if the first source returns an error or // no upstreams, the second source's upstreams will be used // naturally. type MultiUpstreams struct { // The list of upstream source modules to get upstreams from. // They will be queried in order, with their results appended // in the order they are returned. SourcesRaw []json.RawMessage `json:"sources,omitempty" caddy:"namespace=http.reverse_proxy.upstreams inline_key=source"` sources []UpstreamSource logger *zap.Logger } // CaddyModule returns the Caddy module information. func (MultiUpstreams) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.reverse_proxy.upstreams.multi", New: func() caddy.Module { return new(MultiUpstreams) }, } } func (mu *MultiUpstreams) Provision(ctx caddy.Context) error { mu.logger = ctx.Logger() if mu.SourcesRaw != nil { mod, err := ctx.LoadModule(mu, "SourcesRaw") if err != nil { return fmt.Errorf("loading upstream source modules: %v", err) } for _, src := range mod.([]any) { mu.sources = append(mu.sources, src.(UpstreamSource)) } } return nil } func (mu MultiUpstreams) GetUpstreams(r *http.Request) ([]*Upstream, error) { var upstreams []*Upstream for i, src := range mu.sources { select { case <-r.Context().Done(): return upstreams, context.Canceled default: } up, err := src.GetUpstreams(r) if err != nil { if c := mu.logger.Check(zapcore.ErrorLevel, "upstream source returned error"); c != nil { c.Write( zap.Int("source_idx", i), zap.Error(err), ) } } else if len(up) == 0 { if c := mu.logger.Check(zapcore.WarnLevel, "upstream source returned 0 upstreams"); c != nil { c.Write(zap.Int("source_idx", i)) } } else { upstreams = append(upstreams, up...) } } return upstreams, nil } // UpstreamResolver holds the set of addresses of DNS resolvers of // upstream addresses type UpstreamResolver struct { // The addresses of DNS resolvers to use when looking up the addresses of proxy upstreams. // It accepts [network addresses](/docs/conventions#network-addresses) // with port range of only 1. If the host is an IP address, it will be dialed directly to resolve the upstream server. // If the host is not an IP address, the addresses are resolved using the [name resolution convention](https://golang.org/pkg/net/#hdr-Name_Resolution) of the Go standard library. // If the array contains more than 1 resolver address, one is chosen at random. Addresses []string `json:"addresses,omitempty"` netAddrs []caddy.NetworkAddress } // ParseAddresses parses all the configured network addresses // and ensures they're ready to be used. func (u *UpstreamResolver) ParseAddresses() error { for _, v := range u.Addresses { addr, err := caddy.ParseNetworkAddressWithDefaults(v, "udp", 53) if err != nil { return err } if addr.PortRangeSize() != 1 { return fmt.Errorf("resolver address must have exactly one address; cannot call %v", addr) } u.netAddrs = append(u.netAddrs, addr) } return nil } func allNew(upstreams []Upstream) []*Upstream { results := make([]*Upstream, len(upstreams)) for i := range upstreams { results[i] = &Upstream{Dial: upstreams[i].Dial} } return results } var ( srvs = make(map[string]srvLookup) srvsMu sync.RWMutex aAaaa = make(map[string]aLookup) aAaaaMu sync.RWMutex ) // Interface guards var ( _ caddy.Provisioner = (*SRVUpstreams)(nil) _ UpstreamSource = (*SRVUpstreams)(nil) _ caddy.Provisioner = (*AUpstreams)(nil) _ UpstreamSource = (*AUpstreams)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/reverseproxy/caddyfile.go
modules/caddyhttp/reverseproxy/caddyfile.go
// Copyright 2015 Matthew Holt and The Caddy 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 reverseproxy import ( "fmt" "net" "net/http" "reflect" "strconv" "strings" "github.com/dustin/go-humanize" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile" "github.com/caddyserver/caddy/v2/internal" "github.com/caddyserver/caddy/v2/modules/caddyhttp" "github.com/caddyserver/caddy/v2/modules/caddyhttp/headers" "github.com/caddyserver/caddy/v2/modules/caddyhttp/rewrite" "github.com/caddyserver/caddy/v2/modules/caddytls" "github.com/caddyserver/caddy/v2/modules/internal/network" ) func init() { httpcaddyfile.RegisterHandlerDirective("reverse_proxy", parseCaddyfile) httpcaddyfile.RegisterHandlerDirective("copy_response", parseCopyResponseCaddyfile) httpcaddyfile.RegisterHandlerDirective("copy_response_headers", parseCopyResponseHeadersCaddyfile) } func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) { rp := new(Handler) err := rp.UnmarshalCaddyfile(h.Dispenser) if err != nil { return nil, err } err = rp.FinalizeUnmarshalCaddyfile(h) if err != nil { return nil, err } return rp, nil } // UnmarshalCaddyfile sets up the handler from Caddyfile tokens. Syntax: // // reverse_proxy [<matcher>] [<upstreams...>] { // # backends // to <upstreams...> // dynamic <name> [...] // // # load balancing // lb_policy <name> [<options...>] // lb_retries <retries> // lb_try_duration <duration> // lb_try_interval <interval> // lb_retry_match <request-matcher> // // # active health checking // health_uri <uri> // health_port <port> // health_interval <interval> // health_passes <num> // health_fails <num> // health_timeout <duration> // health_status <status> // health_body <regexp> // health_method <value> // health_request_body <value> // health_follow_redirects // health_headers { // <field> [<values...>] // } // // # passive health checking // fail_duration <duration> // max_fails <num> // unhealthy_status <status> // unhealthy_latency <duration> // unhealthy_request_count <num> // // # streaming // flush_interval <duration> // request_buffers <size> // response_buffers <size> // stream_timeout <duration> // stream_close_delay <duration> // verbose_logs // // # request manipulation // trusted_proxies [private_ranges] <ranges...> // header_up [+|-]<field> [<value|regexp> [<replacement>]] // header_down [+|-]<field> [<value|regexp> [<replacement>]] // method <method> // rewrite <to> // // # round trip // transport <name> { // ... // } // // # optionally intercept responses from upstream // @name { // status <code...> // header <field> [<value>] // } // replace_status [<matcher>] <status_code> // handle_response [<matcher>] { // <directives...> // // # special directives only available in handle_response // copy_response [<matcher>] [<status>] { // status <status> // } // copy_response_headers [<matcher>] { // include <fields...> // exclude <fields...> // } // } // } // // Proxy upstream addresses should be network dial addresses such // as `host:port`, or a URL such as `scheme://host:port`. Scheme // and port may be inferred from other parts of the address/URL; if // either are missing, defaults to HTTP. // // The FinalizeUnmarshalCaddyfile method should be called after this // to finalize parsing of "handle_response" blocks, if possible. func (h *Handler) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { // currently, all backends must use the same scheme/protocol (the // underlying JSON does not yet support per-backend transports) var commonScheme string // we'll wait until the very end of parsing before // validating and encoding the transport var transport http.RoundTripper var transportModuleName string // collect the response matchers defined as subdirectives // prefixed with "@" for use with "handle_response" blocks h.responseMatchers = make(map[string]caddyhttp.ResponseMatcher) // appendUpstream creates an upstream for address and adds // it to the list. appendUpstream := func(address string) error { pa, err := parseUpstreamDialAddress(address) if err != nil { return d.WrapErr(err) } // the underlying JSON does not yet support different // transports (protocols or schemes) to each backend, // so we remember the last one we see and compare them switch pa.scheme { case "wss": return d.Errf("the scheme wss:// is only supported in browsers; use https:// instead") case "ws": return d.Errf("the scheme ws:// is only supported in browsers; use http:// instead") case "https", "http", "h2c", "": // Do nothing or handle the valid schemes default: return d.Errf("unsupported URL scheme %s://", pa.scheme) } if commonScheme != "" && pa.scheme != commonScheme { return d.Errf("for now, all proxy upstreams must use the same scheme (transport protocol); expecting '%s://' but got '%s://'", commonScheme, pa.scheme) } commonScheme = pa.scheme // if the port of upstream address contains a placeholder, only wrap it with the `Upstream` struct, // delaying actual resolution of the address until request time. if pa.replaceablePort() { h.Upstreams = append(h.Upstreams, &Upstream{Dial: pa.dialAddr()}) return nil } parsedAddr, err := caddy.ParseNetworkAddress(pa.dialAddr()) if err != nil { return d.WrapErr(err) } if pa.isUnix() || !pa.rangedPort() { // unix networks don't have ports h.Upstreams = append(h.Upstreams, &Upstream{ Dial: pa.dialAddr(), }) } else { // expand a port range into multiple upstreams for i := parsedAddr.StartPort; i <= parsedAddr.EndPort; i++ { h.Upstreams = append(h.Upstreams, &Upstream{ Dial: caddy.JoinNetworkAddress("", parsedAddr.Host, fmt.Sprint(i)), }) } } return nil } d.Next() // consume the directive name for _, up := range d.RemainingArgs() { err := appendUpstream(up) if err != nil { return fmt.Errorf("parsing upstream '%s': %w", up, err) } } for d.NextBlock(0) { // if the subdirective has an "@" prefix then we // parse it as a response matcher for use with "handle_response" if strings.HasPrefix(d.Val(), matcherPrefix) { err := caddyhttp.ParseNamedResponseMatcher(d.NewFromNextSegment(), h.responseMatchers) if err != nil { return err } continue } switch d.Val() { case "to": args := d.RemainingArgs() if len(args) == 0 { return d.ArgErr() } for _, up := range args { err := appendUpstream(up) if err != nil { return fmt.Errorf("parsing upstream '%s': %w", up, err) } } case "dynamic": if !d.NextArg() { return d.ArgErr() } if h.DynamicUpstreams != nil { return d.Err("dynamic upstreams already specified") } dynModule := d.Val() modID := "http.reverse_proxy.upstreams." + dynModule unm, err := caddyfile.UnmarshalModule(d, modID) if err != nil { return err } source, ok := unm.(UpstreamSource) if !ok { return d.Errf("module %s (%T) is not an UpstreamSource", modID, unm) } h.DynamicUpstreamsRaw = caddyconfig.JSONModuleObject(source, "source", dynModule, nil) case "lb_policy": if !d.NextArg() { return d.ArgErr() } if h.LoadBalancing != nil && h.LoadBalancing.SelectionPolicyRaw != nil { return d.Err("load balancing selection policy already specified") } name := d.Val() modID := "http.reverse_proxy.selection_policies." + name unm, err := caddyfile.UnmarshalModule(d, modID) if err != nil { return err } sel, ok := unm.(Selector) if !ok { return d.Errf("module %s (%T) is not a reverseproxy.Selector", modID, unm) } if h.LoadBalancing == nil { h.LoadBalancing = new(LoadBalancing) } h.LoadBalancing.SelectionPolicyRaw = caddyconfig.JSONModuleObject(sel, "policy", name, nil) case "lb_retries": if !d.NextArg() { return d.ArgErr() } tries, err := strconv.Atoi(d.Val()) if err != nil { return d.Errf("bad lb_retries number '%s': %v", d.Val(), err) } if h.LoadBalancing == nil { h.LoadBalancing = new(LoadBalancing) } h.LoadBalancing.Retries = tries case "lb_try_duration": if !d.NextArg() { return d.ArgErr() } if h.LoadBalancing == nil { h.LoadBalancing = new(LoadBalancing) } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("bad duration value %s: %v", d.Val(), err) } h.LoadBalancing.TryDuration = caddy.Duration(dur) case "lb_try_interval": if !d.NextArg() { return d.ArgErr() } if h.LoadBalancing == nil { h.LoadBalancing = new(LoadBalancing) } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("bad interval value '%s': %v", d.Val(), err) } h.LoadBalancing.TryInterval = caddy.Duration(dur) case "lb_retry_match": matcherSet, err := caddyhttp.ParseCaddyfileNestedMatcherSet(d) if err != nil { return d.Errf("failed to parse lb_retry_match: %v", err) } if h.LoadBalancing == nil { h.LoadBalancing = new(LoadBalancing) } h.LoadBalancing.RetryMatchRaw = append(h.LoadBalancing.RetryMatchRaw, matcherSet) case "health_uri": if !d.NextArg() { return d.ArgErr() } if h.HealthChecks == nil { h.HealthChecks = new(HealthChecks) } if h.HealthChecks.Active == nil { h.HealthChecks.Active = new(ActiveHealthChecks) } h.HealthChecks.Active.URI = d.Val() case "health_path": if !d.NextArg() { return d.ArgErr() } if h.HealthChecks == nil { h.HealthChecks = new(HealthChecks) } if h.HealthChecks.Active == nil { h.HealthChecks.Active = new(ActiveHealthChecks) } h.HealthChecks.Active.Path = d.Val() caddy.Log().Named("config.adapter.caddyfile").Warn("the 'health_path' subdirective is deprecated, please use 'health_uri' instead!") case "health_upstream": if !d.NextArg() { return d.ArgErr() } if h.HealthChecks == nil { h.HealthChecks = new(HealthChecks) } if h.HealthChecks.Active == nil { h.HealthChecks.Active = new(ActiveHealthChecks) } _, port, err := net.SplitHostPort(d.Val()) if err != nil { return d.Errf("health_upstream is malformed '%s': %v", d.Val(), err) } _, err = strconv.Atoi(port) if err != nil { return d.Errf("bad port number '%s': %v", d.Val(), err) } h.HealthChecks.Active.Upstream = d.Val() case "health_port": if !d.NextArg() { return d.ArgErr() } if h.HealthChecks == nil { h.HealthChecks = new(HealthChecks) } if h.HealthChecks.Active == nil { h.HealthChecks.Active = new(ActiveHealthChecks) } if h.HealthChecks.Active.Upstream != "" { return d.Errf("the 'health_port' subdirective is ignored if 'health_upstream' is used!") } portNum, err := strconv.Atoi(d.Val()) if err != nil { return d.Errf("bad port number '%s': %v", d.Val(), err) } h.HealthChecks.Active.Port = portNum case "health_headers": healthHeaders := make(http.Header) for nesting := d.Nesting(); d.NextBlock(nesting); { key := d.Val() values := d.RemainingArgs() if len(values) == 0 { values = append(values, "") } healthHeaders[key] = append(healthHeaders[key], values...) } if h.HealthChecks == nil { h.HealthChecks = new(HealthChecks) } if h.HealthChecks.Active == nil { h.HealthChecks.Active = new(ActiveHealthChecks) } h.HealthChecks.Active.Headers = healthHeaders case "health_method": if !d.NextArg() { return d.ArgErr() } if h.HealthChecks == nil { h.HealthChecks = new(HealthChecks) } if h.HealthChecks.Active == nil { h.HealthChecks.Active = new(ActiveHealthChecks) } h.HealthChecks.Active.Method = d.Val() case "health_request_body": if !d.NextArg() { return d.ArgErr() } if h.HealthChecks == nil { h.HealthChecks = new(HealthChecks) } if h.HealthChecks.Active == nil { h.HealthChecks.Active = new(ActiveHealthChecks) } h.HealthChecks.Active.Body = d.Val() case "health_interval": if !d.NextArg() { return d.ArgErr() } if h.HealthChecks == nil { h.HealthChecks = new(HealthChecks) } if h.HealthChecks.Active == nil { h.HealthChecks.Active = new(ActiveHealthChecks) } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("bad interval value %s: %v", d.Val(), err) } h.HealthChecks.Active.Interval = caddy.Duration(dur) case "health_timeout": if !d.NextArg() { return d.ArgErr() } if h.HealthChecks == nil { h.HealthChecks = new(HealthChecks) } if h.HealthChecks.Active == nil { h.HealthChecks.Active = new(ActiveHealthChecks) } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("bad timeout value %s: %v", d.Val(), err) } h.HealthChecks.Active.Timeout = caddy.Duration(dur) case "health_status": if !d.NextArg() { return d.ArgErr() } if h.HealthChecks == nil { h.HealthChecks = new(HealthChecks) } if h.HealthChecks.Active == nil { h.HealthChecks.Active = new(ActiveHealthChecks) } val := d.Val() if len(val) == 3 && strings.HasSuffix(val, "xx") { val = val[:1] } statusNum, err := strconv.Atoi(val) if err != nil { return d.Errf("bad status value '%s': %v", d.Val(), err) } h.HealthChecks.Active.ExpectStatus = statusNum case "health_body": if !d.NextArg() { return d.ArgErr() } if h.HealthChecks == nil { h.HealthChecks = new(HealthChecks) } if h.HealthChecks.Active == nil { h.HealthChecks.Active = new(ActiveHealthChecks) } h.HealthChecks.Active.ExpectBody = d.Val() case "health_follow_redirects": if d.NextArg() { return d.ArgErr() } if h.HealthChecks == nil { h.HealthChecks = new(HealthChecks) } if h.HealthChecks.Active == nil { h.HealthChecks.Active = new(ActiveHealthChecks) } h.HealthChecks.Active.FollowRedirects = true case "health_passes": if !d.NextArg() { return d.ArgErr() } if h.HealthChecks == nil { h.HealthChecks = new(HealthChecks) } if h.HealthChecks.Active == nil { h.HealthChecks.Active = new(ActiveHealthChecks) } passes, err := strconv.Atoi(d.Val()) if err != nil { return d.Errf("invalid passes count '%s': %v", d.Val(), err) } h.HealthChecks.Active.Passes = passes case "health_fails": if !d.NextArg() { return d.ArgErr() } if h.HealthChecks == nil { h.HealthChecks = new(HealthChecks) } if h.HealthChecks.Active == nil { h.HealthChecks.Active = new(ActiveHealthChecks) } fails, err := strconv.Atoi(d.Val()) if err != nil { return d.Errf("invalid fails count '%s': %v", d.Val(), err) } h.HealthChecks.Active.Fails = fails case "max_fails": if !d.NextArg() { return d.ArgErr() } if h.HealthChecks == nil { h.HealthChecks = new(HealthChecks) } if h.HealthChecks.Passive == nil { h.HealthChecks.Passive = new(PassiveHealthChecks) } maxFails, err := strconv.Atoi(d.Val()) if err != nil { return d.Errf("invalid maximum fail count '%s': %v", d.Val(), err) } h.HealthChecks.Passive.MaxFails = maxFails case "fail_duration": if !d.NextArg() { return d.ArgErr() } if h.HealthChecks == nil { h.HealthChecks = new(HealthChecks) } if h.HealthChecks.Passive == nil { h.HealthChecks.Passive = new(PassiveHealthChecks) } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("bad duration value '%s': %v", d.Val(), err) } h.HealthChecks.Passive.FailDuration = caddy.Duration(dur) case "unhealthy_request_count": if !d.NextArg() { return d.ArgErr() } if h.HealthChecks == nil { h.HealthChecks = new(HealthChecks) } if h.HealthChecks.Passive == nil { h.HealthChecks.Passive = new(PassiveHealthChecks) } maxConns, err := strconv.Atoi(d.Val()) if err != nil { return d.Errf("invalid maximum connection count '%s': %v", d.Val(), err) } h.HealthChecks.Passive.UnhealthyRequestCount = maxConns case "unhealthy_status": args := d.RemainingArgs() if len(args) == 0 { return d.ArgErr() } if h.HealthChecks == nil { h.HealthChecks = new(HealthChecks) } if h.HealthChecks.Passive == nil { h.HealthChecks.Passive = new(PassiveHealthChecks) } for _, arg := range args { if len(arg) == 3 && strings.HasSuffix(arg, "xx") { arg = arg[:1] } statusNum, err := strconv.Atoi(arg) if err != nil { return d.Errf("bad status value '%s': %v", d.Val(), err) } h.HealthChecks.Passive.UnhealthyStatus = append(h.HealthChecks.Passive.UnhealthyStatus, statusNum) } case "unhealthy_latency": if !d.NextArg() { return d.ArgErr() } if h.HealthChecks == nil { h.HealthChecks = new(HealthChecks) } if h.HealthChecks.Passive == nil { h.HealthChecks.Passive = new(PassiveHealthChecks) } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("bad duration value '%s': %v", d.Val(), err) } h.HealthChecks.Passive.UnhealthyLatency = caddy.Duration(dur) case "flush_interval": if !d.NextArg() { return d.ArgErr() } if fi, err := strconv.Atoi(d.Val()); err == nil { h.FlushInterval = caddy.Duration(fi) } else { dur, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("bad duration value '%s': %v", d.Val(), err) } h.FlushInterval = caddy.Duration(dur) } case "request_buffers", "response_buffers": subdir := d.Val() if !d.NextArg() { return d.ArgErr() } val := d.Val() var size int64 if val == "unlimited" { size = -1 } else { usize, err := humanize.ParseBytes(val) if err != nil { return d.Errf("invalid byte size '%s': %v", val, err) } size = int64(usize) } if d.NextArg() { return d.ArgErr() } switch subdir { case "request_buffers": h.RequestBuffers = size case "response_buffers": h.ResponseBuffers = size } case "stream_timeout": if !d.NextArg() { return d.ArgErr() } if fi, err := strconv.Atoi(d.Val()); err == nil { h.StreamTimeout = caddy.Duration(fi) } else { dur, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("bad duration value '%s': %v", d.Val(), err) } h.StreamTimeout = caddy.Duration(dur) } case "stream_close_delay": if !d.NextArg() { return d.ArgErr() } if fi, err := strconv.Atoi(d.Val()); err == nil { h.StreamCloseDelay = caddy.Duration(fi) } else { dur, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("bad duration value '%s': %v", d.Val(), err) } h.StreamCloseDelay = caddy.Duration(dur) } case "trusted_proxies": for d.NextArg() { if d.Val() == "private_ranges" { h.TrustedProxies = append(h.TrustedProxies, internal.PrivateRangesCIDR()...) continue } h.TrustedProxies = append(h.TrustedProxies, d.Val()) } case "header_up": var err error if h.Headers == nil { h.Headers = new(headers.Handler) } if h.Headers.Request == nil { h.Headers.Request = new(headers.HeaderOps) } args := d.RemainingArgs() switch len(args) { case 1: err = headers.CaddyfileHeaderOp(h.Headers.Request, args[0], "", nil) case 2: // some lint checks, I guess if strings.EqualFold(args[0], "host") && (args[1] == "{hostport}" || args[1] == "{http.request.hostport}") { caddy.Log().Named("caddyfile").Warn("Unnecessary header_up Host: the reverse proxy's default behavior is to pass headers to the upstream") } if strings.EqualFold(args[0], "x-forwarded-for") && (args[1] == "{remote}" || args[1] == "{http.request.remote}" || args[1] == "{remote_host}" || args[1] == "{http.request.remote.host}") { caddy.Log().Named("caddyfile").Warn("Unnecessary header_up X-Forwarded-For: the reverse proxy's default behavior is to pass headers to the upstream") } if strings.EqualFold(args[0], "x-forwarded-proto") && (args[1] == "{scheme}" || args[1] == "{http.request.scheme}") { caddy.Log().Named("caddyfile").Warn("Unnecessary header_up X-Forwarded-Proto: the reverse proxy's default behavior is to pass headers to the upstream") } if strings.EqualFold(args[0], "x-forwarded-host") && (args[1] == "{host}" || args[1] == "{http.request.host}" || args[1] == "{hostport}" || args[1] == "{http.request.hostport}") { caddy.Log().Named("caddyfile").Warn("Unnecessary header_up X-Forwarded-Host: the reverse proxy's default behavior is to pass headers to the upstream") } err = headers.CaddyfileHeaderOp(h.Headers.Request, args[0], args[1], nil) case 3: err = headers.CaddyfileHeaderOp(h.Headers.Request, args[0], args[1], &args[2]) default: return d.ArgErr() } if err != nil { return d.Err(err.Error()) } case "header_down": var err error if h.Headers == nil { h.Headers = new(headers.Handler) } if h.Headers.Response == nil { h.Headers.Response = &headers.RespHeaderOps{ HeaderOps: new(headers.HeaderOps), } } args := d.RemainingArgs() switch len(args) { case 1: err = headers.CaddyfileHeaderOp(h.Headers.Response.HeaderOps, args[0], "", nil) case 2: err = headers.CaddyfileHeaderOp(h.Headers.Response.HeaderOps, args[0], args[1], nil) case 3: err = headers.CaddyfileHeaderOp(h.Headers.Response.HeaderOps, args[0], args[1], &args[2]) default: return d.ArgErr() } if err != nil { return d.Err(err.Error()) } case "method": if !d.NextArg() { return d.ArgErr() } if h.Rewrite == nil { h.Rewrite = &rewrite.Rewrite{} } h.Rewrite.Method = d.Val() if d.NextArg() { return d.ArgErr() } case "rewrite": if !d.NextArg() { return d.ArgErr() } if h.Rewrite == nil { h.Rewrite = &rewrite.Rewrite{} } h.Rewrite.URI = d.Val() if d.NextArg() { return d.ArgErr() } case "transport": if !d.NextArg() { return d.ArgErr() } if h.TransportRaw != nil { return d.Err("transport already specified") } transportModuleName = d.Val() modID := "http.reverse_proxy.transport." + transportModuleName unm, err := caddyfile.UnmarshalModule(d, modID) if err != nil { return err } rt, ok := unm.(http.RoundTripper) if !ok { return d.Errf("module %s (%T) is not a RoundTripper", modID, unm) } transport = rt case "handle_response": // delegate the parsing of handle_response to the caller, // since we need the httpcaddyfile.Helper to parse subroutes. // See h.FinalizeUnmarshalCaddyfile h.handleResponseSegments = append(h.handleResponseSegments, d.NewFromNextSegment()) case "replace_status": args := d.RemainingArgs() if len(args) != 1 && len(args) != 2 { return d.Errf("must have one or two arguments: an optional response matcher, and a status code") } responseHandler := caddyhttp.ResponseHandler{} if len(args) == 2 { if !strings.HasPrefix(args[0], matcherPrefix) { return d.Errf("must use a named response matcher, starting with '@'") } foundMatcher, ok := h.responseMatchers[args[0]] if !ok { return d.Errf("no named response matcher defined with name '%s'", args[0][1:]) } responseHandler.Match = &foundMatcher responseHandler.StatusCode = caddyhttp.WeakString(args[1]) } else if len(args) == 1 { responseHandler.StatusCode = caddyhttp.WeakString(args[0]) } // make sure there's no block, cause it doesn't make sense if nesting := d.Nesting(); d.NextBlock(nesting) { return d.Errf("cannot define routes for 'replace_status', use 'handle_response' instead.") } h.HandleResponse = append( h.HandleResponse, responseHandler, ) case "verbose_logs": if h.VerboseLogs { return d.Err("verbose_logs already specified") } h.VerboseLogs = true default: return d.Errf("unrecognized subdirective %s", d.Val()) } } // if the scheme inferred from the backends' addresses is // HTTPS, we will need a non-nil transport to enable TLS, // or if H2C, to set the transport versions. if (commonScheme == "https" || commonScheme == "h2c") && transport == nil { transport = new(HTTPTransport) transportModuleName = "http" } // verify transport configuration, and finally encode it if transport != nil { if te, ok := transport.(TLSTransport); ok { if commonScheme == "https" && !te.TLSEnabled() { err := te.EnableTLS(new(TLSConfig)) if err != nil { return err } } if commonScheme == "http" && te.TLSEnabled() { return d.Errf("upstream address scheme is HTTP but transport is configured for HTTP+TLS (HTTPS)") } if h2ct, ok := transport.(H2CTransport); ok && commonScheme == "h2c" { err := h2ct.EnableH2C() if err != nil { return err } } } else if commonScheme == "https" { return d.Errf("upstreams are configured for HTTPS but transport module does not support TLS: %T", transport) } // no need to encode empty default transport if !reflect.DeepEqual(transport, new(HTTPTransport)) { h.TransportRaw = caddyconfig.JSONModuleObject(transport, "protocol", transportModuleName, nil) } } return nil } // FinalizeUnmarshalCaddyfile finalizes the Caddyfile parsing which // requires having an httpcaddyfile.Helper to function, to parse subroutes. func (h *Handler) FinalizeUnmarshalCaddyfile(helper httpcaddyfile.Helper) error { for _, d := range h.handleResponseSegments { // consume the "handle_response" token d.Next() args := d.RemainingArgs() // TODO: Remove this check at some point in the future if len(args) == 2 { return d.Errf("configuring 'handle_response' for status code replacement is no longer supported. Use 'replace_status' instead.") } if len(args) > 1 { return d.Errf("too many arguments for 'handle_response': %s", args) } var matcher *caddyhttp.ResponseMatcher if len(args) == 1 { // the first arg should always be a matcher. if !strings.HasPrefix(args[0], matcherPrefix) { return d.Errf("must use a named response matcher, starting with '@'") } foundMatcher, ok := h.responseMatchers[args[0]] if !ok { return d.Errf("no named response matcher defined with name '%s'", args[0][1:]) } matcher = &foundMatcher } // parse the block as routes handler, err := httpcaddyfile.ParseSegmentAsSubroute(helper.WithDispenser(d.NewFromNextSegment())) if err != nil { return err } subroute, ok := handler.(*caddyhttp.Subroute) if !ok { return helper.Errf("segment was not parsed as a subroute") } h.HandleResponse = append( h.HandleResponse, caddyhttp.ResponseHandler{ Match: matcher, Routes: subroute.Routes, }, ) } // move the handle_response entries without a matcher to the end. // we can't use sort.SliceStable because it will reorder the rest of the // entries which may be undesirable because we don't have a good // heuristic to use for sorting. withoutMatchers := []caddyhttp.ResponseHandler{} withMatchers := []caddyhttp.ResponseHandler{} for _, hr := range h.HandleResponse { if hr.Match == nil { withoutMatchers = append(withoutMatchers, hr) } else { withMatchers = append(withMatchers, hr) } } h.HandleResponse = append(withMatchers, withoutMatchers...) // clean up the bits we only needed for adapting h.handleResponseSegments = nil h.responseMatchers = nil return nil } // UnmarshalCaddyfile deserializes Caddyfile tokens into h. // // transport http { // read_buffer <size> // write_buffer <size> // max_response_header <size> // network_proxy <module> { // ... // } // dial_timeout <duration> // dial_fallback_delay <duration> // response_header_timeout <duration> // expect_continue_timeout <duration> // resolvers <resolvers...> // tls // tls_client_auth <automate_name> | <cert_file> <key_file> // tls_insecure_skip_verify // tls_timeout <duration> // tls_trusted_ca_certs <cert_files...> // tls_trust_pool <module> { // ... // } // tls_server_name <sni> // tls_renegotiation <level> // tls_except_ports <ports...> // keepalive [off|<duration>] // keepalive_interval <interval> // keepalive_idle_conns <max_count> // keepalive_idle_conns_per_host <count> // versions <versions...> // compression off // max_conns_per_host <count> // max_idle_conns_per_host <count> // } func (h *HTTPTransport) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume transport name for d.NextBlock(0) { switch d.Val() { case "read_buffer": if !d.NextArg() { return d.ArgErr() } size, err := humanize.ParseBytes(d.Val()) if err != nil { return d.Errf("invalid read buffer size '%s': %v", d.Val(), err) } h.ReadBufferSize = int(size) case "write_buffer": if !d.NextArg() { return d.ArgErr() } size, err := humanize.ParseBytes(d.Val()) if err != nil { return d.Errf("invalid write buffer size '%s': %v", d.Val(), err) } h.WriteBufferSize = int(size) case "read_timeout": if !d.NextArg() { return d.ArgErr() } timeout, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("invalid read timeout duration '%s': %v", d.Val(), err) } h.ReadTimeout = caddy.Duration(timeout) case "write_timeout": if !d.NextArg() { return d.ArgErr() } timeout, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("invalid write timeout duration '%s': %v", d.Val(), err) } h.WriteTimeout = caddy.Duration(timeout) case "max_response_header": if !d.NextArg() { return d.ArgErr() } size, err := humanize.ParseBytes(d.Val()) if err != nil { return d.Errf("invalid max response header size '%s': %v", d.Val(), err) } h.MaxResponseHeaderSize = int64(size) case "proxy_protocol": if !d.NextArg() { return d.ArgErr() } switch proxyProtocol := d.Val(); proxyProtocol { case "v1", "v2": h.ProxyProtocol = proxyProtocol default: return d.Errf("invalid proxy protocol version '%s'", proxyProtocol) } case "forward_proxy_url": caddy.Log().Warn("The 'forward_proxy_url' field is deprecated. Use 'network_proxy <url>' instead.") if !d.NextArg() { return d.ArgErr() } u := network.ProxyFromURL{URL: d.Val()} h.NetworkProxyRaw = caddyconfig.JSONModuleObject(u, "from", "url", nil) case "network_proxy": if !d.NextArg() { return d.ArgErr() } modStem := d.Val() modID := "caddy.network_proxy." + modStem unm, err := caddyfile.UnmarshalModule(d, modID) if err != nil { return err } h.NetworkProxyRaw = caddyconfig.JSONModuleObject(unm, "from", modStem, nil) case "dial_timeout": if !d.NextArg() { return d.ArgErr() } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("bad timeout value '%s': %v", d.Val(), err) } h.DialTimeout = caddy.Duration(dur) case "dial_fallback_delay": if !d.NextArg() { return d.ArgErr() } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("bad fallback delay value '%s': %v", d.Val(), err) } h.FallbackDelay = caddy.Duration(dur) case "response_header_timeout": if !d.NextArg() { return d.ArgErr() } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("bad timeout value '%s': %v", d.Val(), err) } h.ResponseHeaderTimeout = caddy.Duration(dur)
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
true
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/reverseproxy/httptransport.go
modules/caddyhttp/reverseproxy/httptransport.go
// Copyright 2015 Matthew Holt and The Caddy 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 reverseproxy import ( "context" "crypto/tls" "crypto/x509" "encoding/base64" "encoding/json" "fmt" weakrand "math/rand" "net" "net/http" "net/url" "os" "reflect" "slices" "strings" "time" "github.com/pires/go-proxyproto" "github.com/quic-go/quic-go/http3" "go.uber.org/zap" "go.uber.org/zap/zapcore" "golang.org/x/net/http2" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/modules/caddyhttp" "github.com/caddyserver/caddy/v2/modules/caddytls" "github.com/caddyserver/caddy/v2/modules/internal/network" ) func init() { caddy.RegisterModule(HTTPTransport{}) } // HTTPTransport is essentially a configuration wrapper for http.Transport. // It defines a JSON structure useful when configuring the HTTP transport // for Caddy's reverse proxy. It builds its http.Transport at Provision. type HTTPTransport struct { // TODO: It's possible that other transports (like fastcgi) might be // able to borrow/use at least some of these config fields; if so, // maybe move them into a type called CommonTransport and embed it? // Configures the DNS resolver used to resolve the IP address of upstream hostnames. Resolver *UpstreamResolver `json:"resolver,omitempty"` // Configures TLS to the upstream. Setting this to an empty struct // is sufficient to enable TLS with reasonable defaults. TLS *TLSConfig `json:"tls,omitempty"` // Configures HTTP Keep-Alive (enabled by default). Should only be // necessary if rigorous testing has shown that tuning this helps // improve performance. KeepAlive *KeepAlive `json:"keep_alive,omitempty"` // Whether to enable compression to upstream. Default: true Compression *bool `json:"compression,omitempty"` // Maximum number of connections per host. Default: 0 (no limit) MaxConnsPerHost int `json:"max_conns_per_host,omitempty"` // If non-empty, which PROXY protocol version to send when // connecting to an upstream. Default: off. ProxyProtocol string `json:"proxy_protocol,omitempty"` // URL to the server that the HTTP transport will use to proxy // requests to the upstream. See http.Transport.Proxy for // information regarding supported protocols. This value takes // precedence over `HTTP_PROXY`, etc. // // Providing a value to this parameter results in // requests flowing through the reverse_proxy in the following // way: // // User Agent -> // reverse_proxy -> // forward_proxy_url -> upstream // // Default: http.ProxyFromEnvironment // DEPRECATED: Use NetworkProxyRaw|`network_proxy` instead. Subject to removal. ForwardProxyURL string `json:"forward_proxy_url,omitempty"` // How long to wait before timing out trying to connect to // an upstream. Default: `3s`. DialTimeout caddy.Duration `json:"dial_timeout,omitempty"` // How long to wait before spawning an RFC 6555 Fast Fallback // connection. A negative value disables this. Default: `300ms`. FallbackDelay caddy.Duration `json:"dial_fallback_delay,omitempty"` // How long to wait for reading response headers from server. Default: No timeout. ResponseHeaderTimeout caddy.Duration `json:"response_header_timeout,omitempty"` // The length of time to wait for a server's first response // headers after fully writing the request headers if the // request has a header "Expect: 100-continue". Default: No timeout. ExpectContinueTimeout caddy.Duration `json:"expect_continue_timeout,omitempty"` // The maximum bytes to read from response headers. Default: `10MiB`. MaxResponseHeaderSize int64 `json:"max_response_header_size,omitempty"` // The size of the write buffer in bytes. Default: `4KiB`. WriteBufferSize int `json:"write_buffer_size,omitempty"` // The size of the read buffer in bytes. Default: `4KiB`. ReadBufferSize int `json:"read_buffer_size,omitempty"` // The maximum time to wait for next read from backend. Default: no timeout. ReadTimeout caddy.Duration `json:"read_timeout,omitempty"` // The maximum time to wait for next write to backend. Default: no timeout. WriteTimeout caddy.Duration `json:"write_timeout,omitempty"` // The versions of HTTP to support. As a special case, "h2c" // can be specified to use H2C (HTTP/2 over Cleartext) to the // upstream (this feature is experimental and subject to // change or removal). Default: ["1.1", "2"] // // EXPERIMENTAL: "3" enables HTTP/3, but it must be the only // version specified if enabled. Additionally, HTTPS must be // enabled to the upstream as HTTP/3 requires TLS. Subject // to change or removal while experimental. Versions []string `json:"versions,omitempty"` // Specify the address to bind to when connecting to an upstream. In other words, // it is the address the upstream sees as the remote address. LocalAddress string `json:"local_address,omitempty"` // The pre-configured underlying HTTP transport. Transport *http.Transport `json:"-"` // The module that provides the network (forward) proxy // URL that the HTTP transport will use to proxy // requests to the upstream. See [http.Transport.Proxy](https://pkg.go.dev/net/http#Transport.Proxy) // for information regarding supported protocols. // // Providing a value to this parameter results in requests // flowing through the reverse_proxy in the following way: // // User Agent -> // reverse_proxy -> // [proxy provided by the module] -> upstream // // If nil, defaults to reading the `HTTP_PROXY`, // `HTTPS_PROXY`, and `NO_PROXY` environment variables. NetworkProxyRaw json.RawMessage `json:"network_proxy,omitempty" caddy:"namespace=caddy.network_proxy inline_key=from"` h3Transport *http3.Transport // TODO: EXPERIMENTAL (May 2024) } // CaddyModule returns the Caddy module information. func (HTTPTransport) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.reverse_proxy.transport.http", New: func() caddy.Module { return new(HTTPTransport) }, } } var ( allowedVersions = []string{"1.1", "2", "h2c", "3"} allowedVersionsString = strings.Join(allowedVersions, ", ") ) // Provision sets up h.Transport with a *http.Transport // that is ready to use. func (h *HTTPTransport) Provision(ctx caddy.Context) error { if len(h.Versions) == 0 { h.Versions = []string{"1.1", "2"} } // some users may provide http versions not recognized by caddy, instead of trying to // guess the version, we just error out and let the user fix their config // see: https://github.com/caddyserver/caddy/issues/7111 for _, v := range h.Versions { if !slices.Contains(allowedVersions, v) { return fmt.Errorf("unsupported HTTP version: %s, supported version: %s", v, allowedVersionsString) } } rt, err := h.NewTransport(ctx) if err != nil { return err } h.Transport = rt return nil } // NewTransport builds a standard-lib-compatible http.Transport value from h. func (h *HTTPTransport) NewTransport(caddyCtx caddy.Context) (*http.Transport, error) { // Set keep-alive defaults if it wasn't otherwise configured if h.KeepAlive == nil { h.KeepAlive = new(KeepAlive) } if h.KeepAlive.ProbeInterval == 0 { h.KeepAlive.ProbeInterval = caddy.Duration(30 * time.Second) } if h.KeepAlive.IdleConnTimeout == 0 { h.KeepAlive.IdleConnTimeout = caddy.Duration(2 * time.Minute) } if h.KeepAlive.MaxIdleConnsPerHost == 0 { h.KeepAlive.MaxIdleConnsPerHost = 32 // seems about optimal, see #2805 } // Set a relatively short default dial timeout. // This is helpful to make load-balancer retries more speedy. if h.DialTimeout == 0 { h.DialTimeout = caddy.Duration(3 * time.Second) } dialer := &net.Dialer{ Timeout: time.Duration(h.DialTimeout), FallbackDelay: time.Duration(h.FallbackDelay), } if h.LocalAddress != "" { netaddr, err := caddy.ParseNetworkAddressWithDefaults(h.LocalAddress, "tcp", 0) if err != nil { return nil, err } if netaddr.PortRangeSize() > 1 { return nil, fmt.Errorf("local_address must be a single address, not a port range") } switch netaddr.Network { case "tcp", "tcp4", "tcp6": dialer.LocalAddr, err = net.ResolveTCPAddr(netaddr.Network, netaddr.JoinHostPort(0)) if err != nil { return nil, err } case "unix", "unixgram", "unixpacket": dialer.LocalAddr, err = net.ResolveUnixAddr(netaddr.Network, netaddr.JoinHostPort(0)) if err != nil { return nil, err } case "udp", "udp4", "udp6": return nil, fmt.Errorf("local_address must be a TCP address, not a UDP address") default: return nil, fmt.Errorf("unsupported network") } } if h.Resolver != nil { err := h.Resolver.ParseAddresses() if err != nil { return nil, err } d := &net.Dialer{ Timeout: time.Duration(h.DialTimeout), FallbackDelay: time.Duration(h.FallbackDelay), } dialer.Resolver = &net.Resolver{ PreferGo: true, Dial: func(ctx context.Context, _, _ string) (net.Conn, error) { //nolint:gosec addr := h.Resolver.netAddrs[weakrand.Intn(len(h.Resolver.netAddrs))] return d.DialContext(ctx, addr.Network, addr.JoinHostPort(0)) }, } } dialContext := func(ctx context.Context, network, address string) (net.Conn, error) { // The network is usually tcp, and the address is the host in http.Request.URL.Host // and that's been overwritten in directRequest // However, if proxy is used according to http.ProxyFromEnvironment or proxy providers, // address will be the address of the proxy server. // This means we can safely use the address in dialInfo if proxy is not used (the address and network will be same any way) // or if the upstream is unix (because there is no way socks or http proxy can be used for unix address). if dialInfo, ok := GetDialInfo(ctx); ok { if caddyhttp.GetVar(ctx, proxyVarKey) == nil || strings.HasPrefix(dialInfo.Network, "unix") { network = dialInfo.Network address = dialInfo.Address } } conn, err := dialer.DialContext(ctx, network, address) if err != nil { // identify this error as one that occurred during // dialing, which can be important when trying to // decide whether to retry a request return nil, DialError{err} } if h.ProxyProtocol != "" { proxyProtocolInfo, ok := caddyhttp.GetVar(ctx, proxyProtocolInfoVarKey).(ProxyProtocolInfo) if !ok { return nil, fmt.Errorf("failed to get proxy protocol info from context") } var proxyv byte switch h.ProxyProtocol { case "v1": proxyv = 1 case "v2": proxyv = 2 default: return nil, fmt.Errorf("unexpected proxy protocol version") } // The src and dst have to be of the same address family. As we don't know the original // dst address (it's kind of impossible to know) and this address is generally of very // little interest, we just set it to all zeros. var destAddr net.Addr switch { case proxyProtocolInfo.AddrPort.Addr().Is4(): destAddr = &net.TCPAddr{ IP: net.IPv4zero, } case proxyProtocolInfo.AddrPort.Addr().Is6(): destAddr = &net.TCPAddr{ IP: net.IPv6zero, } default: return nil, fmt.Errorf("unexpected remote addr type in proxy protocol info") } sourceAddr := &net.TCPAddr{ IP: proxyProtocolInfo.AddrPort.Addr().AsSlice(), Port: int(proxyProtocolInfo.AddrPort.Port()), Zone: proxyProtocolInfo.AddrPort.Addr().Zone(), } header := proxyproto.HeaderProxyFromAddrs(proxyv, sourceAddr, destAddr) // retain the log message structure switch h.ProxyProtocol { case "v1": caddyCtx.Logger().Debug("sending proxy protocol header v1", zap.Any("header", header)) case "v2": caddyCtx.Logger().Debug("sending proxy protocol header v2", zap.Any("header", header)) } _, err = header.WriteTo(conn) if err != nil { // identify this error as one that occurred during // dialing, which can be important when trying to // decide whether to retry a request return nil, DialError{err} } } // if read/write timeouts are configured and this is a TCP connection, // enforce the timeouts by wrapping the connection with our own type if tcpConn, ok := conn.(*net.TCPConn); ok && (h.ReadTimeout > 0 || h.WriteTimeout > 0) { conn = &tcpRWTimeoutConn{ TCPConn: tcpConn, readTimeout: time.Duration(h.ReadTimeout), writeTimeout: time.Duration(h.WriteTimeout), logger: caddyCtx.Logger(), } } return conn, nil } // negotiate any HTTP/SOCKS proxy for the HTTP transport proxy := http.ProxyFromEnvironment if h.ForwardProxyURL != "" { caddyCtx.Logger().Warn("forward_proxy_url is deprecated; use network_proxy instead") u := network.ProxyFromURL{URL: h.ForwardProxyURL} h.NetworkProxyRaw = caddyconfig.JSONModuleObject(u, "from", "url", nil) } if len(h.NetworkProxyRaw) != 0 { proxyMod, err := caddyCtx.LoadModule(h, "NetworkProxyRaw") if err != nil { return nil, fmt.Errorf("failed to load network_proxy module: %v", err) } if m, ok := proxyMod.(caddy.ProxyFuncProducer); ok { proxy = m.ProxyFunc() } else { return nil, fmt.Errorf("network_proxy module is not `(func(*http.Request) (*url.URL, error))``") } } // we need to keep track if a proxy is used for a request proxyWrapper := func(req *http.Request) (*url.URL, error) { u, err := proxy(req) if u == nil || err != nil { return u, err } // there must be a proxy for this request caddyhttp.SetVar(req.Context(), proxyVarKey, u) return u, nil } rt := &http.Transport{ Proxy: proxyWrapper, DialContext: dialContext, MaxConnsPerHost: h.MaxConnsPerHost, ResponseHeaderTimeout: time.Duration(h.ResponseHeaderTimeout), ExpectContinueTimeout: time.Duration(h.ExpectContinueTimeout), MaxResponseHeaderBytes: h.MaxResponseHeaderSize, WriteBufferSize: h.WriteBufferSize, ReadBufferSize: h.ReadBufferSize, } if h.TLS != nil { rt.TLSHandshakeTimeout = time.Duration(h.TLS.HandshakeTimeout) var err error rt.TLSClientConfig, err = h.TLS.MakeTLSClientConfig(caddyCtx) if err != nil { return nil, fmt.Errorf("making TLS client config: %v", err) } // servername has a placeholder, so we need to replace it if strings.Contains(h.TLS.ServerName, "{") { rt.DialTLSContext = func(ctx context.Context, network, addr string) (net.Conn, error) { // reuses the dialer from above to establish a plaintext connection conn, err := dialContext(ctx, network, addr) if err != nil { return nil, err } // but add our own handshake logic repl := ctx.Value(caddy.ReplacerCtxKey).(*caddy.Replacer) tlsConfig := rt.TLSClientConfig.Clone() tlsConfig.ServerName = repl.ReplaceAll(tlsConfig.ServerName, "") // h1 only if caddyhttp.GetVar(ctx, tlsH1OnlyVarKey) == true { // stdlib does this // https://github.com/golang/go/blob/4837fbe4145cd47b43eed66fee9eed9c2b988316/src/net/http/transport.go#L1701 tlsConfig.NextProtos = nil } tlsConn := tls.Client(conn, tlsConfig) // complete the handshake before returning the connection if rt.TLSHandshakeTimeout != 0 { var cancel context.CancelFunc ctx, cancel = context.WithTimeout(ctx, rt.TLSHandshakeTimeout) defer cancel() } err = tlsConn.HandshakeContext(ctx) if err != nil { _ = tlsConn.Close() return nil, err } return tlsConn, nil } } } if h.KeepAlive != nil { // according to https://pkg.go.dev/net#Dialer.KeepAliveConfig, // KeepAlive is ignored if KeepAliveConfig.Enable is true. // If configured to 0, a system-dependent default is used. // To disable tcp keepalive, choose a negative value, // so KeepAliveConfig.Enable is false and KeepAlive is negative. // This is different from http keepalive where a tcp connection // can transfer multiple http requests/responses. dialer.KeepAlive = time.Duration(h.KeepAlive.ProbeInterval) dialer.KeepAliveConfig = net.KeepAliveConfig{ Enable: h.KeepAlive.ProbeInterval > 0, Interval: time.Duration(h.KeepAlive.ProbeInterval), } if h.KeepAlive.Enabled != nil { rt.DisableKeepAlives = !*h.KeepAlive.Enabled } rt.MaxIdleConns = h.KeepAlive.MaxIdleConns rt.MaxIdleConnsPerHost = h.KeepAlive.MaxIdleConnsPerHost rt.IdleConnTimeout = time.Duration(h.KeepAlive.IdleConnTimeout) } if h.Compression != nil { rt.DisableCompression = !*h.Compression } // configure HTTP/3 transport if enabled; however, this does not // automatically fall back to lower versions like most web browsers // do (that'd add latency and complexity, besides, we expect that // site owners control the backends), so it must be exclusive if len(h.Versions) == 1 && h.Versions[0] == "3" { h.h3Transport = new(http3.Transport) if h.TLS != nil { var err error h.h3Transport.TLSClientConfig, err = h.TLS.MakeTLSClientConfig(caddyCtx) if err != nil { return nil, fmt.Errorf("making TLS client config for HTTP/3 transport: %v", err) } } } else if len(h.Versions) > 1 && slices.Contains(h.Versions, "3") { return nil, fmt.Errorf("if HTTP/3 is enabled to the upstream, no other HTTP versions are supported") } // if h2/c is enabled, configure it explicitly if slices.Contains(h.Versions, "2") || slices.Contains(h.Versions, "h2c") { if err := http2.ConfigureTransport(rt); err != nil { return nil, err } // DisableCompression from h2 is configured by http2.ConfigureTransport // Likewise, DisableKeepAlives from h1 is used too. // Protocols field is only used when the request is not using TLS, // http1/2 over tls is still allowed if slices.Contains(h.Versions, "h2c") { rt.Protocols = new(http.Protocols) rt.Protocols.SetUnencryptedHTTP2(true) rt.Protocols.SetHTTP1(false) } } return rt, nil } // RoundTrip implements http.RoundTripper. func (h *HTTPTransport) RoundTrip(req *http.Request) (*http.Response, error) { h.SetScheme(req) // use HTTP/3 if enabled (TODO: This is EXPERIMENTAL) if h.h3Transport != nil { return h.h3Transport.RoundTrip(req) } return h.Transport.RoundTrip(req) } // SetScheme ensures that the outbound request req // has the scheme set in its URL; the underlying // http.Transport requires a scheme to be set. // // This method may be used by other transport modules // that wrap/use this one. func (h *HTTPTransport) SetScheme(req *http.Request) { if req.URL.Scheme != "" { return } if h.shouldUseTLS(req) { req.URL.Scheme = "https" } else { req.URL.Scheme = "http" } } // shouldUseTLS returns true if TLS should be used for req. func (h *HTTPTransport) shouldUseTLS(req *http.Request) bool { if h.TLS == nil { return false } port := req.URL.Port() return !slices.Contains(h.TLS.ExceptPorts, port) } // TLSEnabled returns true if TLS is enabled. func (h HTTPTransport) TLSEnabled() bool { return h.TLS != nil } // EnableTLS enables TLS on the transport. func (h *HTTPTransport) EnableTLS(base *TLSConfig) error { h.TLS = base return nil } // EnableH2C enables H2C (HTTP/2 over Cleartext) on the transport. func (h *HTTPTransport) EnableH2C() error { h.Versions = []string{"h2c", "2"} return nil } // OverrideHealthCheckScheme overrides the scheme of the given URL // used for health checks. func (h HTTPTransport) OverrideHealthCheckScheme(base *url.URL, port string) { // if tls is enabled and the port isn't in the except list, use HTTPs if h.TLSEnabled() && !slices.Contains(h.TLS.ExceptPorts, port) { base.Scheme = "https" } } // ProxyProtocolEnabled returns true if proxy protocol is enabled. func (h HTTPTransport) ProxyProtocolEnabled() bool { return h.ProxyProtocol != "" } // Cleanup implements caddy.CleanerUpper and closes any idle connections. func (h HTTPTransport) Cleanup() error { if h.Transport == nil { return nil } h.Transport.CloseIdleConnections() return nil } // TLSConfig holds configuration related to the TLS configuration for the // transport/client. type TLSConfig struct { // Certificate authority module which provides the certificate pool of trusted certificates CARaw json.RawMessage `json:"ca,omitempty" caddy:"namespace=tls.ca_pool.source inline_key=provider"` // Deprecated: Use the `ca` field with the `tls.ca_pool.source.inline` module instead. // Optional list of base64-encoded DER-encoded CA certificates to trust. RootCAPool []string `json:"root_ca_pool,omitempty"` // Deprecated: Use the `ca` field with the `tls.ca_pool.source.file` module instead. // List of PEM-encoded CA certificate files to add to the same trust // store as RootCAPool (or root_ca_pool in the JSON). RootCAPEMFiles []string `json:"root_ca_pem_files,omitempty"` // PEM-encoded client certificate filename to present to servers. ClientCertificateFile string `json:"client_certificate_file,omitempty"` // PEM-encoded key to use with the client certificate. ClientCertificateKeyFile string `json:"client_certificate_key_file,omitempty"` // If specified, Caddy will use and automate a client certificate // with this subject name. ClientCertificateAutomate string `json:"client_certificate_automate,omitempty"` // If true, TLS verification of server certificates will be disabled. // This is insecure and may be removed in the future. Do not use this // option except in testing or local development environments. InsecureSkipVerify bool `json:"insecure_skip_verify,omitempty"` // The duration to allow a TLS handshake to a server. Default: No timeout. HandshakeTimeout caddy.Duration `json:"handshake_timeout,omitempty"` // The server name used when verifying the certificate received in the TLS // handshake. By default, this will use the upstream address' host part. // You only need to override this if your upstream address does not match the // certificate the upstream is likely to use. For example if the upstream // address is an IP address, then you would need to configure this to the // hostname being served by the upstream server. Currently, this does not // support placeholders because the TLS config is not provisioned on each // connection, so a static value must be used. ServerName string `json:"server_name,omitempty"` // TLS renegotiation level. TLS renegotiation is the act of performing // subsequent handshakes on a connection after the first. // The level can be: // - "never": (the default) disables renegotiation. // - "once": allows a remote server to request renegotiation once per connection. // - "freely": allows a remote server to repeatedly request renegotiation. Renegotiation string `json:"renegotiation,omitempty"` // Skip TLS ports specifies a list of upstream ports on which TLS should not be // attempted even if it is configured. Handy when using dynamic upstreams that // return HTTP and HTTPS endpoints too. // When specified, TLS will automatically be configured on the transport. // The value can be a list of any valid tcp port numbers, default empty. ExceptPorts []string `json:"except_ports,omitempty"` // The list of elliptic curves to support. Caddy's // defaults are modern and secure. Curves []string `json:"curves,omitempty"` } // MakeTLSClientConfig returns a tls.Config usable by a client to a backend. // If there is no custom TLS configuration, a nil config may be returned. func (t *TLSConfig) MakeTLSClientConfig(ctx caddy.Context) (*tls.Config, error) { cfg := new(tls.Config) // client auth if t.ClientCertificateFile != "" && t.ClientCertificateKeyFile == "" { return nil, fmt.Errorf("client_certificate_file specified without client_certificate_key_file") } if t.ClientCertificateFile == "" && t.ClientCertificateKeyFile != "" { return nil, fmt.Errorf("client_certificate_key_file specified without client_certificate_file") } if t.ClientCertificateFile != "" && t.ClientCertificateKeyFile != "" { cert, err := tls.LoadX509KeyPair(t.ClientCertificateFile, t.ClientCertificateKeyFile) if err != nil { return nil, fmt.Errorf("loading client certificate key pair: %v", err) } cfg.Certificates = []tls.Certificate{cert} } if t.ClientCertificateAutomate != "" { // TODO: use or enable ctx.IdentityCredentials() ... tlsAppIface, err := ctx.App("tls") if err != nil { return nil, fmt.Errorf("getting tls app: %v", err) } tlsApp := tlsAppIface.(*caddytls.TLS) err = tlsApp.Manage(map[string]struct{}{t.ClientCertificateAutomate: {}}) if err != nil { return nil, fmt.Errorf("managing client certificate: %v", err) } cfg.GetClientCertificate = func(cri *tls.CertificateRequestInfo) (*tls.Certificate, error) { certs := caddytls.AllMatchingCertificates(t.ClientCertificateAutomate) var err error for _, cert := range certs { certCertificate := cert.Certificate // avoid taking address of iteration variable (gosec warning) err = cri.SupportsCertificate(&certCertificate) if err == nil { return &cert.Certificate, nil } } if err == nil { err = fmt.Errorf("no client certificate found for automate name: %s", t.ClientCertificateAutomate) } return nil, err } } // trusted root CAs if len(t.RootCAPool) > 0 || len(t.RootCAPEMFiles) > 0 { ctx.Logger().Warn("root_ca_pool and root_ca_pem_files are deprecated. Use one of the tls.ca_pool.source modules instead") rootPool := x509.NewCertPool() for _, encodedCACert := range t.RootCAPool { caCert, err := decodeBase64DERCert(encodedCACert) if err != nil { return nil, fmt.Errorf("parsing CA certificate: %v", err) } rootPool.AddCert(caCert) } for _, pemFile := range t.RootCAPEMFiles { pemData, err := os.ReadFile(pemFile) if err != nil { return nil, fmt.Errorf("failed reading ca cert: %v", err) } rootPool.AppendCertsFromPEM(pemData) } cfg.RootCAs = rootPool } if t.CARaw != nil { if len(t.RootCAPool) > 0 || len(t.RootCAPEMFiles) > 0 { return nil, fmt.Errorf("conflicting config for Root CA pool") } caRaw, err := ctx.LoadModule(t, "CARaw") if err != nil { return nil, fmt.Errorf("failed to load ca module: %v", err) } ca, ok := caRaw.(caddytls.CA) if !ok { return nil, fmt.Errorf("CA module '%s' is not a certificate pool provider", ca) } cfg.RootCAs = ca.CertPool() } // Renegotiation switch t.Renegotiation { case "never", "": cfg.Renegotiation = tls.RenegotiateNever case "once": cfg.Renegotiation = tls.RenegotiateOnceAsClient case "freely": cfg.Renegotiation = tls.RenegotiateFreelyAsClient default: return nil, fmt.Errorf("invalid TLS renegotiation level: %v", t.Renegotiation) } // override for the server name used verify the TLS handshake cfg.ServerName = t.ServerName // throw all security out the window cfg.InsecureSkipVerify = t.InsecureSkipVerify curvesAdded := make(map[tls.CurveID]struct{}) for _, curveName := range t.Curves { curveID := caddytls.SupportedCurves[curveName] if _, ok := curvesAdded[curveID]; !ok { curvesAdded[curveID] = struct{}{} cfg.CurvePreferences = append(cfg.CurvePreferences, curveID) } } // only return a config if it's not empty if reflect.DeepEqual(cfg, new(tls.Config)) { return nil, nil } return cfg, nil } // KeepAlive holds configuration pertaining to HTTP Keep-Alive. type KeepAlive struct { // Whether HTTP Keep-Alive is enabled. Default: `true` Enabled *bool `json:"enabled,omitempty"` // How often to probe for liveness. Default: `30s`. ProbeInterval caddy.Duration `json:"probe_interval,omitempty"` // Maximum number of idle connections. Default: `0`, which means no limit. MaxIdleConns int `json:"max_idle_conns,omitempty"` // Maximum number of idle connections per host. Default: `32`. MaxIdleConnsPerHost int `json:"max_idle_conns_per_host,omitempty"` // How long connections should be kept alive when idle. Default: `2m`. IdleConnTimeout caddy.Duration `json:"idle_timeout,omitempty"` } // tcpRWTimeoutConn enforces read/write timeouts for a TCP connection. // If it fails to set deadlines, the error is logged but does not abort // the read/write attempt (ignoring the error is consistent with what // the standard library does: https://github.com/golang/go/blob/c5da4fb7ac5cb7434b41fc9a1df3bee66c7f1a4d/src/net/http/server.go#L981-L986) type tcpRWTimeoutConn struct { *net.TCPConn readTimeout, writeTimeout time.Duration logger *zap.Logger } func (c *tcpRWTimeoutConn) Read(b []byte) (int, error) { if c.readTimeout > 0 { err := c.TCPConn.SetReadDeadline(time.Now().Add(c.readTimeout)) if err != nil { if ce := c.logger.Check(zapcore.ErrorLevel, "failed to set read deadline"); ce != nil { ce.Write(zap.Error(err)) } } } return c.TCPConn.Read(b) } func (c *tcpRWTimeoutConn) Write(b []byte) (int, error) { if c.writeTimeout > 0 { err := c.TCPConn.SetWriteDeadline(time.Now().Add(c.writeTimeout)) if err != nil { if ce := c.logger.Check(zapcore.ErrorLevel, "failed to set write deadline"); ce != nil { ce.Write(zap.Error(err)) } } } return c.TCPConn.Write(b) } // decodeBase64DERCert base64-decodes, then DER-decodes, certStr. func decodeBase64DERCert(certStr string) (*x509.Certificate, error) { // decode base64 derBytes, err := base64.StdEncoding.DecodeString(certStr) if err != nil { return nil, err } // parse the DER-encoded certificate return x509.ParseCertificate(derBytes) } // Interface guards var ( _ caddy.Provisioner = (*HTTPTransport)(nil) _ http.RoundTripper = (*HTTPTransport)(nil) _ caddy.CleanerUpper = (*HTTPTransport)(nil) _ TLSTransport = (*HTTPTransport)(nil) _ H2CTransport = (*HTTPTransport)(nil) _ HealthCheckSchemeOverriderTransport = (*HTTPTransport)(nil) _ ProxyProtocolTransport = (*HTTPTransport)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/reverseproxy/addresses_test.go
modules/caddyhttp/reverseproxy/addresses_test.go
// Copyright 2015 Matthew Holt and The Caddy 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 reverseproxy import "testing" func TestParseUpstreamDialAddress(t *testing.T) { for i, tc := range []struct { input string expectHostPort string expectScheme string expectErr bool }{ { input: "foo", expectHostPort: "foo:80", }, { input: "foo:1234", expectHostPort: "foo:1234", }, { input: "127.0.0.1", expectHostPort: "127.0.0.1:80", }, { input: "127.0.0.1:1234", expectHostPort: "127.0.0.1:1234", }, { input: "[::1]", expectHostPort: "[::1]:80", }, { input: "[::1]:1234", expectHostPort: "[::1]:1234", }, { input: "{foo}", expectHostPort: "{foo}", }, { input: "{foo}:80", expectHostPort: "{foo}:80", }, { input: "{foo}:{bar}", expectHostPort: "{foo}:{bar}", }, { input: "http://foo", expectHostPort: "foo:80", expectScheme: "http", }, { input: "http://foo:1234", expectHostPort: "foo:1234", expectScheme: "http", }, { input: "http://127.0.0.1", expectHostPort: "127.0.0.1:80", expectScheme: "http", }, { input: "http://127.0.0.1:1234", expectHostPort: "127.0.0.1:1234", expectScheme: "http", }, { input: "http://[::1]", expectHostPort: "[::1]:80", expectScheme: "http", }, { input: "http://[::1]:80", expectHostPort: "[::1]:80", expectScheme: "http", }, { input: "https://foo", expectHostPort: "foo:443", expectScheme: "https", }, { input: "https://foo:1234", expectHostPort: "foo:1234", expectScheme: "https", }, { input: "https://127.0.0.1", expectHostPort: "127.0.0.1:443", expectScheme: "https", }, { input: "https://127.0.0.1:1234", expectHostPort: "127.0.0.1:1234", expectScheme: "https", }, { input: "https://[::1]", expectHostPort: "[::1]:443", expectScheme: "https", }, { input: "https://[::1]:1234", expectHostPort: "[::1]:1234", expectScheme: "https", }, { input: "h2c://foo", expectHostPort: "foo:80", expectScheme: "h2c", }, { input: "h2c://foo:1234", expectHostPort: "foo:1234", expectScheme: "h2c", }, { input: "h2c://127.0.0.1", expectHostPort: "127.0.0.1:80", expectScheme: "h2c", }, { input: "h2c://127.0.0.1:1234", expectHostPort: "127.0.0.1:1234", expectScheme: "h2c", }, { input: "h2c://[::1]", expectHostPort: "[::1]:80", expectScheme: "h2c", }, { input: "h2c://[::1]:1234", expectHostPort: "[::1]:1234", expectScheme: "h2c", }, { input: "localhost:1001-1009", expectHostPort: "localhost:1001-1009", }, { input: "{host}:1001-1009", expectHostPort: "{host}:1001-1009", }, { input: "http://localhost:1001-1009", expectHostPort: "localhost:1001-1009", expectScheme: "http", }, { input: "https://localhost:1001-1009", expectHostPort: "localhost:1001-1009", expectScheme: "https", }, { input: "unix//var/php.sock", expectHostPort: "unix//var/php.sock", }, { input: "unix+h2c//var/grpc.sock", expectHostPort: "unix//var/grpc.sock", expectScheme: "h2c", }, { input: "unix/{foo}", expectHostPort: "unix/{foo}", }, { input: "unix+h2c/{foo}", expectHostPort: "unix/{foo}", expectScheme: "h2c", }, { input: "unix//foo/{foo}/bar", expectHostPort: "unix//foo/{foo}/bar", }, { input: "unix+h2c//foo/{foo}/bar", expectHostPort: "unix//foo/{foo}/bar", expectScheme: "h2c", }, { input: "http://{foo}", expectErr: true, }, { input: "http:// :80", expectErr: true, }, { input: "http://localhost/path", expectErr: true, }, { input: "http://localhost?key=value", expectErr: true, }, { input: "http://localhost#fragment", expectErr: true, }, { input: "http://localhost:8001-8002-8003", expectErr: true, }, { input: "http://localhost:8001-8002/foo:bar", expectErr: true, }, { input: "http://localhost:8001-8002/foo:1", expectErr: true, }, { input: "http://localhost:8001-8002/foo:1-2", expectErr: true, }, { input: "http://localhost:8001-8002#foo:1", expectErr: true, }, { input: "http://foo:443", expectErr: true, }, { input: "https://foo:80", expectErr: true, }, { input: "h2c://foo:443", expectErr: true, }, { input: `unix/c:\absolute\path`, expectHostPort: `unix/c:\absolute\path`, }, { input: `unix+h2c/c:\absolute\path`, expectHostPort: `unix/c:\absolute\path`, expectScheme: "h2c", }, { input: "unix/c:/absolute/path", expectHostPort: "unix/c:/absolute/path", }, { input: "unix+h2c/c:/absolute/path", expectHostPort: "unix/c:/absolute/path", expectScheme: "h2c", }, } { actualAddr, err := parseUpstreamDialAddress(tc.input) if tc.expectErr && err == nil { t.Errorf("Test %d: Expected error but got %v", i, err) } if !tc.expectErr && err != nil { t.Errorf("Test %d: Expected no error but got %v", i, err) } if actualAddr.dialAddr() != tc.expectHostPort { t.Errorf("Test %d: input %s: Expected host and port '%s' but got '%s'", i, tc.input, tc.expectHostPort, actualAddr.dialAddr()) } if actualAddr.scheme != tc.expectScheme { t.Errorf("Test %d: Expected scheme '%s' but got '%s'", i, tc.expectScheme, actualAddr.scheme) } } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/reverseproxy/ascii_test.go
modules/caddyhttp/reverseproxy/ascii_test.go
// Copyright 2015 Matthew Holt and The Caddy 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. // Most of the code in this file was initially borrowed from the Go // standard library and modified; It had this copyright notice: // Copyright 2021 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Original source, copied because the package was marked internal: // https://github.com/golang/go/blob/5c489514bc5e61ad9b5b07bd7d8ec65d66a0512a/src/net/http/internal/ascii/print_test.go package reverseproxy import "testing" func TestEqualFold(t *testing.T) { tests := []struct { name string a, b string want bool }{ { name: "empty", want: true, }, { name: "simple match", a: "CHUNKED", b: "chunked", want: true, }, { name: "same string", a: "chunked", b: "chunked", want: true, }, { name: "Unicode Kelvin symbol", a: "chunKed", // This "K" is 'KELVIN SIGN' (\u212A) b: "chunked", want: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := asciiEqualFold(tt.a, tt.b); got != tt.want { t.Errorf("AsciiEqualFold(%q,%q): got %v want %v", tt.a, tt.b, got, tt.want) } }) } } func TestIsPrint(t *testing.T) { tests := []struct { name string in string want bool }{ { name: "empty", want: true, }, { name: "ASCII low", in: "This is a space: ' '", want: true, }, { name: "ASCII high", in: "This is a tilde: '~'", want: true, }, { name: "ASCII low non-print", in: "This is a unit separator: \x1F", want: false, }, { name: "Ascii high non-print", in: "This is a Delete: \x7F", want: false, }, { name: "Unicode letter", in: "Today it's 280K outside: it's freezing!", // This "K" is 'KELVIN SIGN' (\u212A) want: false, }, { name: "Unicode emoji", in: "Gophers like 🧀", want: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := asciiIsPrint(tt.in); got != tt.want { t.Errorf("IsASCIIPrint(%q): got %v want %v", tt.in, got, tt.want) } }) } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/reverseproxy/buffering_test.go
modules/caddyhttp/reverseproxy/buffering_test.go
package reverseproxy import ( "io" "testing" ) type zeroReader struct{} func (zeroReader) Read(p []byte) (int, error) { for i := range p { p[i] = 0 } return len(p), nil } func TestBuffering(t *testing.T) { var ( h Handler zr zeroReader ) type args struct { body io.ReadCloser limit int64 } tests := []struct { name string args args resultCheck func(io.ReadCloser, int64, args) bool }{ { name: "0 limit, body is returned as is", args: args{ body: io.NopCloser(&zr), limit: 0, }, resultCheck: func(res io.ReadCloser, read int64, args args) bool { return res == args.body && read == args.limit && read == 0 }, }, { name: "negative limit, body is read completely", args: args{ body: io.NopCloser(io.LimitReader(&zr, 100)), limit: -1, }, resultCheck: func(res io.ReadCloser, read int64, args args) bool { brc, ok := res.(bodyReadCloser) return ok && brc.body == nil && brc.buf.Len() == 100 && read == 100 }, }, { name: "positive limit, body is read partially", args: args{ body: io.NopCloser(io.LimitReader(&zr, 100)), limit: 50, }, resultCheck: func(res io.ReadCloser, read int64, args args) bool { brc, ok := res.(bodyReadCloser) return ok && brc.body != nil && brc.buf.Len() == 50 && read == 50 }, }, { name: "positive limit, body is read completely", args: args{ body: io.NopCloser(io.LimitReader(&zr, 100)), limit: 101, }, resultCheck: func(res io.ReadCloser, read int64, args args) bool { brc, ok := res.(bodyReadCloser) return ok && brc.body == nil && brc.buf.Len() == 100 && read == 100 }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { res, read := h.bufferedBody(tt.args.body, tt.args.limit) if !tt.resultCheck(res, read, tt.args) { t.Error("Handler.bufferedBody() test failed") return } }) } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/reverseproxy/ascii.go
modules/caddyhttp/reverseproxy/ascii.go
// Copyright 2015 Matthew Holt and The Caddy 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. // Most of the code in this file was initially borrowed from the Go // standard library and modified; It had this copyright notice: // Copyright 2021 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Original source, copied because the package was marked internal: // https://github.com/golang/go/blob/5c489514bc5e61ad9b5b07bd7d8ec65d66a0512a/src/net/http/internal/ascii/print.go package reverseproxy // asciiEqualFold is strings.EqualFold, ASCII only. It reports whether s and t // are equal, ASCII-case-insensitively. func asciiEqualFold(s, t string) bool { if len(s) != len(t) { return false } for i := 0; i < len(s); i++ { if asciiLower(s[i]) != asciiLower(t[i]) { return false } } return true } // asciiLower returns the ASCII lowercase version of b. func asciiLower(b byte) byte { if 'A' <= b && b <= 'Z' { return b + ('a' - 'A') } return b } // asciiIsPrint returns whether s is ASCII and printable according to // https://tools.ietf.org/html/rfc20#section-4.2. func asciiIsPrint(s string) bool { for i := 0; i < len(s); i++ { if s[i] < ' ' || s[i] > '~' { return false } } return true }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/reverseproxy/reverseproxy.go
modules/caddyhttp/reverseproxy/reverseproxy.go
// Copyright 2015 Matthew Holt and The Caddy 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 reverseproxy import ( "bytes" "context" "crypto/rand" "encoding/base64" "encoding/json" "errors" "fmt" "io" "net" "net/http" "net/http/httptrace" "net/netip" "net/textproto" "net/url" "strconv" "strings" "sync" "time" "go.uber.org/zap" "go.uber.org/zap/zapcore" "golang.org/x/net/http/httpguts" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/modules/caddyevents" "github.com/caddyserver/caddy/v2/modules/caddyhttp" "github.com/caddyserver/caddy/v2/modules/caddyhttp/headers" "github.com/caddyserver/caddy/v2/modules/caddyhttp/rewrite" ) func init() { caddy.RegisterModule(Handler{}) } // Handler implements a highly configurable and production-ready reverse proxy. // // Upon proxying, this module sets the following placeholders (which can be used // both within and after this handler; for example, in response headers): // // Placeholder | Description // ------------|------------- // `{http.reverse_proxy.upstream.address}` | The full address to the upstream as given in the config // `{http.reverse_proxy.upstream.hostport}` | The host:port of the upstream // `{http.reverse_proxy.upstream.host}` | The host of the upstream // `{http.reverse_proxy.upstream.port}` | The port of the upstream // `{http.reverse_proxy.upstream.requests}` | The approximate current number of requests to the upstream // `{http.reverse_proxy.upstream.max_requests}` | The maximum approximate number of requests allowed to the upstream // `{http.reverse_proxy.upstream.fails}` | The number of recent failed requests to the upstream // `{http.reverse_proxy.upstream.latency}` | How long it took the proxy upstream to write the response header. // `{http.reverse_proxy.upstream.latency_ms}` | Same as 'latency', but in milliseconds. // `{http.reverse_proxy.upstream.duration}` | Time spent proxying to the upstream, including writing response body to client. // `{http.reverse_proxy.upstream.duration_ms}` | Same as 'upstream.duration', but in milliseconds. // `{http.reverse_proxy.duration}` | Total time spent proxying, including selecting an upstream, retries, and writing response. // `{http.reverse_proxy.duration_ms}` | Same as 'duration', but in milliseconds. // `{http.reverse_proxy.retries}` | The number of retries actually performed to communicate with an upstream. type Handler struct { // Configures the method of transport for the proxy. A transport // is what performs the actual "round trip" to the backend. // The default transport is plaintext HTTP. TransportRaw json.RawMessage `json:"transport,omitempty" caddy:"namespace=http.reverse_proxy.transport inline_key=protocol"` // A circuit breaker may be used to relieve pressure on a backend // that is beginning to exhibit symptoms of stress or latency. // By default, there is no circuit breaker. CBRaw json.RawMessage `json:"circuit_breaker,omitempty" caddy:"namespace=http.reverse_proxy.circuit_breakers inline_key=type"` // Load balancing distributes load/requests between backends. LoadBalancing *LoadBalancing `json:"load_balancing,omitempty"` // Health checks update the status of backends, whether they are // up or down. Down backends will not be proxied to. HealthChecks *HealthChecks `json:"health_checks,omitempty"` // Upstreams is the static list of backends to proxy to. Upstreams UpstreamPool `json:"upstreams,omitempty"` // A module for retrieving the list of upstreams dynamically. Dynamic // upstreams are retrieved at every iteration of the proxy loop for // each request (i.e. before every proxy attempt within every request). // Active health checks do not work on dynamic upstreams, and passive // health checks are only effective on dynamic upstreams if the proxy // server is busy enough that concurrent requests to the same backends // are continuous. Instead of health checks for dynamic upstreams, it // is recommended that the dynamic upstream module only return available // backends in the first place. DynamicUpstreamsRaw json.RawMessage `json:"dynamic_upstreams,omitempty" caddy:"namespace=http.reverse_proxy.upstreams inline_key=source"` // Adjusts how often to flush the response buffer. By default, // no periodic flushing is done. A negative value disables // response buffering, and flushes immediately after each // write to the client. This option is ignored when the upstream's // response is recognized as a streaming response, or if its // content length is -1; for such responses, writes are flushed // to the client immediately. FlushInterval caddy.Duration `json:"flush_interval,omitempty"` // A list of IP ranges (supports CIDR notation) from which // X-Forwarded-* header values should be trusted. By default, // no proxies are trusted, so existing values will be ignored // when setting these headers. If the proxy is trusted, then // existing values will be used when constructing the final // header values. TrustedProxies []string `json:"trusted_proxies,omitempty"` // Headers manipulates headers between Caddy and the backend. // By default, all headers are passed-thru without changes, // with the exceptions of special hop-by-hop headers. // // X-Forwarded-For, X-Forwarded-Proto and X-Forwarded-Host // are also set implicitly. Headers *headers.Handler `json:"headers,omitempty"` // If nonzero, the entire request body up to this size will be read // and buffered in memory before being proxied to the backend. This // should be avoided if at all possible for performance reasons, but // could be useful if the backend is intolerant of read latency or // chunked encodings. RequestBuffers int64 `json:"request_buffers,omitempty"` // If nonzero, the entire response body up to this size will be read // and buffered in memory before being proxied to the client. This // should be avoided if at all possible for performance reasons, but // could be useful if the backend has tighter memory constraints. ResponseBuffers int64 `json:"response_buffers,omitempty"` // If nonzero, streaming requests such as WebSockets will be // forcibly closed at the end of the timeout. Default: no timeout. StreamTimeout caddy.Duration `json:"stream_timeout,omitempty"` // If nonzero, streaming requests such as WebSockets will not be // closed when the proxy config is unloaded, and instead the stream // will remain open until the delay is complete. In other words, // enabling this prevents streams from closing when Caddy's config // is reloaded. Enabling this may be a good idea to avoid a thundering // herd of reconnecting clients which had their connections closed // by the previous config closing. Default: no delay. StreamCloseDelay caddy.Duration `json:"stream_close_delay,omitempty"` // If configured, rewrites the copy of the upstream request. // Allows changing the request method and URI (path and query). // Since the rewrite is applied to the copy, it does not persist // past the reverse proxy handler. // If the method is changed to `GET` or `HEAD`, the request body // will not be copied to the backend. This allows a later request // handler -- either in a `handle_response` route, or after -- to // read the body. // By default, no rewrite is performed, and the method and URI // from the incoming request is used as-is for proxying. Rewrite *rewrite.Rewrite `json:"rewrite,omitempty"` // List of handlers and their associated matchers to evaluate // after successful roundtrips. The first handler that matches // the response from a backend will be invoked. The response // body from the backend will not be written to the client; // it is up to the handler to finish handling the response. // If passive health checks are enabled, any errors from the // handler chain will not affect the health status of the // backend. // // Three new placeholders are available in this handler chain: // - `{http.reverse_proxy.status_code}` The status code from the response // - `{http.reverse_proxy.status_text}` The status text from the response // - `{http.reverse_proxy.header.*}` The headers from the response HandleResponse []caddyhttp.ResponseHandler `json:"handle_response,omitempty"` // If set, the proxy will write very detailed logs about its // inner workings. Enable this only when debugging, as it // will produce a lot of output. // // EXPERIMENTAL: This feature is subject to change or removal. VerboseLogs bool `json:"verbose_logs,omitempty"` Transport http.RoundTripper `json:"-"` CB CircuitBreaker `json:"-"` DynamicUpstreams UpstreamSource `json:"-"` // Holds the parsed CIDR ranges from TrustedProxies trustedProxies []netip.Prefix // Holds the named response matchers from the Caddyfile while adapting responseMatchers map[string]caddyhttp.ResponseMatcher // Holds the handle_response Caddyfile tokens while adapting handleResponseSegments []*caddyfile.Dispenser // Stores upgraded requests (hijacked connections) for proper cleanup connections map[io.ReadWriteCloser]openConnection connectionsCloseTimer *time.Timer connectionsMu *sync.Mutex ctx caddy.Context logger *zap.Logger events *caddyevents.App } // CaddyModule returns the Caddy module information. func (Handler) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.handlers.reverse_proxy", New: func() caddy.Module { return new(Handler) }, } } // Provision ensures that h is set up properly before use. func (h *Handler) Provision(ctx caddy.Context) error { eventAppIface, err := ctx.App("events") if err != nil { return fmt.Errorf("getting events app: %v", err) } h.events = eventAppIface.(*caddyevents.App) h.ctx = ctx h.logger = ctx.Logger() h.connections = make(map[io.ReadWriteCloser]openConnection) h.connectionsMu = new(sync.Mutex) // warn about unsafe buffering config if h.RequestBuffers == -1 || h.ResponseBuffers == -1 { h.logger.Warn("UNLIMITED BUFFERING: buffering is enabled without any cap on buffer size, which can result in OOM crashes") } // start by loading modules if h.TransportRaw != nil { mod, err := ctx.LoadModule(h, "TransportRaw") if err != nil { return fmt.Errorf("loading transport: %v", err) } h.Transport = mod.(http.RoundTripper) // set default buffer sizes if applicable if bt, ok := h.Transport.(BufferedTransport); ok { reqBuffers, respBuffers := bt.DefaultBufferSizes() if h.RequestBuffers == 0 { h.RequestBuffers = reqBuffers } if h.ResponseBuffers == 0 { h.ResponseBuffers = respBuffers } } } if h.LoadBalancing != nil && h.LoadBalancing.SelectionPolicyRaw != nil { mod, err := ctx.LoadModule(h.LoadBalancing, "SelectionPolicyRaw") if err != nil { return fmt.Errorf("loading load balancing selection policy: %s", err) } h.LoadBalancing.SelectionPolicy = mod.(Selector) } if h.CBRaw != nil { mod, err := ctx.LoadModule(h, "CBRaw") if err != nil { return fmt.Errorf("loading circuit breaker: %s", err) } h.CB = mod.(CircuitBreaker) } if h.DynamicUpstreamsRaw != nil { mod, err := ctx.LoadModule(h, "DynamicUpstreamsRaw") if err != nil { return fmt.Errorf("loading upstream source module: %v", err) } h.DynamicUpstreams = mod.(UpstreamSource) } // parse trusted proxy CIDRs ahead of time for _, str := range h.TrustedProxies { if strings.Contains(str, "/") { ipNet, err := netip.ParsePrefix(str) if err != nil { return fmt.Errorf("parsing CIDR expression: '%s': %v", str, err) } h.trustedProxies = append(h.trustedProxies, ipNet) } else { ipAddr, err := netip.ParseAddr(str) if err != nil { return fmt.Errorf("invalid IP address: '%s': %v", str, err) } ipNew := netip.PrefixFrom(ipAddr, ipAddr.BitLen()) h.trustedProxies = append(h.trustedProxies, ipNew) } } // ensure any embedded headers handler module gets provisioned // (see https://caddy.community/t/set-cookie-manipulation-in-reverse-proxy/7666?u=matt // for what happens if we forget to provision it) if h.Headers != nil { err := h.Headers.Provision(ctx) if err != nil { return fmt.Errorf("provisioning embedded headers handler: %v", err) } } if h.Rewrite != nil { err := h.Rewrite.Provision(ctx) if err != nil { return fmt.Errorf("provisioning rewrite: %v", err) } } // set up transport if h.Transport == nil { t := &HTTPTransport{} err := t.Provision(ctx) if err != nil { return fmt.Errorf("provisioning default transport: %v", err) } h.Transport = t } // set up load balancing if h.LoadBalancing == nil { h.LoadBalancing = new(LoadBalancing) } if h.LoadBalancing.SelectionPolicy == nil { h.LoadBalancing.SelectionPolicy = RandomSelection{} } if h.LoadBalancing.TryDuration > 0 && h.LoadBalancing.TryInterval == 0 { // a non-zero try_duration with a zero try_interval // will always spin the CPU for try_duration if the // upstream is local or low-latency; avoid that by // defaulting to a sane wait period between attempts h.LoadBalancing.TryInterval = caddy.Duration(250 * time.Millisecond) } lbMatcherSets, err := ctx.LoadModule(h.LoadBalancing, "RetryMatchRaw") if err != nil { return err } err = h.LoadBalancing.RetryMatch.FromInterface(lbMatcherSets) if err != nil { return err } // set up upstreams for _, u := range h.Upstreams { h.provisionUpstream(u) } if h.HealthChecks != nil { // set defaults on passive health checks, if necessary if h.HealthChecks.Passive != nil { h.HealthChecks.Passive.logger = h.logger.Named("health_checker.passive") if h.HealthChecks.Passive.MaxFails == 0 { h.HealthChecks.Passive.MaxFails = 1 } } // if active health checks are enabled, configure them and start a worker if h.HealthChecks.Active != nil { err := h.HealthChecks.Active.Provision(ctx, h) if err != nil { return err } if h.HealthChecks.Active.IsEnabled() { go h.activeHealthChecker() } } } // set up any response routes for i, rh := range h.HandleResponse { err := rh.Provision(ctx) if err != nil { return fmt.Errorf("provisioning response handler %d: %v", i, err) } } upstreamHealthyUpdater := newMetricsUpstreamsHealthyUpdater(h, ctx) upstreamHealthyUpdater.init() return nil } // Cleanup cleans up the resources made by h. func (h *Handler) Cleanup() error { err := h.cleanupConnections() // remove hosts from our config from the pool for _, upstream := range h.Upstreams { _, _ = hosts.Delete(upstream.String()) } return err } func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) // prepare the request for proxying; this is needed only once clonedReq, err := h.prepareRequest(r, repl) if err != nil { return caddyhttp.Error(http.StatusInternalServerError, fmt.Errorf("preparing request for upstream round-trip: %v", err)) } // websocket over http2 or http3 if extended connect is enabled, assuming backend doesn't support this, the request will be modified to http1.1 upgrade // Both use the same upgrade mechanism: server advertizes extended connect support, and client sends the pseudo header :protocol in a CONNECT request // The quic-go http3 implementation also puts :protocol in r.Proto for CONNECT requests (quic-go/http3/headers.go@70-72,185,203) // TODO: once we can reliably detect backend support this, it can be removed for those backends if (r.ProtoMajor == 2 && r.Method == http.MethodConnect && r.Header.Get(":protocol") == "websocket") || (r.ProtoMajor == 3 && r.Method == http.MethodConnect && r.Proto == "websocket") { clonedReq.Header.Del(":protocol") // keep the body for later use. http1.1 upgrade uses http.NoBody caddyhttp.SetVar(clonedReq.Context(), "extended_connect_websocket_body", clonedReq.Body) clonedReq.Body = http.NoBody clonedReq.Method = http.MethodGet clonedReq.Header.Set("Upgrade", "websocket") clonedReq.Header.Set("Connection", "Upgrade") key := make([]byte, 16) _, randErr := rand.Read(key) if randErr != nil { return randErr } clonedReq.Header["Sec-WebSocket-Key"] = []string{base64.StdEncoding.EncodeToString(key)} } // we will need the original headers and Host value if // header operations are configured; this is so that each // retry can apply the modifications, because placeholders // may be used which depend on the selected upstream for // their values reqHost := clonedReq.Host reqHeader := clonedReq.Header // If the cloned request body was fully buffered, keep a reference to its // buffer so we can reuse it across retries and return it to the pool // once we’re done. var bufferedReqBody *bytes.Buffer if reqBodyBuf, ok := clonedReq.Body.(bodyReadCloser); ok && reqBodyBuf.body == nil && reqBodyBuf.buf != nil { bufferedReqBody = reqBodyBuf.buf reqBodyBuf.buf = nil defer func() { bufferedReqBody.Reset() bufPool.Put(bufferedReqBody) }() } start := time.Now() defer func() { // total proxying duration, including time spent on LB and retries repl.Set("http.reverse_proxy.duration", time.Since(start)) repl.Set("http.reverse_proxy.duration_ms", time.Since(start).Seconds()*1e3) // multiply seconds to preserve decimal (see #4666) }() // in the proxy loop, each iteration is an attempt to proxy the request, // and because we may retry some number of times, carry over the error // from previous tries because of the nuances of load balancing & retries var proxyErr error var retries int for { // if the request body was buffered (and only the entire body, hence no body // set to read from after the buffer), make reading from the body idempotent // and reusable, so if a backend partially or fully reads the body but then // produces an error, the request can be repeated to the next backend with // the full body (retries should only happen for idempotent requests) (see #6259) if bufferedReqBody != nil { clonedReq.Body = io.NopCloser(bytes.NewReader(bufferedReqBody.Bytes())) } var done bool done, proxyErr = h.proxyLoopIteration(clonedReq, r, w, proxyErr, start, retries, repl, reqHeader, reqHost, next) if done { break } if h.VerboseLogs { var lbWait time.Duration if h.LoadBalancing != nil { lbWait = time.Duration(h.LoadBalancing.TryInterval) } if c := h.logger.Check(zapcore.DebugLevel, "retrying"); c != nil { c.Write(zap.Error(proxyErr), zap.Duration("after", lbWait)) } } retries++ } // number of retries actually performed repl.Set("http.reverse_proxy.retries", retries) if proxyErr != nil { return statusError(proxyErr) } return nil } // proxyLoopIteration implements an iteration of the proxy loop. Despite the enormous amount of local state // that has to be passed in, we brought this into its own method so that we could run defer more easily. // It returns true when the loop is done and should break; false otherwise. The error value returned should // be assigned to the proxyErr value for the next iteration of the loop (or the error handled after break). func (h *Handler) proxyLoopIteration(r *http.Request, origReq *http.Request, w http.ResponseWriter, proxyErr error, start time.Time, retries int, repl *caddy.Replacer, reqHeader http.Header, reqHost string, next caddyhttp.Handler, ) (bool, error) { // get the updated list of upstreams upstreams := h.Upstreams if h.DynamicUpstreams != nil { dUpstreams, err := h.DynamicUpstreams.GetUpstreams(r) if err != nil { if c := h.logger.Check(zapcore.ErrorLevel, "failed getting dynamic upstreams; falling back to static upstreams"); c != nil { c.Write(zap.Error(err)) } } else { upstreams = dUpstreams for _, dUp := range dUpstreams { h.provisionUpstream(dUp) } if c := h.logger.Check(zapcore.DebugLevel, "provisioned dynamic upstreams"); c != nil { c.Write(zap.Int("count", len(dUpstreams))) } defer func() { // these upstreams are dynamic, so they are only used for this iteration // of the proxy loop; be sure to let them go away when we're done with them for _, upstream := range dUpstreams { _, _ = hosts.Delete(upstream.String()) } }() } } // choose an available upstream upstream := h.LoadBalancing.SelectionPolicy.Select(upstreams, r, w) if upstream == nil { if proxyErr == nil { proxyErr = caddyhttp.Error(http.StatusServiceUnavailable, errNoUpstream) } if !h.LoadBalancing.tryAgain(h.ctx, start, retries, proxyErr, r, h.logger) { return true, proxyErr } return false, proxyErr } // the dial address may vary per-request if placeholders are // used, so perform those replacements here; the resulting // DialInfo struct should have valid network address syntax dialInfo, err := upstream.fillDialInfo(repl) if err != nil { return true, fmt.Errorf("making dial info: %v", err) } if c := h.logger.Check(zapcore.DebugLevel, "selected upstream"); c != nil { c.Write( zap.String("dial", dialInfo.Address), zap.Int("total_upstreams", len(upstreams)), ) } // attach to the request information about how to dial the upstream; // this is necessary because the information cannot be sufficiently // or satisfactorily represented in a URL caddyhttp.SetVar(r.Context(), dialInfoVarKey, dialInfo) // set placeholders with information about this upstream repl.Set("http.reverse_proxy.upstream.address", dialInfo.String()) repl.Set("http.reverse_proxy.upstream.hostport", dialInfo.Address) repl.Set("http.reverse_proxy.upstream.host", dialInfo.Host) repl.Set("http.reverse_proxy.upstream.port", dialInfo.Port) repl.Set("http.reverse_proxy.upstream.requests", upstream.Host.NumRequests()) repl.Set("http.reverse_proxy.upstream.max_requests", upstream.MaxRequests) repl.Set("http.reverse_proxy.upstream.fails", upstream.Host.Fails()) // mutate request headers according to this upstream; // because we're in a retry loop, we have to copy // headers (and the r.Host value) from the original // so that each retry is identical to the first if h.Headers != nil && h.Headers.Request != nil { r.Header = make(http.Header) copyHeader(r.Header, reqHeader) r.Host = reqHost h.Headers.Request.ApplyToRequest(r) } // proxy the request to that upstream proxyErr = h.reverseProxy(w, r, origReq, repl, dialInfo, next) if proxyErr == nil || errors.Is(proxyErr, context.Canceled) { // context.Canceled happens when the downstream client // cancels the request, which is not our failure return true, nil } // if the roundtrip was successful, don't retry the request or // ding the health status of the upstream (an error can still // occur after the roundtrip if, for example, a response handler // after the roundtrip returns an error) if succ, ok := proxyErr.(roundtripSucceededError); ok { return true, succ.error } // remember this failure (if enabled) h.countFailure(upstream) // if we've tried long enough, break if !h.LoadBalancing.tryAgain(h.ctx, start, retries, proxyErr, r, h.logger) { return true, proxyErr } return false, proxyErr } // Mapping of the canonical form of the headers, to the RFC 6455 form, // i.e. `WebSocket` with uppercase 'S'. var websocketHeaderMapping = map[string]string{ "Sec-Websocket-Accept": "Sec-WebSocket-Accept", "Sec-Websocket-Extensions": "Sec-WebSocket-Extensions", "Sec-Websocket-Key": "Sec-WebSocket-Key", "Sec-Websocket-Protocol": "Sec-WebSocket-Protocol", "Sec-Websocket-Version": "Sec-WebSocket-Version", } // normalizeWebsocketHeaders ensures we use the standard casing as per // RFC 6455, i.e. `WebSocket` with uppercase 'S'. Most servers don't // care about this difference (read headers case insensitively), but // some do, so this maximizes compatibility with upstreams. // See https://github.com/caddyserver/caddy/pull/6621 func normalizeWebsocketHeaders(header http.Header) { for k, rk := range websocketHeaderMapping { if v, ok := header[k]; ok { delete(header, k) header[rk] = v } } } // prepareRequest clones req so that it can be safely modified without // changing the original request or introducing data races. It then // modifies it so that it is ready to be proxied, except for directing // to a specific upstream. This method adjusts headers and other relevant // properties of the cloned request and should be done just once (before // proxying) regardless of proxy retries. This assumes that no mutations // of the cloned request are performed by h during or after proxying. func (h Handler) prepareRequest(req *http.Request, repl *caddy.Replacer) (*http.Request, error) { req = cloneRequest(req) // if enabled, perform rewrites on the cloned request; if // the method is GET or HEAD, prevent the request body // from being copied to the upstream if h.Rewrite != nil { changed := h.Rewrite.Rewrite(req, repl) if changed && (h.Rewrite.Method == "GET" || h.Rewrite.Method == "HEAD") { req.ContentLength = 0 req.Body = nil } } // if enabled, buffer client request; this should only be // enabled if the upstream requires it and does not work // with "slow clients" (gunicorn, etc.) - this obviously // has a perf overhead and makes the proxy at risk of // exhausting memory and more susceptible to slowloris // attacks, so it is strongly recommended to only use this // feature if absolutely required, if read timeouts are // set, and if body size is limited if h.RequestBuffers != 0 && req.Body != nil { var readBytes int64 req.Body, readBytes = h.bufferedBody(req.Body, h.RequestBuffers) // set Content-Length when body is fully buffered if b, ok := req.Body.(bodyReadCloser); ok && b.body == nil { req.ContentLength = readBytes req.Header.Set("Content-Length", strconv.FormatInt(req.ContentLength, 10)) } } if req.ContentLength == 0 { req.Body = nil // Issue golang/go#16036: nil Body for http.Transport retries } req.Close = false // if User-Agent is not set by client, then explicitly // disable it so it's not set to default value by std lib if _, ok := req.Header["User-Agent"]; !ok { req.Header.Set("User-Agent", "") } // Indicate if request has been conveyed in early data. // RFC 8470: "An intermediary that forwards a request prior to the // completion of the TLS handshake with its client MUST send it with // the Early-Data header field set to “1” (i.e., it adds it if not // present in the request). An intermediary MUST use the Early-Data // header field if the request might have been subject to a replay and // might already have been forwarded by it or another instance // (see Section 6.2)." if req.TLS != nil && !req.TLS.HandshakeComplete { req.Header.Set("Early-Data", "1") } reqUpgradeType := upgradeType(req.Header) removeConnectionHeaders(req.Header) // Remove hop-by-hop headers to the backend. Especially // important is "Connection" because we want a persistent // connection, regardless of what the client sent to us. // Issue golang/go#46313: don't skip if field is empty. for _, h := range hopHeaders { // Issue golang/go#21096: tell backend applications that care about trailer support // that we support trailers. (We do, but we don't go out of our way to // advertise that unless the incoming client request thought it was worth // mentioning.) if h == "Te" && httpguts.HeaderValuesContainsToken(req.Header["Te"], "trailers") { req.Header.Set("Te", "trailers") continue } req.Header.Del(h) } // After stripping all the hop-by-hop connection headers above, add back any // necessary for protocol upgrades, such as for websockets. if reqUpgradeType != "" { req.Header.Set("Connection", "Upgrade") req.Header.Set("Upgrade", reqUpgradeType) normalizeWebsocketHeaders(req.Header) } // Set up the PROXY protocol info address := caddyhttp.GetVar(req.Context(), caddyhttp.ClientIPVarKey).(string) addrPort, err := netip.ParseAddrPort(address) if err != nil { // OK; probably didn't have a port addr, err := netip.ParseAddr(address) if err != nil { // Doesn't seem like a valid ip address at all } else { // Ok, only the port was missing addrPort = netip.AddrPortFrom(addr, 0) } } proxyProtocolInfo := ProxyProtocolInfo{AddrPort: addrPort} caddyhttp.SetVar(req.Context(), proxyProtocolInfoVarKey, proxyProtocolInfo) // some of the outbound requests require h1 (e.g. websocket) // https://github.com/golang/go/blob/4837fbe4145cd47b43eed66fee9eed9c2b988316/src/net/http/request.go#L1579 if isWebsocket(req) { caddyhttp.SetVar(req.Context(), tlsH1OnlyVarKey, true) } // Add the supported X-Forwarded-* headers err = h.addForwardedHeaders(req) if err != nil { return nil, err } // Via header(s) req.Header.Add("Via", fmt.Sprintf("%d.%d Caddy", req.ProtoMajor, req.ProtoMinor)) return req, nil } // addForwardedHeaders adds the de-facto standard X-Forwarded-* // headers to the request before it is sent upstream. // // These headers are security sensitive, so care is taken to only // use existing values for these headers from the incoming request // if the client IP is trusted (i.e. coming from a trusted proxy // sitting in front of this server). If the request didn't have // the headers at all, then they will be added with the values // that we can glean from the request. func (h Handler) addForwardedHeaders(req *http.Request) error { // Parse the remote IP, ignore the error as non-fatal, // but the remote IP is required to continue, so we // just return early. This should probably never happen // though, unless some other module manipulated the request's // remote address and used an invalid value. clientIP, _, err := net.SplitHostPort(req.RemoteAddr) if err != nil { // Remove the `X-Forwarded-*` headers to avoid upstreams // potentially trusting a header that came from the client req.Header.Del("X-Forwarded-For") req.Header.Del("X-Forwarded-Proto") req.Header.Del("X-Forwarded-Host") return nil } // Client IP may contain a zone if IPv6, so we need // to pull that out before parsing the IP clientIP, _, _ = strings.Cut(clientIP, "%") ipAddr, err := netip.ParseAddr(clientIP) if err != nil { return fmt.Errorf("invalid IP address: '%s': %v", clientIP, err) } // Check if the client is a trusted proxy trusted := caddyhttp.GetVar(req.Context(), caddyhttp.TrustedProxyVarKey).(bool) for _, ipRange := range h.trustedProxies { if ipRange.Contains(ipAddr) { trusted = true break } } // If we aren't the first proxy, and the proxy is trusted, // retain prior X-Forwarded-For information as a comma+space // separated list and fold multiple headers into one. clientXFF := clientIP prior, ok, omit := allHeaderValues(req.Header, "X-Forwarded-For") if trusted && ok && prior != "" { clientXFF = prior + ", " + clientXFF } if !omit { req.Header.Set("X-Forwarded-For", clientXFF) } // Set X-Forwarded-Proto; many backend apps expect this, // so that they can properly craft URLs with the right // scheme to match the original request proto := "https" if req.TLS == nil { proto = "http" } prior, ok, omit = lastHeaderValue(req.Header, "X-Forwarded-Proto") if trusted && ok && prior != "" { proto = prior } if !omit { req.Header.Set("X-Forwarded-Proto", proto) } // Set X-Forwarded-Host; often this is redundant because // we pass through the request Host as-is, but in situations // where we proxy over HTTPS, the user may need to override // Host themselves, so it's helpful to send the original too. host := req.Host prior, ok, omit = lastHeaderValue(req.Header, "X-Forwarded-Host") if trusted && ok && prior != "" { host = prior } if !omit { req.Header.Set("X-Forwarded-Host", host) } return nil } // reverseProxy performs a round-trip to the given backend and processes the response with the client. // (This method is mostly the beginning of what was borrowed from the net/http/httputil package in the // Go standard library which was used as the foundation.)
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
true
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/reverseproxy/copyresponse.go
modules/caddyhttp/reverseproxy/copyresponse.go
// Copyright 2015 Matthew Holt and The Caddy 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 reverseproxy import ( "fmt" "net/http" "strconv" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func init() { caddy.RegisterModule(CopyResponseHandler{}) caddy.RegisterModule(CopyResponseHeadersHandler{}) } // CopyResponseHandler is a special HTTP handler which may // only be used within reverse_proxy's handle_response routes, // to copy the proxy response. EXPERIMENTAL, subject to change. type CopyResponseHandler struct { // To write the upstream response's body but with a different // status code, set this field to the desired status code. StatusCode caddyhttp.WeakString `json:"status_code,omitempty"` ctx caddy.Context } // CaddyModule returns the Caddy module information. func (CopyResponseHandler) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.handlers.copy_response", New: func() caddy.Module { return new(CopyResponseHandler) }, } } // Provision ensures that h is set up properly before use. func (h *CopyResponseHandler) Provision(ctx caddy.Context) error { h.ctx = ctx return nil } // ServeHTTP implements the Handler interface. func (h CopyResponseHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request, _ caddyhttp.Handler) error { repl := req.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) hrc, ok := req.Context().Value(proxyHandleResponseContextCtxKey).(*handleResponseContext) // don't allow this to be used outside of handle_response routes if !ok { return caddyhttp.Error(http.StatusInternalServerError, fmt.Errorf("cannot use 'copy_response' outside of reverse_proxy's handle_response routes")) } // allow a custom status code to be written; otherwise the // status code from the upstream response is written if codeStr := h.StatusCode.String(); codeStr != "" { intVal, err := strconv.Atoi(repl.ReplaceAll(codeStr, "")) if err != nil { return caddyhttp.Error(http.StatusInternalServerError, err) } hrc.response.StatusCode = intVal } // make sure the reverse_proxy handler doesn't try to call // finalizeResponse again after we've already done it here. hrc.isFinalized = true // write the response return hrc.handler.finalizeResponse(rw, req, hrc.response, repl, hrc.start, hrc.logger) } // CopyResponseHeadersHandler is a special HTTP handler which may // only be used within reverse_proxy's handle_response routes, // to copy headers from the proxy response. EXPERIMENTAL; // subject to change. type CopyResponseHeadersHandler struct { // A list of header fields to copy from the response. // Cannot be defined at the same time as Exclude. Include []string `json:"include,omitempty"` // A list of header fields to skip copying from the response. // Cannot be defined at the same time as Include. Exclude []string `json:"exclude,omitempty"` includeMap map[string]struct{} excludeMap map[string]struct{} ctx caddy.Context } // CaddyModule returns the Caddy module information. func (CopyResponseHeadersHandler) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.handlers.copy_response_headers", New: func() caddy.Module { return new(CopyResponseHeadersHandler) }, } } // Validate ensures the h's configuration is valid. func (h *CopyResponseHeadersHandler) Validate() error { if len(h.Exclude) > 0 && len(h.Include) > 0 { return fmt.Errorf("cannot define both 'exclude' and 'include' lists at the same time") } return nil } // Provision ensures that h is set up properly before use. func (h *CopyResponseHeadersHandler) Provision(ctx caddy.Context) error { h.ctx = ctx // Optimize the include list by converting it to a map if len(h.Include) > 0 { h.includeMap = map[string]struct{}{} } for _, field := range h.Include { h.includeMap[http.CanonicalHeaderKey(field)] = struct{}{} } // Optimize the exclude list by converting it to a map if len(h.Exclude) > 0 { h.excludeMap = map[string]struct{}{} } for _, field := range h.Exclude { h.excludeMap[http.CanonicalHeaderKey(field)] = struct{}{} } return nil } // ServeHTTP implements the Handler interface. func (h CopyResponseHeadersHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request, next caddyhttp.Handler) error { hrc, ok := req.Context().Value(proxyHandleResponseContextCtxKey).(*handleResponseContext) // don't allow this to be used outside of handle_response routes if !ok { return caddyhttp.Error(http.StatusInternalServerError, fmt.Errorf("cannot use 'copy_response_headers' outside of reverse_proxy's handle_response routes")) } for field, values := range hrc.response.Header { // Check the include list first, skip // the header if it's _not_ in this list. if len(h.includeMap) > 0 { if _, ok := h.includeMap[field]; !ok { continue } } // Then, check the exclude list, skip // the header if it _is_ in this list. if len(h.excludeMap) > 0 { if _, ok := h.excludeMap[field]; ok { continue } } // Copy all the values for the header. for _, value := range values { rw.Header().Add(field, value) } } return next.ServeHTTP(rw, req) } // Interface guards var ( _ caddyhttp.MiddlewareHandler = (*CopyResponseHandler)(nil) _ caddyfile.Unmarshaler = (*CopyResponseHandler)(nil) _ caddy.Provisioner = (*CopyResponseHandler)(nil) _ caddyhttp.MiddlewareHandler = (*CopyResponseHeadersHandler)(nil) _ caddyfile.Unmarshaler = (*CopyResponseHeadersHandler)(nil) _ caddy.Provisioner = (*CopyResponseHeadersHandler)(nil) _ caddy.Validator = (*CopyResponseHeadersHandler)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/reverseproxy/streaming.go
modules/caddyhttp/reverseproxy/streaming.go
// Copyright 2015 Matthew Holt and The Caddy 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. // Most of the code in this file was initially borrowed from the Go // standard library and modified; It had this copyright notice: // Copyright 2011 The Go Authors package reverseproxy import ( "bufio" "context" "errors" "fmt" "io" weakrand "math/rand" "mime" "net/http" "sync" "time" "unsafe" "go.uber.org/zap" "go.uber.org/zap/zapcore" "golang.org/x/net/http/httpguts" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) type h2ReadWriteCloser struct { io.ReadCloser http.ResponseWriter } func (rwc h2ReadWriteCloser) Write(p []byte) (n int, err error) { n, err = rwc.ResponseWriter.Write(p) if err != nil { return 0, err } //nolint:bodyclose err = http.NewResponseController(rwc.ResponseWriter).Flush() if err != nil { return 0, err } return n, nil } func (h *Handler) handleUpgradeResponse(logger *zap.Logger, wg *sync.WaitGroup, rw http.ResponseWriter, req *http.Request, res *http.Response) { reqUpType := upgradeType(req.Header) resUpType := upgradeType(res.Header) // Taken from https://github.com/golang/go/commit/5c489514bc5e61ad9b5b07bd7d8ec65d66a0512a // We know reqUpType is ASCII, it's checked by the caller. if !asciiIsPrint(resUpType) { if c := logger.Check(zapcore.DebugLevel, "backend tried to switch to invalid protocol"); c != nil { c.Write(zap.String("backend_upgrade", resUpType)) } return } if !asciiEqualFold(reqUpType, resUpType) { if c := logger.Check(zapcore.DebugLevel, "backend tried to switch to unexpected protocol via Upgrade header"); c != nil { c.Write( zap.String("backend_upgrade", resUpType), zap.String("requested_upgrade", reqUpType), ) } return } backConn, ok := res.Body.(io.ReadWriteCloser) if !ok { logger.Error("internal error: 101 switching protocols response with non-writable body") return } // write header first, response headers should not be counted in size // like the rest of handler chain. copyHeader(rw.Header(), res.Header) normalizeWebsocketHeaders(rw.Header()) var ( conn io.ReadWriteCloser brw *bufio.ReadWriter ) // websocket over http2 or http3 if extended connect is enabled, assuming backend doesn't support this, the request will be modified to http1.1 upgrade // TODO: once we can reliably detect backend support this, it can be removed for those backends if body, ok := caddyhttp.GetVar(req.Context(), "extended_connect_websocket_body").(io.ReadCloser); ok { req.Body = body rw.Header().Del("Upgrade") rw.Header().Del("Connection") delete(rw.Header(), "Sec-WebSocket-Accept") rw.WriteHeader(http.StatusOK) if c := logger.Check(zap.DebugLevel, "upgrading connection"); c != nil { c.Write(zap.Int("http_version", 2)) } //nolint:bodyclose flushErr := http.NewResponseController(rw).Flush() if flushErr != nil { if c := h.logger.Check(zap.ErrorLevel, "failed to flush http2 websocket response"); c != nil { c.Write(zap.Error(flushErr)) } return } conn = h2ReadWriteCloser{req.Body, rw} // bufio is not needed, use minimal buffer brw = bufio.NewReadWriter(bufio.NewReaderSize(conn, 1), bufio.NewWriterSize(conn, 1)) } else { rw.WriteHeader(res.StatusCode) if c := logger.Check(zap.DebugLevel, "upgrading connection"); c != nil { c.Write(zap.Int("http_version", req.ProtoMajor)) } var hijackErr error //nolint:bodyclose conn, brw, hijackErr = http.NewResponseController(rw).Hijack() if errors.Is(hijackErr, http.ErrNotSupported) { if c := h.logger.Check(zap.ErrorLevel, "can't switch protocols using non-Hijacker ResponseWriter"); c != nil { c.Write(zap.String("type", fmt.Sprintf("%T", rw))) } return } if hijackErr != nil { if c := h.logger.Check(zap.ErrorLevel, "hijack failed on protocol switch"); c != nil { c.Write(zap.Error(hijackErr)) } return } } // adopted from https://github.com/golang/go/commit/8bcf2834afdf6a1f7937390903a41518715ef6f5 backConnCloseCh := make(chan struct{}) go func() { // Ensure that the cancellation of a request closes the backend. // See issue https://golang.org/issue/35559. select { case <-req.Context().Done(): case <-backConnCloseCh: } backConn.Close() }() defer close(backConnCloseCh) start := time.Now() defer func() { conn.Close() if c := logger.Check(zapcore.DebugLevel, "connection closed"); c != nil { c.Write(zap.Duration("duration", time.Since(start))) } }() if err := brw.Flush(); err != nil { if c := logger.Check(zapcore.DebugLevel, "response flush"); c != nil { c.Write(zap.Error(err)) } return } // There may be buffered data in the *bufio.Reader // see: https://github.com/caddyserver/caddy/issues/6273 if buffered := brw.Reader.Buffered(); buffered > 0 { data, _ := brw.Peek(buffered) _, err := backConn.Write(data) if err != nil { if c := logger.Check(zapcore.DebugLevel, "backConn write failed"); c != nil { c.Write(zap.Error(err)) } return } } // Ensure the hijacked client connection, and the new connection established // with the backend, are both closed in the event of a server shutdown. This // is done by registering them. We also try to gracefully close connections // we recognize as websockets. // We need to make sure the client connection messages (i.e. to upstream) // are masked, so we need to know whether the connection is considered the // server or the client side of the proxy. gracefulClose := func(conn io.ReadWriteCloser, isClient bool) func() error { if isWebsocket(req) { return func() error { return writeCloseControl(conn, isClient) } } return nil } deleteFrontConn := h.registerConnection(conn, gracefulClose(conn, false)) deleteBackConn := h.registerConnection(backConn, gracefulClose(backConn, true)) defer deleteFrontConn() defer deleteBackConn() spc := switchProtocolCopier{user: conn, backend: backConn, wg: wg} // setup the timeout if requested var timeoutc <-chan time.Time if h.StreamTimeout > 0 { timer := time.NewTimer(time.Duration(h.StreamTimeout)) defer timer.Stop() timeoutc = timer.C } // when a stream timeout is encountered, no error will be read from errc // a buffer size of 2 will allow both the read and write goroutines to send the error and exit // see: https://github.com/caddyserver/caddy/issues/7418 errc := make(chan error, 2) wg.Add(2) go spc.copyToBackend(errc) go spc.copyFromBackend(errc) select { case err := <-errc: if c := logger.Check(zapcore.DebugLevel, "streaming error"); c != nil { c.Write(zap.Error(err)) } case time := <-timeoutc: if c := logger.Check(zapcore.DebugLevel, "stream timed out"); c != nil { c.Write(zap.Time("timeout", time)) } } } // flushInterval returns the p.FlushInterval value, conditionally // overriding its value for a specific request/response. func (h Handler) flushInterval(req *http.Request, res *http.Response) time.Duration { resCTHeader := res.Header.Get("Content-Type") resCT, _, err := mime.ParseMediaType(resCTHeader) // For Server-Sent Events responses, flush immediately. // The MIME type is defined in https://www.w3.org/TR/eventsource/#text-event-stream if err == nil && resCT == "text/event-stream" { return -1 // negative means immediately } // We might have the case of streaming for which Content-Length might be unset. if res.ContentLength == -1 { return -1 } // for h2 and h2c upstream streaming data to client (issues #3556 and #3606) if h.isBidirectionalStream(req, res) { return -1 } return time.Duration(h.FlushInterval) } // isBidirectionalStream returns whether we should work in bi-directional stream mode. // // See https://github.com/caddyserver/caddy/pull/3620 for discussion of nuances. func (h Handler) isBidirectionalStream(req *http.Request, res *http.Response) bool { // We have to check the encoding here; only flush headers with identity encoding. // Non-identity encoding might combine with "encode" directive, and in that case, // if body size larger than enc.MinLength, upper level encode handle might have // Content-Encoding header to write. // (see https://github.com/caddyserver/caddy/issues/3606 for use case) ae := req.Header.Get("Accept-Encoding") return req.ProtoMajor == 2 && res.ProtoMajor == 2 && res.ContentLength == -1 && (ae == "identity" || ae == "") } func (h Handler) copyResponse(dst http.ResponseWriter, src io.Reader, flushInterval time.Duration, logger *zap.Logger) error { var w io.Writer = dst if flushInterval != 0 { var mlwLogger *zap.Logger if h.VerboseLogs { mlwLogger = logger.Named("max_latency_writer") } else { mlwLogger = zap.NewNop() } mlw := &maxLatencyWriter{ dst: dst, //nolint:bodyclose flush: http.NewResponseController(dst).Flush, latency: flushInterval, logger: mlwLogger, } defer mlw.stop() // set up initial timer so headers get flushed even if body writes are delayed mlw.flushPending = true mlw.t = time.AfterFunc(flushInterval, mlw.delayedFlush) w = mlw } buf := streamingBufPool.Get().(*[]byte) defer streamingBufPool.Put(buf) var copyLogger *zap.Logger if h.VerboseLogs { copyLogger = logger } else { copyLogger = zap.NewNop() } _, err := h.copyBuffer(w, src, *buf, copyLogger) return err } // copyBuffer returns any write errors or non-EOF read errors, and the amount // of bytes written. func (h Handler) copyBuffer(dst io.Writer, src io.Reader, buf []byte, logger *zap.Logger) (int64, error) { if len(buf) == 0 { buf = make([]byte, defaultBufferSize) } var written int64 for { logger.Debug("waiting to read from upstream") nr, rerr := src.Read(buf) logger := logger.With(zap.Int("read", nr)) if c := logger.Check(zapcore.DebugLevel, "read from upstream"); c != nil { c.Write(zap.Error(rerr)) } if rerr != nil && rerr != io.EOF && rerr != context.Canceled { // TODO: this could be useful to know (indeed, it revealed an error in our // fastcgi PoC earlier; but it's this single error report here that necessitates // a function separate from io.CopyBuffer, since io.CopyBuffer does not distinguish // between read or write errors; in a reverse proxy situation, write errors are not // something we need to report to the client, but read errors are a problem on our // end for sure. so we need to decide what we want.) // p.logf("copyBuffer: ReverseProxy read error during body copy: %v", rerr) if c := logger.Check(zapcore.ErrorLevel, "reading from backend"); c != nil { c.Write(zap.Error(rerr)) } } if nr > 0 { logger.Debug("writing to downstream") nw, werr := dst.Write(buf[:nr]) if nw > 0 { written += int64(nw) } if c := logger.Check(zapcore.DebugLevel, "wrote to downstream"); c != nil { c.Write( zap.Int("written", nw), zap.Int64("written_total", written), zap.Error(werr), ) } if werr != nil { return written, fmt.Errorf("writing: %w", werr) } if nr != nw { return written, io.ErrShortWrite } } if rerr != nil { if rerr == io.EOF { return written, nil } return written, fmt.Errorf("reading: %w", rerr) } } } // registerConnection holds onto conn so it can be closed in the event // of a server shutdown. This is useful because hijacked connections or // connections dialed to backends don't close when server is shut down. // The caller should call the returned delete() function when the // connection is done to remove it from memory. func (h *Handler) registerConnection(conn io.ReadWriteCloser, gracefulClose func() error) (del func()) { h.connectionsMu.Lock() h.connections[conn] = openConnection{conn, gracefulClose} h.connectionsMu.Unlock() return func() { h.connectionsMu.Lock() delete(h.connections, conn) // if there is no connection left before the connections close timer fires if len(h.connections) == 0 && h.connectionsCloseTimer != nil { // we release the timer that holds the reference to Handler if (*h.connectionsCloseTimer).Stop() { h.logger.Debug("stopped streaming connections close timer - all connections are already closed") } h.connectionsCloseTimer = nil } h.connectionsMu.Unlock() } } // closeConnections immediately closes all hijacked connections (both to client and backend). func (h *Handler) closeConnections() error { var err error h.connectionsMu.Lock() defer h.connectionsMu.Unlock() for _, oc := range h.connections { if oc.gracefulClose != nil { // this is potentially blocking while we have the lock on the connections // map, but that should be OK since the server has in theory shut down // and we are no longer using the connections map gracefulErr := oc.gracefulClose() if gracefulErr != nil && err == nil { err = gracefulErr } } closeErr := oc.conn.Close() if closeErr != nil && err == nil { err = closeErr } } return err } // cleanupConnections closes hijacked connections. // Depending on the value of StreamCloseDelay it does that either immediately // or sets up a timer that will do that later. func (h *Handler) cleanupConnections() error { if h.StreamCloseDelay == 0 { return h.closeConnections() } h.connectionsMu.Lock() defer h.connectionsMu.Unlock() // the handler is shut down, no new connection can appear, // so we can skip setting up the timer when there are no connections if len(h.connections) > 0 { delay := time.Duration(h.StreamCloseDelay) h.connectionsCloseTimer = time.AfterFunc(delay, func() { if c := h.logger.Check(zapcore.DebugLevel, "closing streaming connections after delay"); c != nil { c.Write(zap.Duration("delay", delay)) } err := h.closeConnections() if err != nil { if c := h.logger.Check(zapcore.ErrorLevel, "failed to closed connections after delay"); c != nil { c.Write( zap.Error(err), zap.Duration("delay", delay), ) } } }) } return nil } // writeCloseControl sends a best-effort Close control message to the given // WebSocket connection. Thanks to @pascaldekloe who provided inspiration // from his simple implementation of this I was able to learn from at: // github.com/pascaldekloe/websocket. Further work for handling masking // taken from github.com/gorilla/websocket. func writeCloseControl(conn io.Writer, isClient bool) error { // Sources: // https://github.com/pascaldekloe/websocket/blob/32050af67a5d/websocket.go#L119 // https://github.com/gorilla/websocket/blob/v1.5.0/conn.go#L413 // For now, we're not using a reason. We might later, though. // The code handling the reason is left in var reason string // max 123 bytes (control frame payload limit is 125; status code takes 2) const closeMessage = 8 const finalBit = 1 << 7 // Frame header byte 0 bits from Section 5.2 of RFC 6455 const maskBit = 1 << 7 // Frame header byte 1 bits from Section 5.2 of RFC 6455 const goingAwayUpper uint8 = 1001 >> 8 const goingAwayLower uint8 = 1001 & 0xff b0 := byte(closeMessage) | finalBit b1 := byte(len(reason) + 2) if isClient { b1 |= maskBit } buf := make([]byte, 0, 127) buf = append(buf, b0, b1) msgLength := 4 + len(reason) // Both branches below append the "going away" code and reason appendMessage := func(buf []byte) []byte { buf = append(buf, goingAwayUpper, goingAwayLower) buf = append(buf, []byte(reason)...) return buf } // When we're the client, we need to mask the message as per // https://www.rfc-editor.org/rfc/rfc6455#section-5.3 if isClient { key := newMaskKey() buf = append(buf, key[:]...) msgLength += len(key) buf = appendMessage(buf) maskBytes(key, 0, buf[2+len(key):]) } else { buf = appendMessage(buf) } // simply best-effort, but return error for logging purposes // TODO: we might need to ensure we are the exclusive writer by this point (io.Copy is stopped)? _, err := conn.Write(buf[:msgLength]) return err } // Copied from https://github.com/gorilla/websocket/blob/v1.5.0/mask.go func maskBytes(key [4]byte, pos int, b []byte) int { // Mask one byte at a time for small buffers. if len(b) < 2*wordSize { for i := range b { b[i] ^= key[pos&3] pos++ } return pos & 3 } // Mask one byte at a time to word boundary. if n := int(uintptr(unsafe.Pointer(&b[0]))) % wordSize; n != 0 { n = wordSize - n for i := range b[:n] { b[i] ^= key[pos&3] pos++ } b = b[n:] } // Create aligned word size key. var k [wordSize]byte for i := range k { k[i] = key[(pos+i)&3] } kw := *(*uintptr)(unsafe.Pointer(&k)) // Mask one word at a time. n := (len(b) / wordSize) * wordSize for i := 0; i < n; i += wordSize { *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&b[0])) + uintptr(i))) ^= kw } // Mask one byte at a time for remaining bytes. b = b[n:] for i := range b { b[i] ^= key[pos&3] pos++ } return pos & 3 } // Copied from https://github.com/gorilla/websocket/blob/v1.5.0/conn.go#L184 func newMaskKey() [4]byte { n := weakrand.Uint32() return [4]byte{byte(n), byte(n >> 8), byte(n >> 16), byte(n >> 24)} } // isWebsocket returns true if r looks to be an upgrade request for WebSockets. // It is a fairly naive check. func isWebsocket(r *http.Request) bool { return httpguts.HeaderValuesContainsToken(r.Header["Connection"], "upgrade") && httpguts.HeaderValuesContainsToken(r.Header["Upgrade"], "websocket") } // openConnection maps an open connection to // an optional function for graceful close. type openConnection struct { conn io.ReadWriteCloser gracefulClose func() error } type maxLatencyWriter struct { dst io.Writer flush func() error latency time.Duration // non-zero; negative means to flush immediately mu sync.Mutex // protects t, flushPending, and dst.Flush t *time.Timer flushPending bool logger *zap.Logger } func (m *maxLatencyWriter) Write(p []byte) (n int, err error) { m.mu.Lock() defer m.mu.Unlock() n, err = m.dst.Write(p) if c := m.logger.Check(zapcore.DebugLevel, "wrote bytes"); c != nil { c.Write(zap.Int("n", n), zap.Error(err)) } if m.latency < 0 { m.logger.Debug("flushing immediately") //nolint:errcheck m.flush() return n, err } if m.flushPending { m.logger.Debug("delayed flush already pending") return n, err } if m.t == nil { m.t = time.AfterFunc(m.latency, m.delayedFlush) } else { m.t.Reset(m.latency) } if c := m.logger.Check(zapcore.DebugLevel, "timer set for delayed flush"); c != nil { c.Write(zap.Duration("duration", m.latency)) } m.flushPending = true return n, err } func (m *maxLatencyWriter) delayedFlush() { m.mu.Lock() defer m.mu.Unlock() if !m.flushPending { // if stop was called but AfterFunc already started this goroutine m.logger.Debug("delayed flush is not pending") return } m.logger.Debug("delayed flush") //nolint:errcheck m.flush() m.flushPending = false } func (m *maxLatencyWriter) stop() { m.mu.Lock() defer m.mu.Unlock() m.flushPending = false if m.t != nil { m.t.Stop() } } // switchProtocolCopier exists so goroutines proxying data back and // forth have nice names in stacks. type switchProtocolCopier struct { user, backend io.ReadWriteCloser wg *sync.WaitGroup } func (c switchProtocolCopier) copyFromBackend(errc chan<- error) { _, err := io.Copy(c.user, c.backend) errc <- err c.wg.Done() } func (c switchProtocolCopier) copyToBackend(errc chan<- error) { _, err := io.Copy(c.backend, c.user) errc <- err c.wg.Done() } var streamingBufPool = sync.Pool{ New: func() any { // The Pool's New function should generally only return pointer // types, since a pointer can be put into the return interface // value without an allocation // - (from the package docs) b := make([]byte, defaultBufferSize) return &b }, } const ( defaultBufferSize = 32 * 1024 wordSize = int(unsafe.Sizeof(uintptr(0))) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/reverseproxy/command.go
modules/caddyhttp/reverseproxy/command.go
// Copyright 2015 Matthew Holt and The Caddy 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 reverseproxy import ( "encoding/json" "fmt" "net/http" "strconv" "strings" "github.com/spf13/cobra" "go.uber.org/zap" caddycmd "github.com/caddyserver/caddy/v2/cmd" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" "github.com/caddyserver/caddy/v2/modules/caddyhttp/headers" "github.com/caddyserver/caddy/v2/modules/caddytls" ) func init() { caddycmd.RegisterCommand(caddycmd.Command{ Name: "reverse-proxy", Usage: `[--from <addr>] [--to <addr>] [--change-host-header] [--insecure] [--internal-certs] [--disable-redirects] [--header-up "Field: value"] [--header-down "Field: value"] [--access-log] [--debug]`, Short: "A quick and production-ready reverse proxy", Long: ` A simple but production-ready reverse proxy. Useful for quick deployments, demos, and development. Simply shuttles HTTP(S) traffic from the --from address to the --to address. Multiple --to addresses may be specified by repeating the flag. Unless otherwise specified in the addresses, the --from address will be assumed to be HTTPS if a hostname is given, and the --to address will be assumed to be HTTP. If the --from address has a host or IP, Caddy will attempt to serve the proxy over HTTPS with a certificate (unless overridden by the HTTP scheme or port). If serving HTTPS: --disable-redirects can be used to avoid binding to the HTTP port. --internal-certs can be used to force issuance certs using the internal CA instead of attempting to issue a public certificate. For proxying: --header-up can be used to set a request header to send to the upstream. --header-down can be used to set a response header to send back to the client. --change-host-header sets the Host header on the request to the address of the upstream, instead of defaulting to the incoming Host header. This is a shortcut for --header-up "Host: {http.reverse_proxy.upstream.hostport}". --insecure disables TLS verification with the upstream. WARNING: THIS DISABLES SECURITY BY NOT VERIFYING THE UPSTREAM'S CERTIFICATE. `, CobraFunc: func(cmd *cobra.Command) { cmd.Flags().StringP("from", "f", "localhost", "Address on which to receive traffic") cmd.Flags().StringSliceP("to", "t", []string{}, "Upstream address(es) to which traffic should be sent") cmd.Flags().BoolP("change-host-header", "c", false, "Set upstream Host header to address of upstream") cmd.Flags().BoolP("insecure", "", false, "Disable TLS verification (WARNING: DISABLES SECURITY BY NOT VERIFYING TLS CERTIFICATES!)") cmd.Flags().BoolP("disable-redirects", "r", false, "Disable HTTP->HTTPS redirects") cmd.Flags().BoolP("internal-certs", "i", false, "Use internal CA for issuing certs") cmd.Flags().StringArrayP("header-up", "H", []string{}, "Set a request header to send to the upstream (format: \"Field: value\")") cmd.Flags().StringArrayP("header-down", "d", []string{}, "Set a response header to send back to the client (format: \"Field: value\")") cmd.Flags().BoolP("access-log", "", false, "Enable the access log") cmd.Flags().BoolP("debug", "v", false, "Enable verbose debug logs") cmd.RunE = caddycmd.WrapCommandFuncForCobra(cmdReverseProxy) }, }) } func cmdReverseProxy(fs caddycmd.Flags) (int, error) { caddy.TrapSignals() from := fs.String("from") changeHost := fs.Bool("change-host-header") insecure := fs.Bool("insecure") disableRedir := fs.Bool("disable-redirects") internalCerts := fs.Bool("internal-certs") accessLog := fs.Bool("access-log") debug := fs.Bool("debug") httpPort := strconv.Itoa(caddyhttp.DefaultHTTPPort) httpsPort := strconv.Itoa(caddyhttp.DefaultHTTPSPort) to, err := fs.GetStringSlice("to") if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("invalid to flag: %v", err) } if len(to) == 0 { return caddy.ExitCodeFailedStartup, fmt.Errorf("--to is required") } // set up the downstream address; assume missing information from given parts fromAddr, err := httpcaddyfile.ParseAddress(from) if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("invalid downstream address %s: %v", from, err) } if fromAddr.Path != "" { return caddy.ExitCodeFailedStartup, fmt.Errorf("paths are not allowed: %s", from) } if fromAddr.Scheme == "" { if fromAddr.Port == httpPort || fromAddr.Host == "" { fromAddr.Scheme = "http" } else { fromAddr.Scheme = "https" } } if fromAddr.Port == "" { switch fromAddr.Scheme { case "http": fromAddr.Port = httpPort case "https": fromAddr.Port = httpsPort } } // set up the upstream address; assume missing information from given parts // mixing schemes isn't supported, so use first defined (if available) toAddresses := make([]string, len(to)) var toScheme string for i, toLoc := range to { addr, err := parseUpstreamDialAddress(toLoc) if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("invalid upstream address %s: %v", toLoc, err) } if addr.scheme != "" && toScheme == "" { toScheme = addr.scheme } toAddresses[i] = addr.dialAddr() } // proceed to build the handler and server ht := HTTPTransport{} if toScheme == "https" { ht.TLS = new(TLSConfig) if insecure { ht.TLS.InsecureSkipVerify = true } } upstreamPool := UpstreamPool{} for _, toAddr := range toAddresses { parsedAddr, err := caddy.ParseNetworkAddress(toAddr) if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("invalid upstream address %s: %v", toAddr, err) } if parsedAddr.StartPort == 0 && parsedAddr.EndPort == 0 { // unix networks don't have ports upstreamPool = append(upstreamPool, &Upstream{ Dial: toAddr, }) } else { // expand a port range into multiple upstreams for i := parsedAddr.StartPort; i <= parsedAddr.EndPort; i++ { upstreamPool = append(upstreamPool, &Upstream{ Dial: caddy.JoinNetworkAddress("", parsedAddr.Host, fmt.Sprint(i)), }) } } } handler := Handler{ TransportRaw: caddyconfig.JSONModuleObject(ht, "protocol", "http", nil), Upstreams: upstreamPool, } // set up header_up headerUp, err := fs.GetStringArray("header-up") if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("invalid header flag: %v", err) } if len(headerUp) > 0 { reqHdr := make(http.Header) for i, h := range headerUp { key, val, found := strings.Cut(h, ":") key, val = strings.TrimSpace(key), strings.TrimSpace(val) if !found || key == "" || val == "" { return caddy.ExitCodeFailedStartup, fmt.Errorf("header-up %d: invalid format \"%s\" (expecting \"Field: value\")", i, h) } reqHdr.Set(key, val) } handler.Headers = &headers.Handler{ Request: &headers.HeaderOps{ Set: reqHdr, }, } } // set up header_down headerDown, err := fs.GetStringArray("header-down") if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("invalid header flag: %v", err) } if len(headerDown) > 0 { respHdr := make(http.Header) for i, h := range headerDown { key, val, found := strings.Cut(h, ":") key, val = strings.TrimSpace(key), strings.TrimSpace(val) if !found || key == "" || val == "" { return caddy.ExitCodeFailedStartup, fmt.Errorf("header-down %d: invalid format \"%s\" (expecting \"Field: value\")", i, h) } respHdr.Set(key, val) } if handler.Headers == nil { handler.Headers = &headers.Handler{} } handler.Headers.Response = &headers.RespHeaderOps{ HeaderOps: &headers.HeaderOps{ Set: respHdr, }, } } if changeHost { if handler.Headers == nil { handler.Headers = new(headers.Handler) } if handler.Headers.Request == nil { handler.Headers.Request = new(headers.HeaderOps) } if handler.Headers.Request.Set == nil { handler.Headers.Request.Set = http.Header{} } handler.Headers.Request.Set.Set("Host", "{http.reverse_proxy.upstream.hostport}") } route := caddyhttp.Route{ HandlersRaw: []json.RawMessage{ caddyconfig.JSONModuleObject(handler, "handler", "reverse_proxy", nil), }, } if fromAddr.Host != "" { route.MatcherSetsRaw = []caddy.ModuleMap{ { "host": caddyconfig.JSON(caddyhttp.MatchHost{fromAddr.Host}, nil), }, } } server := &caddyhttp.Server{ Routes: caddyhttp.RouteList{route}, Listen: []string{":" + fromAddr.Port}, } if accessLog { server.Logs = &caddyhttp.ServerLogConfig{} } if fromAddr.Scheme == "http" { server.AutoHTTPS = &caddyhttp.AutoHTTPSConfig{Disabled: true} } else if disableRedir { server.AutoHTTPS = &caddyhttp.AutoHTTPSConfig{DisableRedir: true} } httpApp := caddyhttp.App{ Servers: map[string]*caddyhttp.Server{"proxy": server}, } appsRaw := caddy.ModuleMap{ "http": caddyconfig.JSON(httpApp, nil), } if internalCerts && fromAddr.Host != "" { tlsApp := caddytls.TLS{ Automation: &caddytls.AutomationConfig{ Policies: []*caddytls.AutomationPolicy{{ SubjectsRaw: []string{fromAddr.Host}, IssuersRaw: []json.RawMessage{json.RawMessage(`{"module":"internal"}`)}, }}, }, } appsRaw["tls"] = caddyconfig.JSON(tlsApp, nil) } var false bool cfg := &caddy.Config{ Admin: &caddy.AdminConfig{ Disabled: true, Config: &caddy.ConfigSettings{ Persist: &false, }, }, AppsRaw: appsRaw, } if debug { cfg.Logging = &caddy.Logging{ Logs: map[string]*caddy.CustomLog{ "default": {BaseLog: caddy.BaseLog{Level: zap.DebugLevel.CapitalString()}}, }, } } err = caddy.Run(cfg) if err != nil { return caddy.ExitCodeFailedStartup, err } caddy.Log().Info("caddy proxying", zap.String("from", fromAddr.String()), zap.Strings("to", toAddresses)) if len(toAddresses) > 1 { caddy.Log().Info("using default load balancing policy", zap.String("policy", "random")) } select {} }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/reverseproxy/streaming_test.go
modules/caddyhttp/reverseproxy/streaming_test.go
package reverseproxy import ( "bytes" "net/http/httptest" "strings" "testing" "github.com/caddyserver/caddy/v2" ) func TestHandlerCopyResponse(t *testing.T) { h := Handler{} testdata := []string{ "", strings.Repeat("a", defaultBufferSize), strings.Repeat("123456789 123456789 123456789 12", 3000), } dst := bytes.NewBuffer(nil) recorder := httptest.NewRecorder() recorder.Body = dst for _, d := range testdata { src := bytes.NewBuffer([]byte(d)) dst.Reset() err := h.copyResponse(recorder, src, 0, caddy.Log()) if err != nil { t.Errorf("failed with error: %v", err) } out := dst.String() if out != d { t.Errorf("bad read: got %q", out) } } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/reverseproxy/selectionpolicies_test.go
modules/caddyhttp/reverseproxy/selectionpolicies_test.go
// Copyright 2015 Matthew Holt and The Caddy 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 reverseproxy import ( "context" "net/http" "net/http/httptest" "testing" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func testPool() UpstreamPool { return UpstreamPool{ {Host: new(Host), Dial: "0.0.0.1"}, {Host: new(Host), Dial: "0.0.0.2"}, {Host: new(Host), Dial: "0.0.0.3"}, } } func TestRoundRobinPolicy(t *testing.T) { pool := testPool() rrPolicy := RoundRobinSelection{} req, _ := http.NewRequest("GET", "/", nil) h := rrPolicy.Select(pool, req, nil) // First selected host is 1, because counter starts at 0 // and increments before host is selected if h != pool[1] { t.Error("Expected first round robin host to be second host in the pool.") } h = rrPolicy.Select(pool, req, nil) if h != pool[2] { t.Error("Expected second round robin host to be third host in the pool.") } h = rrPolicy.Select(pool, req, nil) if h != pool[0] { t.Error("Expected third round robin host to be first host in the pool.") } // mark host as down pool[1].setHealthy(false) h = rrPolicy.Select(pool, req, nil) if h != pool[2] { t.Error("Expected to skip down host.") } // mark host as up pool[1].setHealthy(true) h = rrPolicy.Select(pool, req, nil) if h == pool[2] { t.Error("Expected to balance evenly among healthy hosts") } // mark host as full pool[1].countRequest(1) pool[1].MaxRequests = 1 h = rrPolicy.Select(pool, req, nil) if h != pool[2] { t.Error("Expected to skip full host.") } } func TestWeightedRoundRobinPolicy(t *testing.T) { pool := testPool() wrrPolicy := WeightedRoundRobinSelection{ Weights: []int{3, 2, 1}, totalWeight: 6, } req, _ := http.NewRequest("GET", "/", nil) h := wrrPolicy.Select(pool, req, nil) if h != pool[0] { t.Error("Expected first weighted round robin host to be first host in the pool.") } h = wrrPolicy.Select(pool, req, nil) if h != pool[0] { t.Error("Expected second weighted round robin host to be first host in the pool.") } // Third selected host is 1, because counter starts at 0 // and increments before host is selected h = wrrPolicy.Select(pool, req, nil) if h != pool[1] { t.Error("Expected third weighted round robin host to be second host in the pool.") } h = wrrPolicy.Select(pool, req, nil) if h != pool[1] { t.Error("Expected fourth weighted round robin host to be second host in the pool.") } h = wrrPolicy.Select(pool, req, nil) if h != pool[2] { t.Error("Expected fifth weighted round robin host to be third host in the pool.") } h = wrrPolicy.Select(pool, req, nil) if h != pool[0] { t.Error("Expected sixth weighted round robin host to be first host in the pool.") } // mark host as down pool[0].setHealthy(false) h = wrrPolicy.Select(pool, req, nil) if h != pool[1] { t.Error("Expected to skip down host.") } // mark host as up pool[0].setHealthy(true) h = wrrPolicy.Select(pool, req, nil) if h != pool[0] { t.Error("Expected to select first host on availability.") } // mark host as full pool[1].countRequest(1) pool[1].MaxRequests = 1 h = wrrPolicy.Select(pool, req, nil) if h != pool[2] { t.Error("Expected to skip full host.") } } func TestWeightedRoundRobinPolicyWithZeroWeight(t *testing.T) { pool := testPool() wrrPolicy := WeightedRoundRobinSelection{ Weights: []int{0, 2, 1}, totalWeight: 3, } req, _ := http.NewRequest("GET", "/", nil) h := wrrPolicy.Select(pool, req, nil) if h != pool[1] { t.Error("Expected first weighted round robin host to be second host in the pool.") } h = wrrPolicy.Select(pool, req, nil) if h != pool[2] { t.Error("Expected second weighted round robin host to be third host in the pool.") } h = wrrPolicy.Select(pool, req, nil) if h != pool[1] { t.Error("Expected third weighted round robin host to be second host in the pool.") } // mark second host as down pool[1].setHealthy(false) h = wrrPolicy.Select(pool, req, nil) if h != pool[2] { t.Error("Expect select next available host.") } h = wrrPolicy.Select(pool, req, nil) if h != pool[2] { t.Error("Expect select only available host.") } // mark second host as up pool[1].setHealthy(true) h = wrrPolicy.Select(pool, req, nil) if h != pool[1] { t.Error("Expect select first host on availability.") } // test next select in full cycle expected := []*Upstream{pool[1], pool[2], pool[1], pool[1], pool[2], pool[1]} for i, want := range expected { got := wrrPolicy.Select(pool, req, nil) if want != got { t.Errorf("Selection %d: got host[%s], want host[%s]", i+1, got, want) } } } func TestLeastConnPolicy(t *testing.T) { pool := testPool() lcPolicy := LeastConnSelection{} req, _ := http.NewRequest("GET", "/", nil) pool[0].countRequest(10) pool[1].countRequest(10) h := lcPolicy.Select(pool, req, nil) if h != pool[2] { t.Error("Expected least connection host to be third host.") } pool[2].countRequest(100) h = lcPolicy.Select(pool, req, nil) if h != pool[0] && h != pool[1] { t.Error("Expected least connection host to be first or second host.") } } func TestIPHashPolicy(t *testing.T) { pool := testPool() ipHash := IPHashSelection{} req, _ := http.NewRequest("GET", "/", nil) // We should be able to predict where every request is routed. req.RemoteAddr = "172.0.0.1:80" h := ipHash.Select(pool, req, nil) if h != pool[0] { t.Error("Expected ip hash policy host to be the first host.") } req.RemoteAddr = "172.0.0.2:80" h = ipHash.Select(pool, req, nil) if h != pool[1] { t.Error("Expected ip hash policy host to be the second host.") } req.RemoteAddr = "172.0.0.3:80" h = ipHash.Select(pool, req, nil) if h != pool[0] { t.Error("Expected ip hash policy host to be the first host.") } req.RemoteAddr = "172.0.0.4:80" h = ipHash.Select(pool, req, nil) if h != pool[1] { t.Error("Expected ip hash policy host to be the second host.") } // we should get the same results without a port req.RemoteAddr = "172.0.0.1" h = ipHash.Select(pool, req, nil) if h != pool[0] { t.Error("Expected ip hash policy host to be the first host.") } req.RemoteAddr = "172.0.0.2" h = ipHash.Select(pool, req, nil) if h != pool[1] { t.Error("Expected ip hash policy host to be the second host.") } req.RemoteAddr = "172.0.0.3" h = ipHash.Select(pool, req, nil) if h != pool[0] { t.Error("Expected ip hash policy host to be the first host.") } req.RemoteAddr = "172.0.0.4" h = ipHash.Select(pool, req, nil) if h != pool[1] { t.Error("Expected ip hash policy host to be the second host.") } // we should get a healthy host if the original host is unhealthy and a // healthy host is available req.RemoteAddr = "172.0.0.4" pool[1].setHealthy(false) h = ipHash.Select(pool, req, nil) if h != pool[2] { t.Error("Expected ip hash policy host to be the third host.") } req.RemoteAddr = "172.0.0.2" h = ipHash.Select(pool, req, nil) if h != pool[0] { t.Error("Expected ip hash policy host to be the first host.") } pool[1].setHealthy(true) req.RemoteAddr = "172.0.0.3" pool[2].setHealthy(false) h = ipHash.Select(pool, req, nil) if h != pool[0] { t.Error("Expected ip hash policy host to be the first host.") } req.RemoteAddr = "172.0.0.4" h = ipHash.Select(pool, req, nil) if h != pool[1] { t.Error("Expected ip hash policy host to be the second host.") } // We should be able to resize the host pool and still be able to predict // where a req will be routed with the same IP's used above pool = UpstreamPool{ {Host: new(Host), Dial: "0.0.0.2"}, {Host: new(Host), Dial: "0.0.0.3"}, } req.RemoteAddr = "172.0.0.1:80" h = ipHash.Select(pool, req, nil) if h != pool[0] { t.Error("Expected ip hash policy host to be the first host.") } req.RemoteAddr = "172.0.0.2:80" h = ipHash.Select(pool, req, nil) if h != pool[0] { t.Error("Expected ip hash policy host to be the first host.") } req.RemoteAddr = "172.0.0.3:80" h = ipHash.Select(pool, req, nil) if h != pool[0] { t.Error("Expected ip hash policy host to be the first host.") } req.RemoteAddr = "172.0.0.4:80" h = ipHash.Select(pool, req, nil) if h != pool[0] { t.Error("Expected ip hash policy host to be the first host.") } // We should get nil when there are no healthy hosts pool[0].setHealthy(false) pool[1].setHealthy(false) h = ipHash.Select(pool, req, nil) if h != nil { t.Error("Expected ip hash policy host to be nil.") } // Reproduce #4135 pool = UpstreamPool{ {Host: new(Host)}, {Host: new(Host)}, {Host: new(Host)}, {Host: new(Host)}, {Host: new(Host)}, {Host: new(Host)}, {Host: new(Host)}, {Host: new(Host)}, {Host: new(Host)}, } pool[0].setHealthy(false) pool[1].setHealthy(false) pool[2].setHealthy(false) pool[3].setHealthy(false) pool[4].setHealthy(false) pool[5].setHealthy(false) pool[6].setHealthy(false) pool[7].setHealthy(false) pool[8].setHealthy(true) // We should get a result back when there is one healthy host left. h = ipHash.Select(pool, req, nil) if h == nil { // If it is nil, it means we missed a host even though one is available t.Error("Expected ip hash policy host to not be nil, but it is nil.") } } func TestClientIPHashPolicy(t *testing.T) { pool := testPool() ipHash := ClientIPHashSelection{} req, _ := http.NewRequest("GET", "/", nil) req = req.WithContext(context.WithValue(req.Context(), caddyhttp.VarsCtxKey, make(map[string]any))) // We should be able to predict where every request is routed. caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.1:80") h := ipHash.Select(pool, req, nil) if h != pool[0] { t.Error("Expected ip hash policy host to be the first host.") } caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.2:80") h = ipHash.Select(pool, req, nil) if h != pool[1] { t.Error("Expected ip hash policy host to be the second host.") } caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.3:80") h = ipHash.Select(pool, req, nil) if h != pool[0] { t.Error("Expected ip hash policy host to be the first host.") } caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.4:80") h = ipHash.Select(pool, req, nil) if h != pool[1] { t.Error("Expected ip hash policy host to be the second host.") } // we should get the same results without a port caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.1") h = ipHash.Select(pool, req, nil) if h != pool[0] { t.Error("Expected ip hash policy host to be the first host.") } caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.2") h = ipHash.Select(pool, req, nil) if h != pool[1] { t.Error("Expected ip hash policy host to be the second host.") } caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.3") h = ipHash.Select(pool, req, nil) if h != pool[0] { t.Error("Expected ip hash policy host to be the first host.") } caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.4") h = ipHash.Select(pool, req, nil) if h != pool[1] { t.Error("Expected ip hash policy host to be the second host.") } // we should get a healthy host if the original host is unhealthy and a // healthy host is available caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.4") pool[1].setHealthy(false) h = ipHash.Select(pool, req, nil) if h != pool[2] { t.Error("Expected ip hash policy host to be the third host.") } caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.2") h = ipHash.Select(pool, req, nil) if h != pool[0] { t.Error("Expected ip hash policy host to be the first host.") } pool[1].setHealthy(true) caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.3") pool[2].setHealthy(false) h = ipHash.Select(pool, req, nil) if h != pool[0] { t.Error("Expected ip hash policy host to be the first host.") } caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.4") h = ipHash.Select(pool, req, nil) if h != pool[1] { t.Error("Expected ip hash policy host to be the second host.") } // We should be able to resize the host pool and still be able to predict // where a req will be routed with the same IP's used above pool = UpstreamPool{ {Host: new(Host), Dial: "0.0.0.2"}, {Host: new(Host), Dial: "0.0.0.3"}, } caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.1:80") h = ipHash.Select(pool, req, nil) if h != pool[0] { t.Error("Expected ip hash policy host to be the first host.") } caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.2:80") h = ipHash.Select(pool, req, nil) if h != pool[0] { t.Error("Expected ip hash policy host to be the first host.") } caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.3:80") h = ipHash.Select(pool, req, nil) if h != pool[0] { t.Error("Expected ip hash policy host to be the first host.") } caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.4:80") h = ipHash.Select(pool, req, nil) if h != pool[0] { t.Error("Expected ip hash policy host to be the first host.") } // We should get nil when there are no healthy hosts pool[0].setHealthy(false) pool[1].setHealthy(false) h = ipHash.Select(pool, req, nil) if h != nil { t.Error("Expected ip hash policy host to be nil.") } // Reproduce #4135 pool = UpstreamPool{ {Host: new(Host)}, {Host: new(Host)}, {Host: new(Host)}, {Host: new(Host)}, {Host: new(Host)}, {Host: new(Host)}, {Host: new(Host)}, {Host: new(Host)}, {Host: new(Host)}, } pool[0].setHealthy(false) pool[1].setHealthy(false) pool[2].setHealthy(false) pool[3].setHealthy(false) pool[4].setHealthy(false) pool[5].setHealthy(false) pool[6].setHealthy(false) pool[7].setHealthy(false) pool[8].setHealthy(true) // We should get a result back when there is one healthy host left. h = ipHash.Select(pool, req, nil) if h == nil { // If it is nil, it means we missed a host even though one is available t.Error("Expected ip hash policy host to not be nil, but it is nil.") } } func TestFirstPolicy(t *testing.T) { pool := testPool() firstPolicy := FirstSelection{} req := httptest.NewRequest(http.MethodGet, "/", nil) h := firstPolicy.Select(pool, req, nil) if h != pool[0] { t.Error("Expected first policy host to be the first host.") } pool[0].setHealthy(false) h = firstPolicy.Select(pool, req, nil) if h != pool[1] { t.Error("Expected first policy host to be the second host.") } } func TestQueryHashPolicy(t *testing.T) { ctx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()}) defer cancel() queryPolicy := QueryHashSelection{Key: "foo"} if err := queryPolicy.Provision(ctx); err != nil { t.Errorf("Provision error: %v", err) t.FailNow() } pool := testPool() request := httptest.NewRequest(http.MethodGet, "/?foo=1", nil) h := queryPolicy.Select(pool, request, nil) if h != pool[0] { t.Error("Expected query policy host to be the first host.") } request = httptest.NewRequest(http.MethodGet, "/?foo=100000", nil) h = queryPolicy.Select(pool, request, nil) if h != pool[1] { t.Error("Expected query policy host to be the second host.") } request = httptest.NewRequest(http.MethodGet, "/?foo=1", nil) pool[0].setHealthy(false) h = queryPolicy.Select(pool, request, nil) if h != pool[2] { t.Error("Expected query policy host to be the third host.") } request = httptest.NewRequest(http.MethodGet, "/?foo=100000", nil) h = queryPolicy.Select(pool, request, nil) if h != pool[1] { t.Error("Expected query policy host to be the second host.") } // We should be able to resize the host pool and still be able to predict // where a request will be routed with the same query used above pool = UpstreamPool{ {Host: new(Host)}, {Host: new(Host)}, } request = httptest.NewRequest(http.MethodGet, "/?foo=1", nil) h = queryPolicy.Select(pool, request, nil) if h != pool[0] { t.Error("Expected query policy host to be the first host.") } pool[0].setHealthy(false) h = queryPolicy.Select(pool, request, nil) if h != pool[1] { t.Error("Expected query policy host to be the second host.") } request = httptest.NewRequest(http.MethodGet, "/?foo=4", nil) h = queryPolicy.Select(pool, request, nil) if h != pool[1] { t.Error("Expected query policy host to be the second host.") } pool[0].setHealthy(false) pool[1].setHealthy(false) h = queryPolicy.Select(pool, request, nil) if h != nil { t.Error("Expected query policy policy host to be nil.") } request = httptest.NewRequest(http.MethodGet, "/?foo=aa11&foo=bb22", nil) pool = testPool() h = queryPolicy.Select(pool, request, nil) if h != pool[0] { t.Error("Expected query policy host to be the first host.") } } func TestURIHashPolicy(t *testing.T) { pool := testPool() uriPolicy := URIHashSelection{} request := httptest.NewRequest(http.MethodGet, "/test", nil) h := uriPolicy.Select(pool, request, nil) if h != pool[2] { t.Error("Expected uri policy host to be the third host.") } pool[2].setHealthy(false) h = uriPolicy.Select(pool, request, nil) if h != pool[0] { t.Error("Expected uri policy host to be the first host.") } request = httptest.NewRequest(http.MethodGet, "/test_2", nil) h = uriPolicy.Select(pool, request, nil) if h != pool[0] { t.Error("Expected uri policy host to be the first host.") } // We should be able to resize the host pool and still be able to predict // where a request will be routed with the same URI's used above pool = UpstreamPool{ {Host: new(Host)}, {Host: new(Host)}, } request = httptest.NewRequest(http.MethodGet, "/test", nil) h = uriPolicy.Select(pool, request, nil) if h != pool[0] { t.Error("Expected uri policy host to be the first host.") } pool[0].setHealthy(false) h = uriPolicy.Select(pool, request, nil) if h != pool[1] { t.Error("Expected uri policy host to be the first host.") } request = httptest.NewRequest(http.MethodGet, "/test_2", nil) h = uriPolicy.Select(pool, request, nil) if h != pool[1] { t.Error("Expected uri policy host to be the second host.") } pool[0].setHealthy(false) pool[1].setHealthy(false) h = uriPolicy.Select(pool, request, nil) if h != nil { t.Error("Expected uri policy policy host to be nil.") } } func TestLeastRequests(t *testing.T) { pool := testPool() pool[0].Dial = "localhost:8080" pool[1].Dial = "localhost:8081" pool[2].Dial = "localhost:8082" pool[0].setHealthy(true) pool[1].setHealthy(true) pool[2].setHealthy(true) pool[0].countRequest(10) pool[1].countRequest(20) pool[2].countRequest(30) result := leastRequests(pool) if result == nil { t.Error("Least request should not return nil") } if result != pool[0] { t.Error("Least request should return pool[0]") } } func TestRandomChoicePolicy(t *testing.T) { pool := testPool() pool[0].Dial = "localhost:8080" pool[1].Dial = "localhost:8081" pool[2].Dial = "localhost:8082" pool[0].setHealthy(false) pool[1].setHealthy(true) pool[2].setHealthy(true) pool[0].countRequest(10) pool[1].countRequest(20) pool[2].countRequest(30) request := httptest.NewRequest(http.MethodGet, "/test", nil) randomChoicePolicy := RandomChoiceSelection{Choose: 2} h := randomChoicePolicy.Select(pool, request, nil) if h == nil { t.Error("RandomChoicePolicy should not return nil") } if h == pool[0] { t.Error("RandomChoicePolicy should not choose pool[0]") } } func TestCookieHashPolicy(t *testing.T) { ctx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()}) defer cancel() cookieHashPolicy := CookieHashSelection{} if err := cookieHashPolicy.Provision(ctx); err != nil { t.Errorf("Provision error: %v", err) t.FailNow() } pool := testPool() pool[0].Dial = "localhost:8080" pool[1].Dial = "localhost:8081" pool[2].Dial = "localhost:8082" pool[0].setHealthy(true) pool[1].setHealthy(false) pool[2].setHealthy(false) request := httptest.NewRequest(http.MethodGet, "/test", nil) w := httptest.NewRecorder() h := cookieHashPolicy.Select(pool, request, w) cookieServer1 := w.Result().Cookies()[0] if cookieServer1 == nil { t.Fatal("cookieHashPolicy should set a cookie") } if cookieServer1.Name != "lb" { t.Error("cookieHashPolicy should set a cookie with name lb") } if cookieServer1.Secure { t.Error("cookieHashPolicy should set cookie Secure attribute to false when request is not secure") } if h != pool[0] { t.Error("Expected cookieHashPolicy host to be the first only available host.") } pool[1].setHealthy(true) pool[2].setHealthy(true) request = httptest.NewRequest(http.MethodGet, "/test", nil) w = httptest.NewRecorder() request.AddCookie(cookieServer1) h = cookieHashPolicy.Select(pool, request, w) if h != pool[0] { t.Error("Expected cookieHashPolicy host to stick to the first host (matching cookie).") } s := w.Result().Cookies() if len(s) != 0 { t.Error("Expected cookieHashPolicy to not set a new cookie.") } pool[0].setHealthy(false) request = httptest.NewRequest(http.MethodGet, "/test", nil) w = httptest.NewRecorder() request.AddCookie(cookieServer1) h = cookieHashPolicy.Select(pool, request, w) if h == pool[0] { t.Error("Expected cookieHashPolicy to select a new host.") } if w.Result().Cookies() == nil { t.Error("Expected cookieHashPolicy to set a new cookie.") } } func TestCookieHashPolicyWithSecureRequest(t *testing.T) { ctx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()}) defer cancel() cookieHashPolicy := CookieHashSelection{} if err := cookieHashPolicy.Provision(ctx); err != nil { t.Errorf("Provision error: %v", err) t.FailNow() } pool := testPool() pool[0].Dial = "localhost:8080" pool[1].Dial = "localhost:8081" pool[2].Dial = "localhost:8082" pool[0].setHealthy(true) pool[1].setHealthy(false) pool[2].setHealthy(false) // Create a test server that serves HTTPS requests ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { h := cookieHashPolicy.Select(pool, r, w) if h != pool[0] { t.Error("Expected cookieHashPolicy host to be the first only available host.") } })) defer ts.Close() // Make a new HTTPS request to the test server client := ts.Client() request, err := http.NewRequest(http.MethodGet, ts.URL+"/test", nil) if err != nil { t.Fatal(err) } response, err := client.Do(request) if err != nil { t.Fatal(err) } // Check if the cookie set is Secure and has SameSiteNone mode cookies := response.Cookies() if len(cookies) == 0 { t.Fatal("Expected a cookie to be set") } cookie := cookies[0] if !cookie.Secure { t.Error("Expected cookie Secure attribute to be true when request is secure") } if cookie.SameSite != http.SameSiteNoneMode { t.Error("Expected cookie SameSite attribute to be None when request is secure") } } func TestCookieHashPolicyWithFirstFallback(t *testing.T) { ctx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()}) defer cancel() cookieHashPolicy := CookieHashSelection{ FallbackRaw: caddyconfig.JSONModuleObject(FirstSelection{}, "policy", "first", nil), } if err := cookieHashPolicy.Provision(ctx); err != nil { t.Errorf("Provision error: %v", err) t.FailNow() } pool := testPool() pool[0].Dial = "localhost:8080" pool[1].Dial = "localhost:8081" pool[2].Dial = "localhost:8082" pool[0].setHealthy(true) pool[1].setHealthy(true) pool[2].setHealthy(true) request := httptest.NewRequest(http.MethodGet, "/test", nil) w := httptest.NewRecorder() h := cookieHashPolicy.Select(pool, request, w) cookieServer1 := w.Result().Cookies()[0] if cookieServer1 == nil { t.Fatal("cookieHashPolicy should set a cookie") } if cookieServer1.Name != "lb" { t.Error("cookieHashPolicy should set a cookie with name lb") } if h != pool[0] { t.Errorf("Expected cookieHashPolicy host to be the first only available host, got %s", h) } request = httptest.NewRequest(http.MethodGet, "/test", nil) w = httptest.NewRecorder() request.AddCookie(cookieServer1) h = cookieHashPolicy.Select(pool, request, w) if h != pool[0] { t.Errorf("Expected cookieHashPolicy host to stick to the first host (matching cookie), got %s", h) } s := w.Result().Cookies() if len(s) != 0 { t.Error("Expected cookieHashPolicy to not set a new cookie.") } pool[0].setHealthy(false) request = httptest.NewRequest(http.MethodGet, "/test", nil) w = httptest.NewRecorder() request.AddCookie(cookieServer1) h = cookieHashPolicy.Select(pool, request, w) if h != pool[1] { t.Errorf("Expected cookieHashPolicy to select the next first available host, got %s", h) } if w.Result().Cookies() == nil { t.Error("Expected cookieHashPolicy to set a new cookie.") } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/reverseproxy/fastcgi/client.go
modules/caddyhttp/reverseproxy/fastcgi/client.go
// Copyright 2015 Matthew Holt and The Caddy 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. // Forked Jan. 2015 from http://bitbucket.org/PinIdea/fcgi_client // (which is forked from https://code.google.com/p/go-fastcgi-client/). // This fork contains several fixes and improvements by Matt Holt and // other contributors to the Caddy project. // Copyright 2012 Junqing Tan <ivan@mysqlab.net> and The Go Authors // Use of this source code is governed by a BSD-style // Part of source code is from Go fcgi package package fastcgi import ( "bufio" "bytes" "io" "mime/multipart" "net" "net/http" "net/http/httputil" "net/textproto" "net/url" "os" "path/filepath" "strconv" "strings" "time" "go.uber.org/zap" "go.uber.org/zap/zapcore" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) // FCGIListenSockFileno describes listen socket file number. const FCGIListenSockFileno uint8 = 0 // FCGIHeaderLen describes header length. const FCGIHeaderLen uint8 = 8 // Version1 describes the version. const Version1 uint8 = 1 // FCGINullRequestID describes the null request ID. const FCGINullRequestID uint8 = 0 // FCGIKeepConn describes keep connection mode. const FCGIKeepConn uint8 = 1 const ( // BeginRequest is the begin request flag. BeginRequest uint8 = iota + 1 // AbortRequest is the abort request flag. AbortRequest // EndRequest is the end request flag. EndRequest // Params is the parameters flag. Params // Stdin is the standard input flag. Stdin // Stdout is the standard output flag. Stdout // Stderr is the standard error flag. Stderr // Data is the data flag. Data // GetValues is the get values flag. GetValues // GetValuesResult is the get values result flag. GetValuesResult // UnknownType is the unknown type flag. UnknownType // MaxType is the maximum type flag. MaxType = UnknownType ) const ( // Responder is the responder flag. Responder uint8 = iota + 1 // Authorizer is the authorizer flag. Authorizer // Filter is the filter flag. Filter ) const ( // RequestComplete is the completed request flag. RequestComplete uint8 = iota // CantMultiplexConns is the multiplexed connections flag. CantMultiplexConns // Overloaded is the overloaded flag. Overloaded // UnknownRole is the unknown role flag. UnknownRole ) const ( // MaxConns is the maximum connections flag. MaxConns string = "MAX_CONNS" // MaxRequests is the maximum requests flag. MaxRequests string = "MAX_REQS" // MultiplexConns is the multiplex connections flag. MultiplexConns string = "MPXS_CONNS" ) const ( maxWrite = 65500 // 65530 may work, but for compatibility maxPad = 255 ) // for padding so we don't have to allocate all the time // not synchronized because we don't care what the contents are var pad [maxPad]byte // client implements a FastCGI client, which is a standard for // interfacing external applications with Web servers. type client struct { rwc net.Conn // keepAlive bool // TODO: implement reqID uint16 stderr bool logger *zap.Logger } // Do made the request and returns a io.Reader that translates the data read // from fcgi responder out of fcgi packet before returning it. func (c *client) Do(p map[string]string, req io.Reader) (r io.Reader, err error) { // check for CONTENT_LENGTH, since the lack of it or wrong value will cause the backend to hang if clStr, ok := p["CONTENT_LENGTH"]; !ok { return nil, caddyhttp.Error(http.StatusLengthRequired, nil) } else if _, err := strconv.ParseUint(clStr, 10, 64); err != nil { // stdlib won't return a negative Content-Length, but we check just in case, // the most likely cause is from a missing content length, which is -1 return nil, caddyhttp.Error(http.StatusLengthRequired, err) } writer := &streamWriter{c: c} writer.buf = bufPool.Get().(*bytes.Buffer) writer.buf.Reset() defer bufPool.Put(writer.buf) err = writer.writeBeginRequest(uint16(Responder), 0) if err != nil { return r, err } writer.recType = Params err = writer.writePairs(p) if err != nil { return r, err } writer.recType = Stdin if req != nil { _, err = io.Copy(writer, req) if err != nil { return nil, err } } err = writer.FlushStream() if err != nil { return nil, err } r = &streamReader{c: c} return r, err } // clientCloser is a io.ReadCloser. It wraps a io.Reader with a Closer // that closes the client connection. type clientCloser struct { rwc net.Conn r *streamReader io.Reader status int logger *zap.Logger } func (f clientCloser) Close() error { stderr := f.r.stderr.Bytes() if len(stderr) == 0 { return f.rwc.Close() } logLevel := zapcore.WarnLevel if f.status >= 400 { logLevel = zapcore.ErrorLevel } if c := f.logger.Check(logLevel, "stderr"); c != nil { c.Write(zap.ByteString("body", stderr)) } return f.rwc.Close() } // Request returns a HTTP Response with Header and Body // from fcgi responder func (c *client) Request(p map[string]string, req io.Reader) (resp *http.Response, err error) { r, err := c.Do(p, req) if err != nil { return resp, err } rb := bufio.NewReader(r) tp := textproto.NewReader(rb) resp = new(http.Response) // Parse the response headers. mimeHeader, err := tp.ReadMIMEHeader() if err != nil && err != io.EOF { return resp, err } resp.Header = http.Header(mimeHeader) if resp.Header.Get("Status") != "" { statusNumber, statusInfo, statusIsCut := strings.Cut(resp.Header.Get("Status"), " ") resp.StatusCode, err = strconv.Atoi(statusNumber) if err != nil { return resp, err } if statusIsCut { resp.Status = statusInfo } } else { resp.StatusCode = http.StatusOK } // TODO: fixTransferEncoding ? resp.TransferEncoding = resp.Header["Transfer-Encoding"] resp.ContentLength, _ = strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 64) // wrap the response body in our closer closer := clientCloser{ rwc: c.rwc, r: r.(*streamReader), Reader: rb, status: resp.StatusCode, logger: noopLogger, } if chunked(resp.TransferEncoding) { closer.Reader = httputil.NewChunkedReader(rb) } if c.stderr { closer.logger = c.logger } resp.Body = closer return resp, err } // Get issues a GET request to the fcgi responder. func (c *client) Get(p map[string]string, body io.Reader, l int64) (resp *http.Response, err error) { p["REQUEST_METHOD"] = "GET" p["CONTENT_LENGTH"] = strconv.FormatInt(l, 10) return c.Request(p, body) } // Head issues a HEAD request to the fcgi responder. func (c *client) Head(p map[string]string) (resp *http.Response, err error) { p["REQUEST_METHOD"] = "HEAD" p["CONTENT_LENGTH"] = "0" return c.Request(p, nil) } // Options issues an OPTIONS request to the fcgi responder. func (c *client) Options(p map[string]string) (resp *http.Response, err error) { p["REQUEST_METHOD"] = "OPTIONS" p["CONTENT_LENGTH"] = "0" return c.Request(p, nil) } // Post issues a POST request to the fcgi responder. with request body // in the format that bodyType specified func (c *client) Post(p map[string]string, method string, bodyType string, body io.Reader, l int64) (resp *http.Response, err error) { if p == nil { p = make(map[string]string) } p["REQUEST_METHOD"] = strings.ToUpper(method) if len(p["REQUEST_METHOD"]) == 0 || p["REQUEST_METHOD"] == "GET" { p["REQUEST_METHOD"] = "POST" } p["CONTENT_LENGTH"] = strconv.FormatInt(l, 10) if len(bodyType) > 0 { p["CONTENT_TYPE"] = bodyType } else { p["CONTENT_TYPE"] = "application/x-www-form-urlencoded" } return c.Request(p, body) } // PostForm issues a POST to the fcgi responder, with form // as a string key to a list values (url.Values) func (c *client) PostForm(p map[string]string, data url.Values) (resp *http.Response, err error) { body := bytes.NewReader([]byte(data.Encode())) return c.Post(p, "POST", "application/x-www-form-urlencoded", body, int64(body.Len())) } // PostFile issues a POST to the fcgi responder in multipart(RFC 2046) standard, // with form as a string key to a list values (url.Values), // and/or with file as a string key to a list file path. func (c *client) PostFile(p map[string]string, data url.Values, file map[string]string) (resp *http.Response, err error) { buf := &bytes.Buffer{} writer := multipart.NewWriter(buf) bodyType := writer.FormDataContentType() for key, val := range data { for _, v0 := range val { err = writer.WriteField(key, v0) if err != nil { return resp, err } } } for key, val := range file { fd, e := os.Open(val) if e != nil { return nil, e } defer fd.Close() part, e := writer.CreateFormFile(key, filepath.Base(val)) if e != nil { return nil, e } _, err = io.Copy(part, fd) if err != nil { return resp, err } } err = writer.Close() if err != nil { return resp, err } return c.Post(p, "POST", bodyType, buf, int64(buf.Len())) } // SetReadTimeout sets the read timeout for future calls that read from the // fcgi responder. A zero value for t means no timeout will be set. func (c *client) SetReadTimeout(t time.Duration) error { if t != 0 { return c.rwc.SetReadDeadline(time.Now().Add(t)) } return nil } // SetWriteTimeout sets the write timeout for future calls that send data to // the fcgi responder. A zero value for t means no timeout will be set. func (c *client) SetWriteTimeout(t time.Duration) error { if t != 0 { return c.rwc.SetWriteDeadline(time.Now().Add(t)) } return nil } // Checks whether chunked is part of the encodings stack func chunked(te []string) bool { return len(te) > 0 && te[0] == "chunked" }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/reverseproxy/fastcgi/writer.go
modules/caddyhttp/reverseproxy/fastcgi/writer.go
// Copyright 2015 Matthew Holt and The Caddy 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 fastcgi import ( "bytes" "encoding/binary" ) // streamWriter abstracts out the separation of a stream into discrete records. // It only writes maxWrite bytes at a time. type streamWriter struct { c *client h header buf *bytes.Buffer recType uint8 } func (w *streamWriter) writeRecord(recType uint8, content []byte) (err error) { w.h.init(recType, w.c.reqID, len(content)) w.buf.Write(pad[:8]) w.writeHeader() w.buf.Write(content) w.buf.Write(pad[:w.h.PaddingLength]) _, err = w.buf.WriteTo(w.c.rwc) return err } func (w *streamWriter) writeBeginRequest(role uint16, flags uint8) error { b := [8]byte{byte(role >> 8), byte(role), flags} return w.writeRecord(BeginRequest, b[:]) } func (w *streamWriter) Write(p []byte) (int, error) { // init header if w.buf.Len() < 8 { w.buf.Write(pad[:8]) } nn := 0 for len(p) > 0 { n := len(p) nl := maxWrite + 8 - w.buf.Len() if n > nl { n = nl w.buf.Write(p[:n]) if err := w.Flush(); err != nil { return nn, err } // reset headers w.buf.Write(pad[:8]) } else { w.buf.Write(p[:n]) } nn += n p = p[n:] } return nn, nil } func (w *streamWriter) endStream() error { // send empty record to close the stream return w.writeRecord(w.recType, nil) } func (w *streamWriter) writePairs(pairs map[string]string) error { b := make([]byte, 8) nn := 0 // init headers w.buf.Write(b) for k, v := range pairs { m := 8 + len(k) + len(v) if m > maxWrite { // param data size exceed 65535 bytes" vl := maxWrite - 8 - len(k) v = v[:vl] } n := encodeSize(b, uint32(len(k))) n += encodeSize(b[n:], uint32(len(v))) m = n + len(k) + len(v) if (nn + m) > maxWrite { if err := w.Flush(); err != nil { return err } // reset headers w.buf.Write(b) nn = 0 } nn += m w.buf.Write(b[:n]) w.buf.WriteString(k) w.buf.WriteString(v) } return w.FlushStream() } func encodeSize(b []byte, size uint32) int { if size > 127 { size |= 1 << 31 binary.BigEndian.PutUint32(b, size) return 4 } b[0] = byte(size) //nolint:gosec // false positive; b is made 8 bytes long, then this function is always called with b being at least 4 or 1 byte long return 1 } // writeHeader populate header wire data in buf, it abuses buffer.Bytes() modification func (w *streamWriter) writeHeader() { h := w.buf.Bytes()[:8] h[0] = w.h.Version h[1] = w.h.Type binary.BigEndian.PutUint16(h[2:4], w.h.ID) binary.BigEndian.PutUint16(h[4:6], w.h.ContentLength) h[6] = w.h.PaddingLength h[7] = w.h.Reserved } // Flush write buffer data to the underlying connection, it assumes header data is the first 8 bytes of buf func (w *streamWriter) Flush() error { w.h.init(w.recType, w.c.reqID, w.buf.Len()-8) w.writeHeader() w.buf.Write(pad[:w.h.PaddingLength]) _, err := w.buf.WriteTo(w.c.rwc) return err } // FlushStream flush data then end current stream func (w *streamWriter) FlushStream() error { if err := w.Flush(); err != nil { return err } return w.endStream() }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false