language
stringlengths
0
24
filename
stringlengths
9
214
code
stringlengths
99
9.93M
Go
caddy/caddyconfig/httpcaddyfile/builtins_test.go
package httpcaddyfile import ( "strings" "testing" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" _ "github.com/caddyserver/caddy/v2/modules/logging" ) func TestLogDirectiveSyntax(t *testing.T) { for i, tc := range []struct { input string output string expectError bool }{ { input: `:8080 { log } `, output: `{"apps":{"http":{"servers":{"srv0":{"listen":[":8080"],"logs":{}}}}}}`, expectError: false, }, { input: `:8080 { log { output file foo.log } } `, output: `{"logging":{"logs":{"default":{"exclude":["http.log.access.log0"]},"log0":{"writer":{"filename":"foo.log","output":"file"},"include":["http.log.access.log0"]}}},"apps":{"http":{"servers":{"srv0":{"listen":[":8080"],"logs":{"default_logger_name":"log0"}}}}}}`, expectError: false, }, { input: `:8080 { log { format filter { wrap console fields { request>remote_ip ip_mask { ipv4 24 ipv6 32 } } } } } `, output: `{"logging":{"logs":{"default":{"exclude":["http.log.access.log0"]},"log0":{"encoder":{"fields":{"request\u003eremote_ip":{"filter":"ip_mask","ipv4_cidr":24,"ipv6_cidr":32}},"format":"filter","wrap":{"format":"console"}},"include":["http.log.access.log0"]}}},"apps":{"http":{"servers":{"srv0":{"listen":[":8080"],"logs":{"default_logger_name":"log0"}}}}}}`, expectError: false, }, { input: `:8080 { log name-override { output file foo.log } } `, output: `{"logging":{"logs":{"default":{"exclude":["http.log.access.name-override"]},"name-override":{"writer":{"filename":"foo.log","output":"file"},"include":["http.log.access.name-override"]}}},"apps":{"http":{"servers":{"srv0":{"listen":[":8080"],"logs":{"default_logger_name":"name-override"}}}}}}`, expectError: false, }, } { adapter := caddyfile.Adapter{ ServerType: ServerType{}, } out, _, err := adapter.Adapt([]byte(tc.input), nil) if err != nil != tc.expectError { t.Errorf("Test %d error expectation failed Expected: %v, got %s", i, tc.expectError, err) continue } if string(out) != tc.output { t.Errorf("Test %d error output mismatch Expected: %s, got %s", i, tc.output, out) } } } func TestRedirDirectiveSyntax(t *testing.T) { for i, tc := range []struct { input string expectError bool }{ { input: `:8080 { redir :8081 }`, expectError: false, }, { input: `:8080 { redir * :8081 }`, expectError: false, }, { input: `:8080 { redir /api/* :8081 300 }`, expectError: false, }, { input: `:8080 { redir :8081 300 }`, expectError: false, }, { input: `:8080 { redir /api/* :8081 399 }`, expectError: false, }, { input: `:8080 { redir :8081 399 }`, expectError: false, }, { input: `:8080 { redir /old.html /new.html }`, expectError: false, }, { input: `:8080 { redir /old.html /new.html temporary }`, expectError: false, }, { input: `:8080 { redir https://example.com{uri} permanent }`, expectError: false, }, { input: `:8080 { redir /old.html /new.html permanent }`, expectError: false, }, { input: `:8080 { redir /old.html /new.html html }`, expectError: false, }, { // this is now allowed so a Location header // can be written and consumed by JS // in the case of XHR requests input: `:8080 { redir * :8081 401 }`, expectError: false, }, { input: `:8080 { redir * :8081 402 }`, expectError: true, }, { input: `:8080 { redir * :8081 {http.reverse_proxy.status_code} }`, expectError: false, }, { input: `:8080 { redir /old.html /new.html htlm }`, expectError: true, }, { input: `:8080 { redir * :8081 200 }`, expectError: true, }, { input: `:8080 { redir * :8081 temp }`, expectError: true, }, { input: `:8080 { redir * :8081 perm }`, expectError: true, }, { input: `:8080 { redir * :8081 php }`, expectError: true, }, } { adapter := caddyfile.Adapter{ ServerType: ServerType{}, } _, _, err := adapter.Adapt([]byte(tc.input), nil) if err != nil != tc.expectError { t.Errorf("Test %d error expectation failed Expected: %v, got %s", i, tc.expectError, err) continue } } } func TestImportErrorLine(t *testing.T) { for i, tc := range []struct { input string errorFunc func(err error) bool }{ { input: `(t1) { abort {args[:]} } :8080 { import t1 import t1 true }`, errorFunc: func(err error) bool { return err != nil && strings.Contains(err.Error(), "Caddyfile:6 (import t1)") }, }, { input: `(t1) { abort {args[:]} } :8080 { import t1 true }`, errorFunc: func(err error) bool { return err != nil && strings.Contains(err.Error(), "Caddyfile:5 (import t1)") }, }, { input: ` import testdata/import_variadic_snippet.txt :8080 { import t1 true }`, errorFunc: func(err error) bool { return err == nil }, }, { input: ` import testdata/import_variadic_with_import.txt :8080 { import t1 true import t2 true }`, errorFunc: func(err error) bool { return err == nil }, }, } { adapter := caddyfile.Adapter{ ServerType: ServerType{}, } _, _, err := adapter.Adapt([]byte(tc.input), nil) if !tc.errorFunc(err) { t.Errorf("Test %d error expectation failed, got %s", i, err) continue } } } func TestNestedImport(t *testing.T) { for i, tc := range []struct { input string errorFunc func(err error) bool }{ { input: `(t1) { respond {args[0]} {args[1]} } (t2) { import t1 {args[0]} 202 } :8080 { handle { import t2 "foobar" } }`, errorFunc: func(err error) bool { return err == nil }, }, { input: `(t1) { respond {args[:]} } (t2) { import t1 {args[0]} {args[1]} } :8080 { handle { import t2 "foobar" 202 } }`, errorFunc: func(err error) bool { return err == nil }, }, { input: `(t1) { respond {args[0]} {args[1]} } (t2) { import t1 {args[:]} } :8080 { handle { import t2 "foobar" 202 } }`, errorFunc: func(err error) bool { return err == nil }, }, } { adapter := caddyfile.Adapter{ ServerType: ServerType{}, } _, _, err := adapter.Adapt([]byte(tc.input), nil) if !tc.errorFunc(err) { t.Errorf("Test %d error expectation failed, got %s", i, err) continue } } }
Go
caddy/caddyconfig/httpcaddyfile/directives.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 httpcaddyfile import ( "encoding/json" "net" "sort" "strconv" "strings" "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" ) // directiveOrder specifies the order // to apply directives in HTTP routes. // // The root directive goes first in case rewrites or // redirects depend on existence of files, i.e. the // file matcher, which must know the root first. // // The header directive goes second so that headers // can be manipulated before doing redirects. var directiveOrder = []string{ "tracing", "map", "vars", "root", "skip_log", "header", "copy_response_headers", // only in reverse_proxy's handle_response "request_body", "redir", // incoming request manipulation "method", "rewrite", "uri", "try_files", // middleware handlers; some wrap responses "basicauth", "forward_auth", "request_header", "encode", "push", "templates", // special routing & dispatching directives "invoke", "handle", "handle_path", "route", // handlers that typically respond to requests "abort", "error", "copy_response", // only in reverse_proxy's handle_response "respond", "metrics", "reverse_proxy", "php_fastcgi", "file_server", "acme_server", } // directiveIsOrdered returns true if dir is // a known, ordered (sorted) directive. func directiveIsOrdered(dir string) bool { for _, d := range directiveOrder { if d == dir { return true } } return false } // RegisterDirective registers a unique directive dir with an // associated unmarshaling (setup) function. When directive dir // is encountered in a Caddyfile, setupFunc will be called to // unmarshal its tokens. func RegisterDirective(dir string, setupFunc UnmarshalFunc) { if _, ok := registeredDirectives[dir]; ok { panic("directive " + dir + " already registered") } registeredDirectives[dir] = setupFunc } // RegisterHandlerDirective is like RegisterDirective, but for // directives which specifically output only an HTTP handler. // Directives registered with this function will always have // an optional matcher token as the first argument. func RegisterHandlerDirective(dir string, setupFunc UnmarshalHandlerFunc) { RegisterDirective(dir, func(h Helper) ([]ConfigValue, error) { if !h.Next() { return nil, h.ArgErr() } matcherSet, err := h.ExtractMatcherSet() if err != nil { return nil, err } val, err := setupFunc(h) if err != nil { return nil, err } return h.NewRoute(matcherSet, val), nil }) } // RegisterGlobalOption registers a unique global option opt with // an associated unmarshaling (setup) function. When the global // option opt is encountered in a Caddyfile, setupFunc will be // called to unmarshal its tokens. func RegisterGlobalOption(opt string, setupFunc UnmarshalGlobalFunc) { if _, ok := registeredGlobalOptions[opt]; ok { panic("global option " + opt + " already registered") } registeredGlobalOptions[opt] = setupFunc } // Helper is a type which helps setup a value from // Caddyfile tokens. type Helper struct { *caddyfile.Dispenser // State stores intermediate variables during caddyfile adaptation. State map[string]any options map[string]any warnings *[]caddyconfig.Warning matcherDefs map[string]caddy.ModuleMap parentBlock caddyfile.ServerBlock groupCounter counter } // Option gets the option keyed by name. func (h Helper) Option(name string) any { return h.options[name] } // Caddyfiles returns the list of config files from // which tokens in the current server block were loaded. func (h Helper) Caddyfiles() []string { // first obtain set of names of files involved // in this server block, without duplicates files := make(map[string]struct{}) for _, segment := range h.parentBlock.Segments { for _, token := range segment { files[token.File] = struct{}{} } } // then convert the set into a slice filesSlice := make([]string, 0, len(files)) for file := range files { filesSlice = append(filesSlice, file) } sort.Strings(filesSlice) return filesSlice } // JSON converts val into JSON. Any errors are added to warnings. func (h Helper) JSON(val any) json.RawMessage { return caddyconfig.JSON(val, h.warnings) } // MatcherToken assumes the next argument token is (possibly) a matcher, // and if so, returns the matcher set along with a true value. If the next // token is not a matcher, nil and false is returned. Note that a true // value may be returned with a nil matcher set if it is a catch-all. func (h Helper) MatcherToken() (caddy.ModuleMap, bool, error) { if !h.NextArg() { return nil, false, nil } return matcherSetFromMatcherToken(h.Dispenser.Token(), h.matcherDefs, h.warnings) } // ExtractMatcherSet is like MatcherToken, except this is a higher-level // method that returns the matcher set described by the matcher token, // or nil if there is none, and deletes the matcher token from the // dispenser and resets it as if this look-ahead never happened. Useful // when wrapping a route (one or more handlers) in a user-defined matcher. func (h Helper) ExtractMatcherSet() (caddy.ModuleMap, error) { matcherSet, hasMatcher, err := h.MatcherToken() if err != nil { return nil, err } if hasMatcher { // strip matcher token; we don't need to // use the return value here because a // new dispenser should have been made // solely for this directive's tokens, // with no other uses of same slice h.Dispenser.Delete() } h.Dispenser.Reset() // pretend this lookahead never happened return matcherSet, nil } // NewRoute returns config values relevant to creating a new HTTP route. func (h Helper) NewRoute(matcherSet caddy.ModuleMap, handler caddyhttp.MiddlewareHandler, ) []ConfigValue { mod, err := caddy.GetModule(caddy.GetModuleID(handler)) if err != nil { *h.warnings = append(*h.warnings, caddyconfig.Warning{ File: h.File(), Line: h.Line(), Message: err.Error(), }) return nil } var matcherSetsRaw []caddy.ModuleMap if matcherSet != nil { matcherSetsRaw = append(matcherSetsRaw, matcherSet) } return []ConfigValue{ { Class: "route", Value: caddyhttp.Route{ MatcherSetsRaw: matcherSetsRaw, HandlersRaw: []json.RawMessage{caddyconfig.JSONModuleObject(handler, "handler", mod.ID.Name(), h.warnings)}, }, }, } } // GroupRoutes adds the routes (caddyhttp.Route type) in vals to the // same group, if there is more than one route in vals. func (h Helper) GroupRoutes(vals []ConfigValue) { // ensure there's at least two routes; group of one is pointless var count int for _, v := range vals { if _, ok := v.Value.(caddyhttp.Route); ok { count++ if count > 1 { break } } } if count < 2 { return } // now that we know the group will have some effect, do it groupName := h.groupCounter.nextGroup() for i := range vals { if route, ok := vals[i].Value.(caddyhttp.Route); ok { route.Group = groupName vals[i].Value = route } } } // NewBindAddresses returns config values relevant to adding // listener bind addresses to the config. func (h Helper) NewBindAddresses(addrs []string) []ConfigValue { return []ConfigValue{{Class: "bind", Value: addrs}} } // WithDispenser returns a new instance based on d. All others Helper // fields are copied, so typically maps are shared with this new instance. func (h Helper) WithDispenser(d *caddyfile.Dispenser) Helper { h.Dispenser = d return h } // ParseSegmentAsSubroute parses the segment such that its subdirectives // are themselves treated as directives, from which a subroute is built // and returned. func ParseSegmentAsSubroute(h Helper) (caddyhttp.MiddlewareHandler, error) { allResults, err := parseSegmentAsConfig(h) if err != nil { return nil, err } return buildSubroute(allResults, h.groupCounter, true) } // parseSegmentAsConfig parses the segment such that its subdirectives // are themselves treated as directives, including named matcher definitions, // and the raw Config structs are returned. func parseSegmentAsConfig(h Helper) ([]ConfigValue, error) { var allResults []ConfigValue for h.Next() { // don't allow non-matcher args on the first line if h.NextArg() { return nil, h.ArgErr() } // slice the linear list of tokens into top-level segments var segments []caddyfile.Segment for nesting := h.Nesting(); h.NextBlock(nesting); { segments = append(segments, h.NextSegment()) } // copy existing matcher definitions so we can augment // new ones that are defined only in this scope matcherDefs := make(map[string]caddy.ModuleMap, len(h.matcherDefs)) for key, val := range h.matcherDefs { matcherDefs[key] = val } // find and extract any embedded matcher definitions in this scope for i := 0; i < len(segments); i++ { seg := segments[i] if strings.HasPrefix(seg.Directive(), matcherPrefix) { // parse, then add the matcher to matcherDefs err := parseMatcherDefinitions(caddyfile.NewDispenser(seg), matcherDefs) if err != nil { return nil, err } // remove the matcher segment (consumed), then step back the loop segments = append(segments[:i], segments[i+1:]...) i-- } } // with matchers ready to go, evaluate each directive's segment for _, seg := range segments { dir := seg.Directive() dirFunc, ok := registeredDirectives[dir] if !ok { return nil, h.Errf("unrecognized directive: %s - are you sure your Caddyfile structure (nesting and braces) is correct?", dir) } subHelper := h subHelper.Dispenser = caddyfile.NewDispenser(seg) subHelper.matcherDefs = matcherDefs results, err := dirFunc(subHelper) if err != nil { return nil, h.Errf("parsing caddyfile tokens for '%s': %v", dir, err) } dir = normalizeDirectiveName(dir) for _, result := range results { result.directive = dir allResults = append(allResults, result) } } } return allResults, nil } // ConfigValue represents a value to be added to the final // configuration, or a value to be consulted when building // the final configuration. type ConfigValue struct { // The kind of value this is. As the config is // being built, the adapter will look in the // "pile" for values belonging to a certain // class when it is setting up a certain part // of the config. The associated value will be // type-asserted and placed accordingly. Class string // The value to be used when building the config. // Generally its type is associated with the // name of the Class. Value any directive string } func sortRoutes(routes []ConfigValue) { dirPositions := make(map[string]int) for i, dir := range directiveOrder { dirPositions[dir] = i } sort.SliceStable(routes, func(i, j int) bool { // if the directives are different, just use the established directive order iDir, jDir := routes[i].directive, routes[j].directive if iDir != jDir { return dirPositions[iDir] < dirPositions[jDir] } // directives are the same; sub-sort by path matcher length if there's // only one matcher set and one path (this is a very common case and // usually -- but not always -- helpful/expected, oh well; user can // always take manual control of order using handler or route blocks) iRoute, ok := routes[i].Value.(caddyhttp.Route) if !ok { return false } jRoute, ok := routes[j].Value.(caddyhttp.Route) if !ok { return false } // decode the path matchers if there is just one matcher set var iPM, jPM caddyhttp.MatchPath if len(iRoute.MatcherSetsRaw) == 1 { _ = json.Unmarshal(iRoute.MatcherSetsRaw[0]["path"], &iPM) } if len(jRoute.MatcherSetsRaw) == 1 { _ = json.Unmarshal(jRoute.MatcherSetsRaw[0]["path"], &jPM) } // if there is only one path in the path matcher, sort by longer path // (more specific) first; missing path matchers or multi-matchers are // treated as zero-length paths var iPathLen, jPathLen int if len(iPM) == 1 { iPathLen = len(iPM[0]) } if len(jPM) == 1 { jPathLen = len(jPM[0]) } sortByPath := func() bool { // we can only confidently compare path lengths if both // directives have a single path to match (issue #5037) if iPathLen > 0 && jPathLen > 0 { // if both paths are the same except for a trailing wildcard, // sort by the shorter path first (which is more specific) if strings.TrimSuffix(iPM[0], "*") == strings.TrimSuffix(jPM[0], "*") { return iPathLen < jPathLen } // sort most-specific (longest) path first return iPathLen > jPathLen } // if both directives don't have a single path to compare, // sort whichever one has a matcher first; if both have // a matcher, sort equally (stable sort preserves order) return len(iRoute.MatcherSetsRaw) > 0 && len(jRoute.MatcherSetsRaw) == 0 }() // some directives involve setting values which can overwrite // each other, so it makes most sense to reverse the order so // that the least-specific matcher is first, allowing the last // matching one to win if iDir == "vars" { return !sortByPath } // everything else is most-specific matcher first return sortByPath }) } // serverBlock pairs a Caddyfile server block with // a "pile" of config values, keyed by class name, // as well as its parsed keys for convenience. type serverBlock struct { block caddyfile.ServerBlock pile map[string][]ConfigValue // config values obtained from directives keys []Address } // hostsFromKeys returns a list of all the non-empty hostnames found in // the keys of the server block sb. If logger mode is false, a key with // an empty hostname portion will return an empty slice, since that // server block is interpreted to effectively match all hosts. An empty // string is never added to the slice. // // If loggerMode is true, then the non-standard ports of keys will be // joined to the hostnames. This is to effectively match the Host // header of requests that come in for that key. // // The resulting slice is not sorted but will never have duplicates. func (sb serverBlock) hostsFromKeys(loggerMode bool) []string { // ensure each entry in our list is unique hostMap := make(map[string]struct{}) for _, addr := range sb.keys { if addr.Host == "" { if !loggerMode { // server block contains a key like ":443", i.e. the host portion // is empty / catch-all, which means to match all hosts return []string{} } // never append an empty string continue } if loggerMode && addr.Port != "" && addr.Port != strconv.Itoa(caddyhttp.DefaultHTTPPort) && addr.Port != strconv.Itoa(caddyhttp.DefaultHTTPSPort) { hostMap[net.JoinHostPort(addr.Host, addr.Port)] = struct{}{} } else { hostMap[addr.Host] = struct{}{} } } // convert map to slice sblockHosts := make([]string, 0, len(hostMap)) for host := range hostMap { sblockHosts = append(sblockHosts, host) } return sblockHosts } func (sb serverBlock) hostsFromKeysNotHTTP(httpPort string) []string { // ensure each entry in our list is unique hostMap := make(map[string]struct{}) for _, addr := range sb.keys { if addr.Host == "" { continue } if addr.Scheme != "http" && addr.Port != httpPort { hostMap[addr.Host] = struct{}{} } } // convert map to slice sblockHosts := make([]string, 0, len(hostMap)) for host := range hostMap { sblockHosts = append(sblockHosts, host) } return sblockHosts } // hasHostCatchAllKey returns true if sb has a key that // omits a host portion, i.e. it "catches all" hosts. func (sb serverBlock) hasHostCatchAllKey() bool { for _, addr := range sb.keys { if addr.Host == "" { return true } } return false } // isAllHTTP returns true if all sb keys explicitly specify // the http:// scheme func (sb serverBlock) isAllHTTP() bool { for _, addr := range sb.keys { if addr.Scheme != "http" { return false } } return true } type ( // UnmarshalFunc is a function which can unmarshal Caddyfile // tokens into zero or more config values using a Helper type. // These are passed in a call to RegisterDirective. UnmarshalFunc func(h Helper) ([]ConfigValue, error) // UnmarshalHandlerFunc is like UnmarshalFunc, except the // output of the unmarshaling is an HTTP handler. This // function does not need to deal with HTTP request matching // which is abstracted away. Since writing HTTP handlers // with Caddyfile support is very common, this is a more // convenient way to add a handler to the chain since a lot // of the details common to HTTP handlers are taken care of // for you. These are passed to a call to // RegisterHandlerDirective. UnmarshalHandlerFunc func(h Helper) (caddyhttp.MiddlewareHandler, error) // UnmarshalGlobalFunc is a function which can unmarshal Caddyfile // tokens from a global option. It is passed the tokens to parse and // existing value from the previous instance of this global option // (if any). It returns the value to associate with this global option. UnmarshalGlobalFunc func(d *caddyfile.Dispenser, existingVal any) (any, error) ) var registeredDirectives = make(map[string]UnmarshalFunc) var registeredGlobalOptions = make(map[string]UnmarshalGlobalFunc)
Go
caddy/caddyconfig/httpcaddyfile/directives_test.go
package httpcaddyfile import ( "reflect" "sort" "testing" ) func TestHostsFromKeys(t *testing.T) { for i, tc := range []struct { keys []Address expectNormalMode []string expectLoggerMode []string }{ { []Address{ {Original: "foo", Host: "foo"}, }, []string{"foo"}, []string{"foo"}, }, { []Address{ {Original: "foo", Host: "foo"}, {Original: "bar", Host: "bar"}, }, []string{"bar", "foo"}, []string{"bar", "foo"}, }, { []Address{ {Original: ":2015", Port: "2015"}, }, []string{}, []string{}, }, { []Address{ {Original: ":443", Port: "443"}, }, []string{}, []string{}, }, { []Address{ {Original: "foo", Host: "foo"}, {Original: ":2015", Port: "2015"}, }, []string{}, []string{"foo"}, }, { []Address{ {Original: "example.com:2015", Host: "example.com", Port: "2015"}, }, []string{"example.com"}, []string{"example.com:2015"}, }, { []Address{ {Original: "example.com:80", Host: "example.com", Port: "80"}, }, []string{"example.com"}, []string{"example.com"}, }, { []Address{ {Original: "https://:2015/foo", Scheme: "https", Port: "2015", Path: "/foo"}, }, []string{}, []string{}, }, { []Address{ {Original: "https://example.com:2015/foo", Scheme: "https", Host: "example.com", Port: "2015", Path: "/foo"}, }, []string{"example.com"}, []string{"example.com:2015"}, }, } { sb := serverBlock{keys: tc.keys} // test in normal mode actual := sb.hostsFromKeys(false) sort.Strings(actual) if !reflect.DeepEqual(tc.expectNormalMode, actual) { t.Errorf("Test %d (loggerMode=false): Expected: %v Actual: %v", i, tc.expectNormalMode, actual) } // test in logger mode actual = sb.hostsFromKeys(true) sort.Strings(actual) if !reflect.DeepEqual(tc.expectLoggerMode, actual) { t.Errorf("Test %d (loggerMode=true): Expected: %v Actual: %v", i, tc.expectLoggerMode, actual) } } }
Go
caddy/caddyconfig/httpcaddyfile/httptype.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 httpcaddyfile import ( "encoding/json" "fmt" "reflect" "regexp" "sort" "strconv" "strings" "go.uber.org/zap" "golang.org/x/exp/slices" "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" "github.com/caddyserver/caddy/v2/modules/caddypki" "github.com/caddyserver/caddy/v2/modules/caddytls" ) func init() { caddyconfig.RegisterAdapter("caddyfile", caddyfile.Adapter{ServerType: ServerType{}}) } // App represents the configuration for a non-standard // Caddy app module (e.g. third-party plugin) which was // parsed from a global options block. type App struct { // The JSON key for the app being configured Name string // The raw app config as JSON Value json.RawMessage } // ServerType can set up a config from an HTTP Caddyfile. type ServerType struct{} // Setup makes a config from the tokens. func (st ServerType) Setup( inputServerBlocks []caddyfile.ServerBlock, options map[string]any, ) (*caddy.Config, []caddyconfig.Warning, error) { var warnings []caddyconfig.Warning gc := counter{new(int)} state := make(map[string]any) // load all the server blocks and associate them with a "pile" of config values originalServerBlocks := make([]serverBlock, 0, len(inputServerBlocks)) for _, sblock := range inputServerBlocks { for j, k := range sblock.Keys { if j == 0 && strings.HasPrefix(k, "@") { return nil, warnings, fmt.Errorf("cannot define a matcher outside of a site block: '%s'", k) } } originalServerBlocks = append(originalServerBlocks, serverBlock{ block: sblock, pile: make(map[string][]ConfigValue), }) } // apply any global options var err error originalServerBlocks, err = st.evaluateGlobalOptionsBlock(originalServerBlocks, options) if err != nil { return nil, warnings, err } originalServerBlocks, err = st.extractNamedRoutes(originalServerBlocks, options, &warnings) if err != nil { return nil, warnings, err } // replace shorthand placeholders (which are convenient // when writing a Caddyfile) with their actual placeholder // identifiers or variable names replacer := strings.NewReplacer(placeholderShorthands()...) // these are placeholders that allow a user-defined final // parameters, but we still want to provide a shorthand // for those, so we use a regexp to replace regexpReplacements := []struct { search *regexp.Regexp replace string }{ {regexp.MustCompile(`{header\.([\w-]*)}`), "{http.request.header.$1}"}, {regexp.MustCompile(`{cookie\.([\w-]*)}`), "{http.request.cookie.$1}"}, {regexp.MustCompile(`{labels\.([\w-]*)}`), "{http.request.host.labels.$1}"}, {regexp.MustCompile(`{path\.([\w-]*)}`), "{http.request.uri.path.$1}"}, {regexp.MustCompile(`{file\.([\w-]*)}`), "{http.request.uri.path.file.$1}"}, {regexp.MustCompile(`{query\.([\w-]*)}`), "{http.request.uri.query.$1}"}, {regexp.MustCompile(`{re\.([\w-]*)\.([\w-]*)}`), "{http.regexp.$1.$2}"}, {regexp.MustCompile(`{vars\.([\w-]*)}`), "{http.vars.$1}"}, {regexp.MustCompile(`{rp\.([\w-\.]*)}`), "{http.reverse_proxy.$1}"}, {regexp.MustCompile(`{err\.([\w-\.]*)}`), "{http.error.$1}"}, {regexp.MustCompile(`{file_match\.([\w-]*)}`), "{http.matchers.file.$1}"}, } for _, sb := range originalServerBlocks { for _, segment := range sb.block.Segments { for i := 0; i < len(segment); i++ { // simple string replacements segment[i].Text = replacer.Replace(segment[i].Text) // complex regexp replacements for _, r := range regexpReplacements { segment[i].Text = r.search.ReplaceAllString(segment[i].Text, r.replace) } } } if len(sb.block.Keys) == 0 { return nil, warnings, fmt.Errorf("server block without any key is global configuration, and if used, it must be first") } // extract matcher definitions matcherDefs := make(map[string]caddy.ModuleMap) for _, segment := range sb.block.Segments { if dir := segment.Directive(); strings.HasPrefix(dir, matcherPrefix) { d := sb.block.DispenseDirective(dir) err := parseMatcherDefinitions(d, matcherDefs) if err != nil { return nil, warnings, err } } } // evaluate each directive ("segment") in this block for _, segment := range sb.block.Segments { dir := segment.Directive() if strings.HasPrefix(dir, matcherPrefix) { // matcher definitions were pre-processed continue } dirFunc, ok := registeredDirectives[dir] if !ok { tkn := segment[0] message := "%s:%d: unrecognized directive: %s" if !sb.block.HasBraces { message += "\nDid you mean to define a second site? If so, you must use curly braces around each site to separate their configurations." } return nil, warnings, fmt.Errorf(message, tkn.File, tkn.Line, dir) } h := Helper{ Dispenser: caddyfile.NewDispenser(segment), options: options, warnings: &warnings, matcherDefs: matcherDefs, parentBlock: sb.block, groupCounter: gc, State: state, } results, err := dirFunc(h) if err != nil { return nil, warnings, fmt.Errorf("parsing caddyfile tokens for '%s': %v", dir, err) } dir = normalizeDirectiveName(dir) for _, result := range results { result.directive = dir sb.pile[result.Class] = append(sb.pile[result.Class], result) } // specially handle named routes that were pulled out from // the invoke directive, which could be nested anywhere within // some subroutes in this directive; we add them to the pile // for this server block if state[namedRouteKey] != nil { for name := range state[namedRouteKey].(map[string]struct{}) { result := ConfigValue{Class: namedRouteKey, Value: name} sb.pile[result.Class] = append(sb.pile[result.Class], result) } state[namedRouteKey] = nil } } } // map sbmap, err := st.mapAddressToServerBlocks(originalServerBlocks, options) if err != nil { return nil, warnings, err } // reduce pairings := st.consolidateAddrMappings(sbmap) // each pairing of listener addresses to list of server // blocks is basically a server definition servers, err := st.serversFromPairings(pairings, options, &warnings, gc) if err != nil { return nil, warnings, err } // now that each server is configured, make the HTTP app httpApp := caddyhttp.App{ HTTPPort: tryInt(options["http_port"], &warnings), HTTPSPort: tryInt(options["https_port"], &warnings), GracePeriod: tryDuration(options["grace_period"], &warnings), ShutdownDelay: tryDuration(options["shutdown_delay"], &warnings), Servers: servers, } // then make the TLS app tlsApp, warnings, err := st.buildTLSApp(pairings, options, warnings) if err != nil { return nil, warnings, err } // then make the PKI app pkiApp, warnings, err := st.buildPKIApp(pairings, options, warnings) if err != nil { return nil, warnings, err } // extract any custom logs, and enforce configured levels var customLogs []namedCustomLog var hasDefaultLog bool addCustomLog := func(ncl namedCustomLog) { if ncl.name == "" { return } if ncl.name == caddy.DefaultLoggerName { hasDefaultLog = true } if _, ok := options["debug"]; ok && ncl.log != nil && ncl.log.Level == "" { ncl.log.Level = zap.DebugLevel.CapitalString() } customLogs = append(customLogs, ncl) } // Apply global log options, when set if options["log"] != nil { for _, logValue := range options["log"].([]ConfigValue) { addCustomLog(logValue.Value.(namedCustomLog)) } } if !hasDefaultLog { // if the default log was not customized, ensure we // configure it with any applicable options if _, ok := options["debug"]; ok { customLogs = append(customLogs, namedCustomLog{ name: caddy.DefaultLoggerName, log: &caddy.CustomLog{ BaseLog: caddy.BaseLog{Level: zap.DebugLevel.CapitalString()}, }, }) } } // Apply server-specific log options for _, p := range pairings { for _, sb := range p.serverBlocks { for _, clVal := range sb.pile["custom_log"] { addCustomLog(clVal.Value.(namedCustomLog)) } } } // annnd the top-level config, then we're done! cfg := &caddy.Config{AppsRaw: make(caddy.ModuleMap)} // loop through the configured options, and if any of // them are an httpcaddyfile App, then we insert them // into the config as raw Caddy apps for _, opt := range options { if app, ok := opt.(App); ok { cfg.AppsRaw[app.Name] = app.Value } } // insert the standard Caddy apps into the config if len(httpApp.Servers) > 0 { cfg.AppsRaw["http"] = caddyconfig.JSON(httpApp, &warnings) } if !reflect.DeepEqual(tlsApp, &caddytls.TLS{CertificatesRaw: make(caddy.ModuleMap)}) { cfg.AppsRaw["tls"] = caddyconfig.JSON(tlsApp, &warnings) } if !reflect.DeepEqual(pkiApp, &caddypki.PKI{CAs: make(map[string]*caddypki.CA)}) { cfg.AppsRaw["pki"] = caddyconfig.JSON(pkiApp, &warnings) } if storageCvtr, ok := options["storage"].(caddy.StorageConverter); ok { cfg.StorageRaw = caddyconfig.JSONModuleObject(storageCvtr, "module", storageCvtr.(caddy.Module).CaddyModule().ID.Name(), &warnings) } if adminConfig, ok := options["admin"].(*caddy.AdminConfig); ok && adminConfig != nil { cfg.Admin = adminConfig } if pc, ok := options["persist_config"].(string); ok && pc == "off" { if cfg.Admin == nil { cfg.Admin = new(caddy.AdminConfig) } if cfg.Admin.Config == nil { cfg.Admin.Config = new(caddy.ConfigSettings) } cfg.Admin.Config.Persist = new(bool) } if len(customLogs) > 0 { if cfg.Logging == nil { cfg.Logging = &caddy.Logging{ Logs: make(map[string]*caddy.CustomLog), } } // Add the default log first if defined, so that it doesn't // accidentally get re-created below due to the Exclude logic for _, ncl := range customLogs { if ncl.name == caddy.DefaultLoggerName && ncl.log != nil { cfg.Logging.Logs[caddy.DefaultLoggerName] = ncl.log break } } // Add the rest of the custom logs for _, ncl := range customLogs { if ncl.log == nil || ncl.name == caddy.DefaultLoggerName { continue } if ncl.name != "" { cfg.Logging.Logs[ncl.name] = ncl.log } // most users seem to prefer not writing access logs // to the default log when they are directed to a // file or have any other special customization if ncl.name != caddy.DefaultLoggerName && len(ncl.log.Include) > 0 { defaultLog, ok := cfg.Logging.Logs[caddy.DefaultLoggerName] if !ok { defaultLog = new(caddy.CustomLog) cfg.Logging.Logs[caddy.DefaultLoggerName] = defaultLog } defaultLog.Exclude = append(defaultLog.Exclude, ncl.log.Include...) // avoid duplicates by sorting + compacting sort.Strings(defaultLog.Exclude) defaultLog.Exclude = slices.Compact[[]string, string](defaultLog.Exclude) } } // we may have not actually added anything, so remove if empty if len(cfg.Logging.Logs) == 0 { cfg.Logging = nil } } return cfg, warnings, nil } // evaluateGlobalOptionsBlock evaluates the global options block, // which is expected to be the first server block if it has zero // keys. It returns the updated list of server blocks with the // global options block removed, and updates options accordingly. func (ServerType) evaluateGlobalOptionsBlock(serverBlocks []serverBlock, options map[string]any) ([]serverBlock, error) { if len(serverBlocks) == 0 || len(serverBlocks[0].block.Keys) > 0 { return serverBlocks, nil } for _, segment := range serverBlocks[0].block.Segments { opt := segment.Directive() var val any var err error disp := caddyfile.NewDispenser(segment) optFunc, ok := registeredGlobalOptions[opt] if !ok { tkn := segment[0] return nil, fmt.Errorf("%s:%d: unrecognized global option: %s", tkn.File, tkn.Line, opt) } val, err = optFunc(disp, options[opt]) if err != nil { return nil, fmt.Errorf("parsing caddyfile tokens for '%s': %v", opt, err) } // As a special case, fold multiple "servers" options together // in an array instead of overwriting a possible existing value if opt == "servers" { existingOpts, ok := options[opt].([]serverOptions) if !ok { existingOpts = []serverOptions{} } serverOpts, ok := val.(serverOptions) if !ok { return nil, fmt.Errorf("unexpected type from 'servers' global options: %T", val) } options[opt] = append(existingOpts, serverOpts) continue } // Additionally, fold multiple "log" options together into an // array so that multiple loggers can be configured. if opt == "log" { existingOpts, ok := options[opt].([]ConfigValue) if !ok { existingOpts = []ConfigValue{} } logOpts, ok := val.([]ConfigValue) if !ok { return nil, fmt.Errorf("unexpected type from 'log' global options: %T", val) } options[opt] = append(existingOpts, logOpts...) continue } options[opt] = val } // If we got "servers" options, we'll sort them by their listener address if serverOpts, ok := options["servers"].([]serverOptions); ok { sort.Slice(serverOpts, func(i, j int) bool { return len(serverOpts[i].ListenerAddress) > len(serverOpts[j].ListenerAddress) }) // Reject the config if there are duplicate listener address seen := make(map[string]bool) for _, entry := range serverOpts { if _, alreadySeen := seen[entry.ListenerAddress]; alreadySeen { return nil, fmt.Errorf("cannot have 'servers' global options with duplicate listener addresses: %s", entry.ListenerAddress) } seen[entry.ListenerAddress] = true } } return serverBlocks[1:], nil } // extractNamedRoutes pulls out any named route server blocks // so they don't get parsed as sites, and stores them in options // for later. func (ServerType) extractNamedRoutes( serverBlocks []serverBlock, options map[string]any, warnings *[]caddyconfig.Warning, ) ([]serverBlock, error) { namedRoutes := map[string]*caddyhttp.Route{} gc := counter{new(int)} state := make(map[string]any) // copy the server blocks so we can // splice out the named route ones filtered := append([]serverBlock{}, serverBlocks...) index := -1 for _, sb := range serverBlocks { index++ if !sb.block.IsNamedRoute { continue } // splice out this block, because we know it's not a real server filtered = append(filtered[:index], filtered[index+1:]...) index-- if len(sb.block.Segments) == 0 { continue } // zip up all the segments since ParseSegmentAsSubroute // was designed to take a directive+ wholeSegment := caddyfile.Segment{} for _, segment := range sb.block.Segments { wholeSegment = append(wholeSegment, segment...) } h := Helper{ Dispenser: caddyfile.NewDispenser(wholeSegment), options: options, warnings: warnings, matcherDefs: nil, parentBlock: sb.block, groupCounter: gc, State: state, } handler, err := ParseSegmentAsSubroute(h) if err != nil { return nil, err } subroute := handler.(*caddyhttp.Subroute) route := caddyhttp.Route{} if len(subroute.Routes) == 1 && len(subroute.Routes[0].MatcherSetsRaw) == 0 { // if there's only one route with no matcher, then we can simplify route.HandlersRaw = append(route.HandlersRaw, subroute.Routes[0].HandlersRaw[0]) } else { // otherwise we need the whole subroute route.HandlersRaw = []json.RawMessage{caddyconfig.JSONModuleObject(handler, "handler", subroute.CaddyModule().ID.Name(), h.warnings)} } namedRoutes[sb.block.Keys[0]] = &route } options["named_routes"] = namedRoutes return filtered, nil } // serversFromPairings creates the servers for each pairing of addresses // to server blocks. Each pairing is essentially a server definition. func (st *ServerType) serversFromPairings( pairings []sbAddrAssociation, options map[string]any, warnings *[]caddyconfig.Warning, groupCounter counter, ) (map[string]*caddyhttp.Server, error) { servers := make(map[string]*caddyhttp.Server) defaultSNI := tryString(options["default_sni"], warnings) fallbackSNI := tryString(options["fallback_sni"], warnings) httpPort := strconv.Itoa(caddyhttp.DefaultHTTPPort) if hp, ok := options["http_port"].(int); ok { httpPort = strconv.Itoa(hp) } httpsPort := strconv.Itoa(caddyhttp.DefaultHTTPSPort) if hsp, ok := options["https_port"].(int); ok { httpsPort = strconv.Itoa(hsp) } autoHTTPS := "on" if ah, ok := options["auto_https"].(string); ok { autoHTTPS = ah } for i, p := range pairings { // detect ambiguous site definitions: server blocks which // have the same host bound to the same interface (listener // address), otherwise their routes will improperly be added // to the same server (see issue #4635) for j, sblock1 := range p.serverBlocks { for _, key := range sblock1.block.Keys { for k, sblock2 := range p.serverBlocks { if k == j { continue } if sliceContains(sblock2.block.Keys, key) { return nil, fmt.Errorf("ambiguous site definition: %s", key) } } } } srv := &caddyhttp.Server{ Listen: p.addresses, } // handle the auto_https global option if autoHTTPS != "on" { srv.AutoHTTPS = new(caddyhttp.AutoHTTPSConfig) switch autoHTTPS { case "off": srv.AutoHTTPS.Disabled = true case "disable_redirects": srv.AutoHTTPS.DisableRedir = true case "disable_certs": srv.AutoHTTPS.DisableCerts = true case "ignore_loaded_certs": srv.AutoHTTPS.IgnoreLoadedCerts = true } } // Using paths in site addresses is deprecated // See ParseAddress() where parsing should later reject paths // See https://github.com/caddyserver/caddy/pull/4728 for a full explanation for _, sblock := range p.serverBlocks { for _, addr := range sblock.keys { if addr.Path != "" { caddy.Log().Named("caddyfile").Warn("Using a path in a site address is deprecated; please use the 'handle' directive instead", zap.String("address", addr.String())) } } } // sort server blocks by their keys; this is important because // only the first matching site should be evaluated, and we should // attempt to match most specific site first (host and path), in // case their matchers overlap; we do this somewhat naively by // descending sort by length of host then path sort.SliceStable(p.serverBlocks, func(i, j int) bool { // TODO: we could pre-process the specificities for efficiency, // but I don't expect many blocks will have THAT many keys... var iLongestPath, jLongestPath string var iLongestHost, jLongestHost string var iWildcardHost, jWildcardHost bool for _, addr := range p.serverBlocks[i].keys { if strings.Contains(addr.Host, "*") || addr.Host == "" { iWildcardHost = true } if specificity(addr.Host) > specificity(iLongestHost) { iLongestHost = addr.Host } if specificity(addr.Path) > specificity(iLongestPath) { iLongestPath = addr.Path } } for _, addr := range p.serverBlocks[j].keys { if strings.Contains(addr.Host, "*") || addr.Host == "" { jWildcardHost = true } if specificity(addr.Host) > specificity(jLongestHost) { jLongestHost = addr.Host } if specificity(addr.Path) > specificity(jLongestPath) { jLongestPath = addr.Path } } // catch-all blocks (blocks with no hostname) should always go // last, even after blocks with wildcard hosts if specificity(iLongestHost) == 0 { return false } if specificity(jLongestHost) == 0 { return true } if iWildcardHost != jWildcardHost { // site blocks that have a key with a wildcard in the hostname // must always be less specific than blocks without one; see // https://github.com/caddyserver/caddy/issues/3410 return jWildcardHost && !iWildcardHost } if specificity(iLongestHost) == specificity(jLongestHost) { return len(iLongestPath) > len(jLongestPath) } return specificity(iLongestHost) > specificity(jLongestHost) }) var hasCatchAllTLSConnPolicy, addressQualifiesForTLS bool autoHTTPSWillAddConnPolicy := autoHTTPS != "off" // if needed, the ServerLogConfig is initialized beforehand so // that all server blocks can populate it with data, even when not // coming with a log directive for _, sblock := range p.serverBlocks { if len(sblock.pile["custom_log"]) != 0 { srv.Logs = new(caddyhttp.ServerLogConfig) break } } // add named routes to the server if 'invoke' was used inside of it configuredNamedRoutes := options["named_routes"].(map[string]*caddyhttp.Route) for _, sblock := range p.serverBlocks { if len(sblock.pile[namedRouteKey]) == 0 { continue } for _, value := range sblock.pile[namedRouteKey] { if srv.NamedRoutes == nil { srv.NamedRoutes = map[string]*caddyhttp.Route{} } name := value.Value.(string) if configuredNamedRoutes[name] == nil { return nil, fmt.Errorf("cannot invoke named route '%s', which was not defined", name) } srv.NamedRoutes[name] = configuredNamedRoutes[name] } } // create a subroute for each site in the server block for _, sblock := range p.serverBlocks { matcherSetsEnc, err := st.compileEncodedMatcherSets(sblock) if err != nil { return nil, fmt.Errorf("server block %v: compiling matcher sets: %v", sblock.block.Keys, err) } hosts := sblock.hostsFromKeys(false) // emit warnings if user put unspecified IP addresses; they probably want the bind directive for _, h := range hosts { if h == "0.0.0.0" || h == "::" { caddy.Log().Named("caddyfile").Warn("Site block has an unspecified IP address which only matches requests having that Host header; you probably want the 'bind' directive to configure the socket", zap.String("address", h)) } } // tls: connection policies if cpVals, ok := sblock.pile["tls.connection_policy"]; ok { // tls connection policies for _, cpVal := range cpVals { cp := cpVal.Value.(*caddytls.ConnectionPolicy) // make sure the policy covers all hostnames from the block for _, h := range hosts { if h == defaultSNI { hosts = append(hosts, "") cp.DefaultSNI = defaultSNI break } if h == fallbackSNI { hosts = append(hosts, "") cp.FallbackSNI = fallbackSNI break } } if len(hosts) > 0 { cp.MatchersRaw = caddy.ModuleMap{ "sni": caddyconfig.JSON(hosts, warnings), // make sure to match all hosts, not just auto-HTTPS-qualified ones } } else { cp.DefaultSNI = defaultSNI cp.FallbackSNI = fallbackSNI } // only append this policy if it actually changes something if !cp.SettingsEmpty() { srv.TLSConnPolicies = append(srv.TLSConnPolicies, cp) hasCatchAllTLSConnPolicy = len(hosts) == 0 } } } for _, addr := range sblock.keys { // if server only uses HTTP port, auto-HTTPS will not apply if listenersUseAnyPortOtherThan(srv.Listen, httpPort) { // exclude any hosts that were defined explicitly with "http://" // in the key from automated cert management (issue #2998) if addr.Scheme == "http" && addr.Host != "" { if srv.AutoHTTPS == nil { srv.AutoHTTPS = new(caddyhttp.AutoHTTPSConfig) } if !sliceContains(srv.AutoHTTPS.Skip, addr.Host) { srv.AutoHTTPS.Skip = append(srv.AutoHTTPS.Skip, addr.Host) } } } // we'll need to remember if the address qualifies for auto-HTTPS, so we // can add a TLS conn policy if necessary if addr.Scheme == "https" || (addr.Scheme != "http" && addr.Host != "" && addr.Port != httpPort) { addressQualifiesForTLS = true } // predict whether auto-HTTPS will add the conn policy for us; if so, we // may not need to add one for this server autoHTTPSWillAddConnPolicy = autoHTTPSWillAddConnPolicy && (addr.Port == httpsPort || (addr.Port != httpPort && addr.Host != "")) } // Look for any config values that provide listener wrappers on the server block for _, listenerConfig := range sblock.pile["listener_wrapper"] { listenerWrapper, ok := listenerConfig.Value.(caddy.ListenerWrapper) if !ok { return nil, fmt.Errorf("config for a listener wrapper did not provide a value that implements caddy.ListenerWrapper") } jsonListenerWrapper := caddyconfig.JSONModuleObject( listenerWrapper, "wrapper", listenerWrapper.(caddy.Module).CaddyModule().ID.Name(), warnings) srv.ListenerWrappersRaw = append(srv.ListenerWrappersRaw, jsonListenerWrapper) } // set up each handler directive, making sure to honor directive order dirRoutes := sblock.pile["route"] siteSubroute, err := buildSubroute(dirRoutes, groupCounter, true) if err != nil { return nil, err } // add the site block's route(s) to the server srv.Routes = appendSubrouteToRouteList(srv.Routes, siteSubroute, matcherSetsEnc, p, warnings) // if error routes are defined, add those too if errorSubrouteVals, ok := sblock.pile["error_route"]; ok { if srv.Errors == nil { srv.Errors = new(caddyhttp.HTTPErrorConfig) } for _, val := range errorSubrouteVals { sr := val.Value.(*caddyhttp.Subroute) srv.Errors.Routes = appendSubrouteToRouteList(srv.Errors.Routes, sr, matcherSetsEnc, p, warnings) } } // add log associations // see https://github.com/caddyserver/caddy/issues/3310 sblockLogHosts := sblock.hostsFromKeys(true) for _, cval := range sblock.pile["custom_log"] { ncl := cval.Value.(namedCustomLog) if sblock.hasHostCatchAllKey() && len(ncl.hostnames) == 0 { // all requests for hosts not able to be listed should use // this log because it's a catch-all-hosts server block srv.Logs.DefaultLoggerName = ncl.name } else if len(ncl.hostnames) > 0 { // if the logger overrides the hostnames, map that to the logger name for _, h := range ncl.hostnames { if srv.Logs.LoggerNames == nil { srv.Logs.LoggerNames = make(map[string]string) } srv.Logs.LoggerNames[h] = ncl.name } } else { // otherwise, map each host to the logger name for _, h := range sblockLogHosts { if srv.Logs.LoggerNames == nil { srv.Logs.LoggerNames = make(map[string]string) } srv.Logs.LoggerNames[h] = ncl.name } } } if srv.Logs != nil && len(sblock.pile["custom_log"]) == 0 { // server has access logs enabled, but this server block does not // enable access logs; therefore, all hosts of this server block // should not be access-logged if len(hosts) == 0 { // if the server block has a catch-all-hosts key, then we should // not log reqs to any host unless it appears in the map srv.Logs.SkipUnmappedHosts = true } srv.Logs.SkipHosts = append(srv.Logs.SkipHosts, sblockLogHosts...) } } // a server cannot (natively) serve both HTTP and HTTPS at the // same time, so make sure the configuration isn't in conflict err := detectConflictingSchemes(srv, p.serverBlocks, options) if err != nil { return nil, err } // a catch-all TLS conn policy is necessary to ensure TLS can // be offered to all hostnames of the server; even though only // one policy is needed to enable TLS for the server, that // policy might apply to only certain TLS handshakes; but when // using the Caddyfile, user would expect all handshakes to at // least have a matching connection policy, so here we append a // catch-all/default policy if there isn't one already (it's // important that it goes at the end) - see issue #3004: // https://github.com/caddyserver/caddy/issues/3004 // TODO: maybe a smarter way to handle this might be to just make the // auto-HTTPS logic at provision-time detect if there is any connection // policy missing for any HTTPS-enabled hosts, if so, add it... maybe? if addressQualifiesForTLS && !hasCatchAllTLSConnPolicy && (len(srv.TLSConnPolicies) > 0 || !autoHTTPSWillAddConnPolicy || defaultSNI != "" || fallbackSNI != "") { srv.TLSConnPolicies = append(srv.TLSConnPolicies, &caddytls.ConnectionPolicy{DefaultSNI: defaultSNI, FallbackSNI: fallbackSNI}) } // tidy things up a bit srv.TLSConnPolicies, err = consolidateConnPolicies(srv.TLSConnPolicies) if err != nil { return nil, fmt.Errorf("consolidating TLS connection policies for server %d: %v", i, err) } srv.Routes = consolidateRoutes(srv.Routes) servers[fmt.Sprintf("srv%d", i)] = srv } err := applyServerOptions(servers, options, warnings) if err != nil { return nil, fmt.Errorf("applying global server options: %v", err) } return servers, nil } func detectConflictingSchemes(srv *caddyhttp.Server, serverBlocks []serverBlock, options map[string]any) error { httpPort := strconv.Itoa(caddyhttp.DefaultHTTPPort) if hp, ok := options["http_port"].(int); ok { httpPort = strconv.Itoa(hp) } httpsPort := strconv.Itoa(caddyhttp.DefaultHTTPSPort) if hsp, ok := options["https_port"].(int); ok { httpsPort = strconv.Itoa(hsp) } var httpOrHTTPS string checkAndSetHTTP := func(addr Address) error { if httpOrHTTPS == "HTTPS" { errMsg := fmt.Errorf("server listening on %v is configured for HTTPS and cannot natively multiplex HTTP and HTTPS: %s", srv.Listen, addr.Original) if addr.Scheme == "" && addr.Host == "" { errMsg = fmt.Errorf("%s (try specifying https:// in the address)", errMsg) } return errMsg } if len(srv.TLSConnPolicies) > 0 { // any connection policies created for an HTTP server // is a logical conflict, as it would enable HTTPS return fmt.Errorf("server listening on %v is HTTP, but attempts to configure TLS connection policies", srv.Listen) } httpOrHTTPS = "HTTP" return nil } checkAndSetHTTPS := func(addr Address) error { if httpOrHTTPS == "HTTP" { return fmt.Errorf("server listening on %v is configured for HTTP and cannot natively multiplex HTTP and HTTPS: %s", srv.Listen, addr.Original) } httpOrHTTPS = "HTTPS" return nil } for _, sblock := range serverBlocks { for _, addr := range sblock.keys { if addr.Scheme == "http" || addr.Port == httpPort { if err := checkAndSetHTTP(addr); err != nil { return err } } else if addr.Scheme == "https" || addr.Port == httpsPort || len(srv.TLSConnPolicies) > 0 { if err := checkAndSetHTTPS(addr); err != nil { return err } } else if addr.Host == "" { if err := checkAndSetHTTP(addr); err != nil { return err } } } } return nil } // consolidateConnPolicies sorts any catch-all policy to the end, removes empty TLS connection // policies, and combines equivalent ones for a cleaner overall output. func consolidateConnPolicies(cps caddytls.ConnectionPolicies) (caddytls.ConnectionPolicies, error) { // catch-all policies (those without any matcher) should be at the // end, otherwise it nullifies any more specific policies sort.SliceStable(cps, func(i, j int) bool { return cps[j].MatchersRaw == nil && cps[i].MatchersRaw != nil }) for i := 0; i < len(cps); i++ { // compare it to the others for j := 0; j < len(cps); j++ { if j == i { continue } // if they're exactly equal in every way, just keep one of them if reflect.DeepEqual(cps[i], cps[j]) { cps = append(cps[:j], cps[j+1:]...) i-- break } // if they have the same matcher, try to reconcile each field: either they must // be identical, or we have to be able to combine them safely if reflect.DeepEqual(cps[i].MatchersRaw, cps[j].MatchersRaw) { if len(cps[i].ALPN) > 0 && len(cps[j].ALPN) > 0 && !reflect.DeepEqual(cps[i].ALPN, cps[j].ALPN) { return nil, fmt.Errorf("two policies with same match criteria have conflicting ALPN: %v vs. %v", cps[i].ALPN, cps[j].ALPN) } if len(cps[i].CipherSuites) > 0 && len(cps[j].CipherSuites) > 0 && !reflect.DeepEqual(cps[i].CipherSuites, cps[j].CipherSuites) { return nil, fmt.Errorf("two policies with same match criteria have conflicting cipher suites: %v vs. %v", cps[i].CipherSuites, cps[j].CipherSuites) } if cps[i].ClientAuthentication == nil && cps[j].ClientAuthentication != nil && !reflect.DeepEqual(cps[i].ClientAuthentication, cps[j].ClientAuthentication) { return nil, fmt.Errorf("two policies with same match criteria have conflicting client auth configuration: %+v vs. %+v", cps[i].ClientAuthentication, cps[j].ClientAuthentication) } if len(cps[i].Curves) > 0 && len(cps[j].Curves) > 0 && !reflect.DeepEqual(cps[i].Curves, cps[j].Curves) { return nil, fmt.Errorf("two policies with same match criteria have conflicting curves: %v vs. %v", cps[i].Curves, cps[j].Curves) } if cps[i].DefaultSNI != "" && cps[j].DefaultSNI != "" && cps[i].DefaultSNI != cps[j].DefaultSNI { return nil, fmt.Errorf("two policies with same match criteria have conflicting default SNI: %s vs. %s", cps[i].DefaultSNI, cps[j].DefaultSNI) } if cps[i].ProtocolMin != "" && cps[j].ProtocolMin != "" && cps[i].ProtocolMin != cps[j].ProtocolMin { return nil, fmt.Errorf("two policies with same match criteria have conflicting min protocol: %s vs. %s", cps[i].ProtocolMin, cps[j].ProtocolMin) } if cps[i].ProtocolMax != "" && cps[j].ProtocolMax != "" && cps[i].ProtocolMax != cps[j].ProtocolMax { return nil, fmt.Errorf("two policies with same match criteria have conflicting max protocol: %s vs. %s", cps[i].ProtocolMax, cps[j].ProtocolMax) } if cps[i].CertSelection != nil && cps[j].CertSelection != nil { // merging fields other than AnyTag is not implemented if !reflect.DeepEqual(cps[i].CertSelection.SerialNumber, cps[j].CertSelection.SerialNumber) || !reflect.DeepEqual(cps[i].CertSelection.SubjectOrganization, cps[j].CertSelection.SubjectOrganization) || cps[i].CertSelection.PublicKeyAlgorithm != cps[j].CertSelection.PublicKeyAlgorithm || !reflect.DeepEqual(cps[i].CertSelection.AllTags, cps[j].CertSelection.AllTags) { return nil, fmt.Errorf("two policies with same match criteria have conflicting cert selections: %+v vs. %+v", cps[i].CertSelection, cps[j].CertSelection) } } // by now we've decided that we can merge the two -- we'll keep i and drop j if len(cps[i].ALPN) == 0 && len(cps[j].ALPN) > 0 { cps[i].ALPN = cps[j].ALPN } if len(cps[i].CipherSuites) == 0 && len(cps[j].CipherSuites) > 0 { cps[i].CipherSuites = cps[j].CipherSuites } if cps[i].ClientAuthentication == nil && cps[j].ClientAuthentication != nil { cps[i].ClientAuthentication = cps[j].ClientAuthentication } if len(cps[i].Curves) == 0 && len(cps[j].Curves) > 0 { cps[i].Curves = cps[j].Curves } if cps[i].DefaultSNI == "" && cps[j].DefaultSNI != "" { cps[i].DefaultSNI = cps[j].DefaultSNI } if cps[i].ProtocolMin == "" && cps[j].ProtocolMin != "" { cps[i].ProtocolMin = cps[j].ProtocolMin } if cps[i].ProtocolMax == "" && cps[j].ProtocolMax != "" { cps[i].ProtocolMax = cps[j].ProtocolMax } if cps[i].CertSelection == nil && cps[j].CertSelection != nil { // if j is the only one with a policy, move it over to i cps[i].CertSelection = cps[j].CertSelection } else if cps[i].CertSelection != nil && cps[j].CertSelection != nil { // if both have one, then combine AnyTag for _, tag := range cps[j].CertSelection.AnyTag { if !sliceContains(cps[i].CertSelection.AnyTag, tag) { cps[i].CertSelection.AnyTag = append(cps[i].CertSelection.AnyTag, tag) } } } cps = append(cps[:j], cps[j+1:]...) i-- break } } } return cps, nil } // appendSubrouteToRouteList appends the routes in subroute // to the routeList, optionally qualified by matchers. func appendSubrouteToRouteList(routeList caddyhttp.RouteList, subroute *caddyhttp.Subroute, matcherSetsEnc []caddy.ModuleMap, p sbAddrAssociation, warnings *[]caddyconfig.Warning, ) caddyhttp.RouteList { // nothing to do if... there's nothing to do if len(matcherSetsEnc) == 0 && len(subroute.Routes) == 0 && subroute.Errors == nil { return routeList } // No need to wrap the handlers in a subroute if this is the only server block // and there is no matcher for it (doing so would produce unnecessarily nested // JSON), *unless* there is a host matcher within this site block; if so, then // we still need to wrap in a subroute because otherwise the host matcher from // the inside of the site block would be a top-level host matcher, which is // subject to auto-HTTPS (cert management), and using a host matcher within // a site block is a valid, common pattern for excluding domains from cert // management, leading to unexpected behavior; see issue #5124. wrapInSubroute := true if len(matcherSetsEnc) == 0 && len(p.serverBlocks) == 1 { var hasHostMatcher bool outer: for _, route := range subroute.Routes { for _, ms := range route.MatcherSetsRaw { for matcherName := range ms { if matcherName == "host" { hasHostMatcher = true break outer } } } } wrapInSubroute = hasHostMatcher } if wrapInSubroute { route := caddyhttp.Route{ // the semantics of a site block in the Caddyfile dictate // that only the first matching one is evaluated, since // site blocks do not cascade nor inherit Terminal: true, } if len(matcherSetsEnc) > 0 { route.MatcherSetsRaw = matcherSetsEnc } if len(subroute.Routes) > 0 || subroute.Errors != nil { route.HandlersRaw = []json.RawMessage{ caddyconfig.JSONModuleObject(subroute, "handler", "subroute", warnings), } } if len(route.MatcherSetsRaw) > 0 || len(route.HandlersRaw) > 0 { routeList = append(routeList, route) } } else { routeList = append(routeList, subroute.Routes...) } return routeList } // buildSubroute turns the config values, which are expected to be routes // into a clean and orderly subroute that has all the routes within it. func buildSubroute(routes []ConfigValue, groupCounter counter, needsSorting bool) (*caddyhttp.Subroute, error) { if needsSorting { for _, val := range routes { if !directiveIsOrdered(val.directive) { return nil, fmt.Errorf("directive '%s' is not an ordered HTTP handler, so it cannot be used here - try placing within a route block or using the order global option", val.directive) } } sortRoutes(routes) } subroute := new(caddyhttp.Subroute) // some directives are mutually exclusive (only first matching // instance should be evaluated); this is done by putting their // routes in the same group mutuallyExclusiveDirs := map[string]*struct { count int groupName string }{ // as a special case, group rewrite directives so that they are mutually exclusive; // this means that only the first matching rewrite will be evaluated, and that's // probably a good thing, since there should never be a need to do more than one // rewrite (I think?), and cascading rewrites smell bad... imagine these rewrites: // rewrite /docs/json/* /docs/json/index.html // rewrite /docs/* /docs/index.html // (We use this on the Caddy website, or at least we did once.) The first rewrite's // result is also matched by the second rewrite, making the first rewrite pointless. // See issue #2959. "rewrite": {}, // handle blocks are also mutually exclusive by definition "handle": {}, // root just sets a variable, so if it was not mutually exclusive, intersecting // root directives would overwrite previously-matched ones; they should not cascade "root": {}, } // we need to deterministically loop over each of these directives // in order to keep the group numbers consistent keys := make([]string, 0, len(mutuallyExclusiveDirs)) for k := range mutuallyExclusiveDirs { keys = append(keys, k) } sort.Strings(keys) for _, meDir := range keys { info := mutuallyExclusiveDirs[meDir] // see how many instances of the directive there are for _, r := range routes { if r.directive == meDir { info.count++ if info.count > 1 { break } } } // if there is more than one, put them in a group // (special case: "rewrite" directive must always be in // its own group--even if there is only one--because we // do not want a rewrite to be consolidated into other // adjacent routes that happen to have the same matcher, // see caddyserver/caddy#3108 - because the implied // intent of rewrite is to do an internal redirect, // we can't assume that the request will continue to // match the same matcher; anyway, giving a route a // unique group name should keep it from consolidating) if info.count > 1 || meDir == "rewrite" { info.groupName = groupCounter.nextGroup() } } // add all the routes piled in from directives for _, r := range routes { // put this route into a group if it is mutually exclusive if info, ok := mutuallyExclusiveDirs[r.directive]; ok { route := r.Value.(caddyhttp.Route) route.Group = info.groupName r.Value = route } switch route := r.Value.(type) { case caddyhttp.Subroute: // if a route-class config value is actually a Subroute handler // with nothing but a list of routes, then it is the intention // of the directive to keep these handlers together and in this // same order, but not necessarily in a subroute (if it wanted // to keep them in a subroute, the directive would have returned // a route with a Subroute as its handler); this is useful to // keep multiple handlers/routes together and in the same order // so that the sorting procedure we did above doesn't reorder them if route.Errors != nil { // if error handlers are also set, this is confusing; it's // probably supposed to be wrapped in a Route and encoded // as a regular handler route... programmer error. panic("found subroute with more than just routes; perhaps it should have been wrapped in a route?") } subroute.Routes = append(subroute.Routes, route.Routes...) case caddyhttp.Route: subroute.Routes = append(subroute.Routes, route) } } subroute.Routes = consolidateRoutes(subroute.Routes) return subroute, nil } // normalizeDirectiveName ensures directives that should be sorted // at the same level are named the same before sorting happens. func normalizeDirectiveName(directive string) string { // As a special case, we want "handle_path" to be sorted // at the same level as "handle", so we force them to use // the same directive name after their parsing is complete. // See https://github.com/caddyserver/caddy/issues/3675#issuecomment-678042377 if directive == "handle_path" { directive = "handle" } return directive } // consolidateRoutes combines routes with the same properties // (same matchers, same Terminal and Group settings) for a // cleaner overall output. func consolidateRoutes(routes caddyhttp.RouteList) caddyhttp.RouteList { for i := 0; i < len(routes)-1; i++ { if reflect.DeepEqual(routes[i].MatcherSetsRaw, routes[i+1].MatcherSetsRaw) && routes[i].Terminal == routes[i+1].Terminal && routes[i].Group == routes[i+1].Group { // keep the handlers in the same order, then splice out repetitive route routes[i].HandlersRaw = append(routes[i].HandlersRaw, routes[i+1].HandlersRaw...) routes = append(routes[:i+1], routes[i+2:]...) i-- } } return routes } func matcherSetFromMatcherToken( tkn caddyfile.Token, matcherDefs map[string]caddy.ModuleMap, warnings *[]caddyconfig.Warning, ) (caddy.ModuleMap, bool, error) { // matcher tokens can be wildcards, simple path matchers, // or refer to a pre-defined matcher by some name if tkn.Text == "*" { // match all requests == no matchers, so nothing to do return nil, true, nil } else if strings.HasPrefix(tkn.Text, "/") { // convenient way to specify a single path match return caddy.ModuleMap{ "path": caddyconfig.JSON(caddyhttp.MatchPath{tkn.Text}, warnings), }, true, nil } else if strings.HasPrefix(tkn.Text, matcherPrefix) { // pre-defined matcher m, ok := matcherDefs[tkn.Text] if !ok { return nil, false, fmt.Errorf("unrecognized matcher name: %+v", tkn.Text) } return m, true, nil } return nil, false, nil } func (st *ServerType) compileEncodedMatcherSets(sblock serverBlock) ([]caddy.ModuleMap, error) { type hostPathPair struct { hostm caddyhttp.MatchHost pathm caddyhttp.MatchPath } // keep routes with common host and path matchers together var matcherPairs []*hostPathPair var catchAllHosts bool for _, addr := range sblock.keys { // choose a matcher pair that should be shared by this // server block; if none exists yet, create one var chosenMatcherPair *hostPathPair for _, mp := range matcherPairs { if (len(mp.pathm) == 0 && addr.Path == "") || (len(mp.pathm) == 1 && mp.pathm[0] == addr.Path) { chosenMatcherPair = mp break } } if chosenMatcherPair == nil { chosenMatcherPair = new(hostPathPair) if addr.Path != "" { chosenMatcherPair.pathm = []string{addr.Path} } matcherPairs = append(matcherPairs, chosenMatcherPair) } // if one of the keys has no host (i.e. is a catch-all for // any hostname), then we need to null out the host matcher // entirely so that it matches all hosts if addr.Host == "" && !catchAllHosts { chosenMatcherPair.hostm = nil catchAllHosts = true } if catchAllHosts { continue } // add this server block's keys to the matcher // pair if it doesn't already exist if addr.Host != "" { var found bool for _, h := range chosenMatcherPair.hostm { if h == addr.Host { found = true break } } if !found { chosenMatcherPair.hostm = append(chosenMatcherPair.hostm, addr.Host) } } } // iterate each pairing of host and path matchers and // put them into a map for JSON encoding var matcherSets []map[string]caddyhttp.RequestMatcher for _, mp := range matcherPairs { matcherSet := make(map[string]caddyhttp.RequestMatcher) if len(mp.hostm) > 0 { matcherSet["host"] = mp.hostm } if len(mp.pathm) > 0 { matcherSet["path"] = mp.pathm } if len(matcherSet) > 0 { matcherSets = append(matcherSets, matcherSet) } } // finally, encode each of the matcher sets matcherSetsEnc := make([]caddy.ModuleMap, 0, len(matcherSets)) for _, ms := range matcherSets { msEncoded, err := encodeMatcherSet(ms) if err != nil { return nil, fmt.Errorf("server block %v: %v", sblock.block.Keys, err) } matcherSetsEnc = append(matcherSetsEnc, msEncoded) } return matcherSetsEnc, nil } func parseMatcherDefinitions(d *caddyfile.Dispenser, matchers map[string]caddy.ModuleMap) error { for d.Next() { // this is the "name" for "named matchers" definitionName := d.Val() if _, ok := matchers[definitionName]; ok { return fmt.Errorf("matcher is defined more than once: %s", definitionName) } matchers[definitionName] = make(caddy.ModuleMap) // given a matcher name and the tokens following it, parse // the tokens as a matcher module and record it makeMatcher := func(matcherName string, tokens []caddyfile.Token) error { mod, err := caddy.GetModule("http.matchers." + matcherName) if err != nil { return fmt.Errorf("getting matcher module '%s': %v", matcherName, err) } unm, ok := mod.New().(caddyfile.Unmarshaler) if !ok { return fmt.Errorf("matcher module '%s' is not a Caddyfile unmarshaler", matcherName) } err = unm.UnmarshalCaddyfile(caddyfile.NewDispenser(tokens)) if err != nil { return err } rm, ok := unm.(caddyhttp.RequestMatcher) if !ok { return fmt.Errorf("matcher module '%s' is not a request matcher", matcherName) } matchers[definitionName][matcherName] = caddyconfig.JSON(rm, nil) return nil } // if the next token is quoted, we can assume it's not a matcher name // and that it's probably an 'expression' matcher if d.NextArg() { if d.Token().Quoted() { err := makeMatcher("expression", []caddyfile.Token{d.Token()}) if err != nil { return err } continue } // if it wasn't quoted, then we need to rewind after calling // d.NextArg() so the below properly grabs the matcher name d.Prev() } // in case there are multiple instances of the same matcher, concatenate // their tokens (we expect that UnmarshalCaddyfile should be able to // handle more than one segment); otherwise, we'd overwrite other // instances of the matcher in this set tokensByMatcherName := make(map[string][]caddyfile.Token) for nesting := d.Nesting(); d.NextArg() || d.NextBlock(nesting); { matcherName := d.Val() tokensByMatcherName[matcherName] = append(tokensByMatcherName[matcherName], d.NextSegment()...) } for matcherName, tokens := range tokensByMatcherName { err := makeMatcher(matcherName, tokens) if err != nil { return err } } } return nil } func encodeMatcherSet(matchers map[string]caddyhttp.RequestMatcher) (caddy.ModuleMap, error) { msEncoded := make(caddy.ModuleMap) for matcherName, val := range matchers { jsonBytes, err := json.Marshal(val) if err != nil { return nil, fmt.Errorf("marshaling matcher set %#v: %v", matchers, err) } msEncoded[matcherName] = jsonBytes } return msEncoded, nil } // placeholderShorthands returns a slice of old-new string pairs, // where the left of the pair is a placeholder shorthand that may // be used in the Caddyfile, and the right is the replacement. func placeholderShorthands() []string { return []string{ "{dir}", "{http.request.uri.path.dir}", "{file}", "{http.request.uri.path.file}", "{host}", "{http.request.host}", "{hostport}", "{http.request.hostport}", "{port}", "{http.request.port}", "{method}", "{http.request.method}", "{path}", "{http.request.uri.path}", "{query}", "{http.request.uri.query}", "{remote}", "{http.request.remote}", "{remote_host}", "{http.request.remote.host}", "{remote_port}", "{http.request.remote.port}", "{scheme}", "{http.request.scheme}", "{uri}", "{http.request.uri}", "{tls_cipher}", "{http.request.tls.cipher_suite}", "{tls_version}", "{http.request.tls.version}", "{tls_client_fingerprint}", "{http.request.tls.client.fingerprint}", "{tls_client_issuer}", "{http.request.tls.client.issuer}", "{tls_client_serial}", "{http.request.tls.client.serial}", "{tls_client_subject}", "{http.request.tls.client.subject}", "{tls_client_certificate_pem}", "{http.request.tls.client.certificate_pem}", "{tls_client_certificate_der_base64}", "{http.request.tls.client.certificate_der_base64}", "{upstream_hostport}", "{http.reverse_proxy.upstream.hostport}", "{client_ip}", "{http.vars.client_ip}", } } // WasReplacedPlaceholderShorthand checks if a token string was // likely a replaced shorthand of the known Caddyfile placeholder // replacement outputs. Useful to prevent some user-defined map // output destinations from overlapping with one of the // predefined shorthands. func WasReplacedPlaceholderShorthand(token string) string { prev := "" for i, item := range placeholderShorthands() { // only look at every 2nd item, which is the replacement if i%2 == 0 { prev = item continue } if strings.Trim(token, "{}") == strings.Trim(item, "{}") { // we return the original shorthand so it // can be used for an error message return prev } } return "" } // tryInt tries to convert val to an integer. If it fails, // it downgrades the error to a warning and returns 0. func tryInt(val any, warnings *[]caddyconfig.Warning) int { intVal, ok := val.(int) if val != nil && !ok && warnings != nil { *warnings = append(*warnings, caddyconfig.Warning{Message: "not an integer type"}) } return intVal } func tryString(val any, warnings *[]caddyconfig.Warning) string { stringVal, ok := val.(string) if val != nil && !ok && warnings != nil { *warnings = append(*warnings, caddyconfig.Warning{Message: "not a string type"}) } return stringVal } func tryDuration(val any, warnings *[]caddyconfig.Warning) caddy.Duration { durationVal, ok := val.(caddy.Duration) if val != nil && !ok && warnings != nil { *warnings = append(*warnings, caddyconfig.Warning{Message: "not a duration type"}) } return durationVal } // sliceContains returns true if needle is in haystack. func sliceContains(haystack []string, needle string) bool { for _, s := range haystack { if s == needle { return true } } return false } // listenersUseAnyPortOtherThan returns true if there are any // listeners in addresses that use a port which is not otherPort. // Mostly borrowed from unexported method in caddyhttp package. func listenersUseAnyPortOtherThan(addresses []string, otherPort string) bool { otherPortInt, err := strconv.Atoi(otherPort) if err != nil { return false } for _, lnAddr := range addresses { laddrs, err := caddy.ParseNetworkAddress(lnAddr) if err != nil { continue } if uint(otherPortInt) > laddrs.EndPort || uint(otherPortInt) < laddrs.StartPort { return true } } return false } // specificity returns len(s) minus any wildcards (*) and // placeholders ({...}). Basically, it's a length count // that penalizes the use of wildcards and placeholders. // This is useful for comparing hostnames and paths. // However, wildcards in paths are not a sure answer to // the question of specificity. For example, // '*.example.com' is clearly less specific than // 'a.example.com', but is '/a' more or less specific // than '/a*'? func specificity(s string) int { l := len(s) - strings.Count(s, "*") for len(s) > 0 { start := strings.Index(s, "{") if start < 0 { return l } end := strings.Index(s[start:], "}") + start + 1 if end <= start { return l } l -= end - start s = s[end:] } return l } type counter struct { n *int } func (c counter) nextGroup() string { name := fmt.Sprintf("group%d", *c.n) *c.n++ return name } type namedCustomLog struct { name string hostnames []string log *caddy.CustomLog } // sbAddrAssociation is a mapping from a list of // addresses to a list of server blocks that are // served on those addresses. type sbAddrAssociation struct { addresses []string serverBlocks []serverBlock } const ( matcherPrefix = "@" namedRouteKey = "named_route" ) // Interface guard var _ caddyfile.ServerType = (*ServerType)(nil)
Go
caddy/caddyconfig/httpcaddyfile/httptype_test.go
package httpcaddyfile import ( "testing" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func TestMatcherSyntax(t *testing.T) { for i, tc := range []struct { input string expectError bool }{ { input: `http://localhost @debug { query showdebug=1 } `, expectError: false, }, { input: `http://localhost @debug { query bad format } `, expectError: true, }, { input: `http://localhost @debug { not { path /somepath* } } `, expectError: false, }, { input: `http://localhost @debug { not path /somepath* } `, expectError: false, }, { input: `http://localhost @debug not path /somepath* `, expectError: false, }, { input: `@matcher { path /matcher-not-allowed/outside-of-site-block/* } http://localhost `, expectError: true, }, } { adapter := caddyfile.Adapter{ ServerType: ServerType{}, } _, _, err := adapter.Adapt([]byte(tc.input), nil) if err != nil != tc.expectError { t.Errorf("Test %d error expectation failed Expected: %v, got %s", i, tc.expectError, err) continue } } } func TestSpecificity(t *testing.T) { for i, tc := range []struct { input string expect int }{ {"", 0}, {"*", 0}, {"*.*", 1}, {"{placeholder}", 0}, {"/{placeholder}", 1}, {"foo", 3}, {"example.com", 11}, {"a.example.com", 13}, {"*.example.com", 12}, {"/foo", 4}, {"/foo*", 4}, {"{placeholder}.example.com", 12}, {"{placeholder.example.com", 24}, {"}.", 2}, {"}{", 2}, {"{}", 0}, {"{{{}}", 1}, } { actual := specificity(tc.input) if actual != tc.expect { t.Errorf("Test %d (%s): Expected %d but got %d", i, tc.input, tc.expect, actual) } } } func TestGlobalOptions(t *testing.T) { for i, tc := range []struct { input string expectError bool }{ { input: ` { email test@example.com } :80 `, expectError: false, }, { input: ` { admin off } :80 `, expectError: false, }, { input: ` { admin 127.0.0.1:2020 } :80 `, expectError: false, }, { input: ` { admin { disabled false } } :80 `, expectError: true, }, { input: ` { admin { enforce_origin origins 192.168.1.1:2020 127.0.0.1:2020 } } :80 `, expectError: false, }, { input: ` { admin 127.0.0.1:2020 { enforce_origin origins 192.168.1.1:2020 127.0.0.1:2020 } } :80 `, expectError: false, }, { input: ` { admin 192.168.1.1:2020 127.0.0.1:2020 { enforce_origin origins 192.168.1.1:2020 127.0.0.1:2020 } } :80 `, expectError: true, }, { input: ` { admin off { enforce_origin origins 192.168.1.1:2020 127.0.0.1:2020 } } :80 `, expectError: true, }, } { adapter := caddyfile.Adapter{ ServerType: ServerType{}, } _, _, err := adapter.Adapt([]byte(tc.input), nil) if err != nil != tc.expectError { t.Errorf("Test %d error expectation failed Expected: %v, got %s", i, tc.expectError, err) continue } } }
Go
caddy/caddyconfig/httpcaddyfile/options.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 httpcaddyfile import ( "strconv" "github.com/caddyserver/certmagic" "github.com/mholt/acmez/acme" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/modules/caddytls" ) func init() { RegisterGlobalOption("debug", parseOptTrue) RegisterGlobalOption("http_port", parseOptHTTPPort) RegisterGlobalOption("https_port", parseOptHTTPSPort) RegisterGlobalOption("default_bind", parseOptStringList) RegisterGlobalOption("grace_period", parseOptDuration) RegisterGlobalOption("shutdown_delay", parseOptDuration) RegisterGlobalOption("default_sni", parseOptSingleString) RegisterGlobalOption("fallback_sni", parseOptSingleString) RegisterGlobalOption("order", parseOptOrder) RegisterGlobalOption("storage", parseOptStorage) RegisterGlobalOption("storage_clean_interval", parseOptDuration) RegisterGlobalOption("renew_interval", parseOptDuration) RegisterGlobalOption("ocsp_interval", parseOptDuration) RegisterGlobalOption("acme_ca", parseOptSingleString) RegisterGlobalOption("acme_ca_root", parseOptSingleString) RegisterGlobalOption("acme_dns", parseOptACMEDNS) RegisterGlobalOption("acme_eab", parseOptACMEEAB) RegisterGlobalOption("cert_issuer", parseOptCertIssuer) RegisterGlobalOption("skip_install_trust", parseOptTrue) RegisterGlobalOption("email", parseOptSingleString) RegisterGlobalOption("admin", parseOptAdmin) RegisterGlobalOption("on_demand_tls", parseOptOnDemand) RegisterGlobalOption("local_certs", parseOptTrue) RegisterGlobalOption("key_type", parseOptSingleString) RegisterGlobalOption("auto_https", parseOptAutoHTTPS) RegisterGlobalOption("servers", parseServerOptions) RegisterGlobalOption("ocsp_stapling", parseOCSPStaplingOptions) RegisterGlobalOption("log", parseLogOptions) RegisterGlobalOption("preferred_chains", parseOptPreferredChains) RegisterGlobalOption("persist_config", parseOptPersistConfig) } func parseOptTrue(d *caddyfile.Dispenser, _ any) (any, error) { return true, nil } func parseOptHTTPPort(d *caddyfile.Dispenser, _ any) (any, error) { var httpPort int for d.Next() { var httpPortStr string if !d.AllArgs(&httpPortStr) { return 0, d.ArgErr() } var err error httpPort, err = strconv.Atoi(httpPortStr) if err != nil { return 0, d.Errf("converting port '%s' to integer value: %v", httpPortStr, err) } } return httpPort, nil } func parseOptHTTPSPort(d *caddyfile.Dispenser, _ any) (any, error) { var httpsPort int for d.Next() { var httpsPortStr string if !d.AllArgs(&httpsPortStr) { return 0, d.ArgErr() } var err error httpsPort, err = strconv.Atoi(httpsPortStr) if err != nil { return 0, d.Errf("converting port '%s' to integer value: %v", httpsPortStr, err) } } return httpsPort, nil } func parseOptOrder(d *caddyfile.Dispenser, _ any) (any, error) { newOrder := directiveOrder for d.Next() { // get directive name if !d.Next() { return nil, d.ArgErr() } dirName := d.Val() if _, ok := registeredDirectives[dirName]; !ok { return nil, d.Errf("%s is not a registered directive", dirName) } // get positional token if !d.Next() { return nil, d.ArgErr() } pos := d.Val() // if directive exists, first remove it for i, d := range newOrder { if d == dirName { newOrder = append(newOrder[:i], newOrder[i+1:]...) break } } // act on the positional switch pos { case "first": newOrder = append([]string{dirName}, newOrder...) if d.NextArg() { return nil, d.ArgErr() } directiveOrder = newOrder return newOrder, nil case "last": newOrder = append(newOrder, dirName) if d.NextArg() { return nil, d.ArgErr() } directiveOrder = newOrder return newOrder, nil case "before": case "after": default: return nil, d.Errf("unknown positional '%s'", pos) } // get name of other directive if !d.NextArg() { return nil, d.ArgErr() } otherDir := d.Val() if d.NextArg() { return nil, d.ArgErr() } // insert directive into proper position for i, d := range newOrder { if d == otherDir { if pos == "before" { newOrder = append(newOrder[:i], append([]string{dirName}, newOrder[i:]...)...) } else if pos == "after" { newOrder = append(newOrder[:i+1], append([]string{dirName}, newOrder[i+1:]...)...) } break } } } directiveOrder = newOrder return newOrder, nil } func parseOptStorage(d *caddyfile.Dispenser, _ any) (any, error) { if !d.Next() { // consume option name return nil, d.ArgErr() } if !d.Next() { // get storage module name return nil, d.ArgErr() } modID := "caddy.storage." + d.Val() unm, err := caddyfile.UnmarshalModule(d, modID) if err != nil { return nil, err } storage, ok := unm.(caddy.StorageConverter) if !ok { return nil, d.Errf("module %s is not a caddy.StorageConverter", modID) } return storage, nil } func parseOptDuration(d *caddyfile.Dispenser, _ any) (any, error) { if !d.Next() { // consume option name return nil, d.ArgErr() } if !d.Next() { // get duration value return nil, d.ArgErr() } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return nil, err } return caddy.Duration(dur), nil } func parseOptACMEDNS(d *caddyfile.Dispenser, _ any) (any, error) { if !d.Next() { // consume option name return nil, d.ArgErr() } if !d.Next() { // get DNS module name return nil, d.ArgErr() } modID := "dns.providers." + d.Val() unm, err := caddyfile.UnmarshalModule(d, modID) if err != nil { return nil, err } prov, ok := unm.(certmagic.ACMEDNSProvider) if !ok { return nil, d.Errf("module %s (%T) is not a certmagic.ACMEDNSProvider", modID, unm) } return prov, nil } func parseOptACMEEAB(d *caddyfile.Dispenser, _ any) (any, error) { eab := new(acme.EAB) for d.Next() { if d.NextArg() { return nil, d.ArgErr() } for nesting := d.Nesting(); d.NextBlock(nesting); { switch d.Val() { case "key_id": if !d.NextArg() { return nil, d.ArgErr() } eab.KeyID = d.Val() case "mac_key": if !d.NextArg() { return nil, d.ArgErr() } eab.MACKey = d.Val() default: return nil, d.Errf("unrecognized parameter '%s'", d.Val()) } } } return eab, nil } func parseOptCertIssuer(d *caddyfile.Dispenser, existing any) (any, error) { var issuers []certmagic.Issuer if existing != nil { issuers = existing.([]certmagic.Issuer) } for d.Next() { // consume option name if !d.Next() { // get issuer module name return nil, d.ArgErr() } modID := "tls.issuance." + d.Val() unm, err := caddyfile.UnmarshalModule(d, modID) if err != nil { return nil, err } iss, ok := unm.(certmagic.Issuer) if !ok { return nil, d.Errf("module %s (%T) is not a certmagic.Issuer", modID, unm) } issuers = append(issuers, iss) } return issuers, nil } func parseOptSingleString(d *caddyfile.Dispenser, _ any) (any, error) { d.Next() // consume parameter name if !d.Next() { return "", d.ArgErr() } val := d.Val() if d.Next() { return "", d.ArgErr() } return val, nil } func parseOptStringList(d *caddyfile.Dispenser, _ any) (any, error) { d.Next() // consume parameter name val := d.RemainingArgs() if len(val) == 0 { return "", d.ArgErr() } return val, nil } func parseOptAdmin(d *caddyfile.Dispenser, _ any) (any, error) { adminCfg := new(caddy.AdminConfig) for d.Next() { if d.NextArg() { listenAddress := d.Val() if listenAddress == "off" { adminCfg.Disabled = true if d.Next() { // Do not accept any remaining options including block return nil, d.Err("No more option is allowed after turning off admin config") } } else { adminCfg.Listen = listenAddress if d.NextArg() { // At most 1 arg is allowed return nil, d.ArgErr() } } } for nesting := d.Nesting(); d.NextBlock(nesting); { switch d.Val() { case "enforce_origin": adminCfg.EnforceOrigin = true case "origins": adminCfg.Origins = d.RemainingArgs() default: return nil, d.Errf("unrecognized parameter '%s'", d.Val()) } } } if adminCfg.Listen == "" && !adminCfg.Disabled { adminCfg.Listen = caddy.DefaultAdminListen } return adminCfg, nil } func parseOptOnDemand(d *caddyfile.Dispenser, _ any) (any, error) { var ond *caddytls.OnDemandConfig for d.Next() { if d.NextArg() { return nil, d.ArgErr() } for nesting := d.Nesting(); d.NextBlock(nesting); { switch d.Val() { case "ask": if !d.NextArg() { return nil, d.ArgErr() } if ond == nil { ond = new(caddytls.OnDemandConfig) } ond.Ask = d.Val() case "interval": if !d.NextArg() { return nil, d.ArgErr() } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return nil, err } if ond == nil { ond = new(caddytls.OnDemandConfig) } if ond.RateLimit == nil { ond.RateLimit = new(caddytls.RateLimit) } ond.RateLimit.Interval = caddy.Duration(dur) case "burst": if !d.NextArg() { return nil, d.ArgErr() } burst, err := strconv.Atoi(d.Val()) if err != nil { return nil, err } if ond == nil { ond = new(caddytls.OnDemandConfig) } if ond.RateLimit == nil { ond.RateLimit = new(caddytls.RateLimit) } ond.RateLimit.Burst = burst default: return nil, d.Errf("unrecognized parameter '%s'", d.Val()) } } } if ond == nil { return nil, d.Err("expected at least one config parameter for on_demand_tls") } return ond, nil } func parseOptPersistConfig(d *caddyfile.Dispenser, _ any) (any, error) { d.Next() // consume parameter name if !d.Next() { return "", d.ArgErr() } val := d.Val() if d.Next() { return "", d.ArgErr() } if val != "off" { return "", d.Errf("persist_config must be 'off'") } return val, nil } func parseOptAutoHTTPS(d *caddyfile.Dispenser, _ any) (any, error) { d.Next() // consume parameter name if !d.Next() { return "", d.ArgErr() } val := d.Val() if d.Next() { return "", d.ArgErr() } if val != "off" && val != "disable_redirects" && val != "disable_certs" && val != "ignore_loaded_certs" { return "", d.Errf("auto_https must be one of 'off', 'disable_redirects', 'disable_certs', or 'ignore_loaded_certs'") } return val, nil } func parseServerOptions(d *caddyfile.Dispenser, _ any) (any, error) { return unmarshalCaddyfileServerOptions(d) } func parseOCSPStaplingOptions(d *caddyfile.Dispenser, _ any) (any, error) { d.Next() // consume option name var val string if !d.AllArgs(&val) { return nil, d.ArgErr() } if val != "off" { return nil, d.Errf("invalid argument '%s'", val) } return certmagic.OCSPConfig{ DisableStapling: val == "off", }, nil } // parseLogOptions parses the global log option. Syntax: // // log [name] { // output <writer_module> ... // format <encoder_module> ... // level <level> // include <namespaces...> // exclude <namespaces...> // } // // When the name argument is unspecified, this directive modifies the default // logger. func parseLogOptions(d *caddyfile.Dispenser, existingVal any) (any, error) { currentNames := make(map[string]struct{}) if existingVal != nil { innerVals, ok := existingVal.([]ConfigValue) if !ok { return nil, d.Errf("existing log values of unexpected type: %T", existingVal) } for _, rawVal := range innerVals { val, ok := rawVal.Value.(namedCustomLog) if !ok { return nil, d.Errf("existing log value of unexpected type: %T", existingVal) } currentNames[val.name] = struct{}{} } } var warnings []caddyconfig.Warning // Call out the same parser that handles server-specific log configuration. configValues, err := parseLogHelper( Helper{ Dispenser: d, warnings: &warnings, }, currentNames, ) if err != nil { return nil, err } if len(warnings) > 0 { return nil, d.Errf("warnings found in parsing global log options: %+v", warnings) } return configValues, nil } func parseOptPreferredChains(d *caddyfile.Dispenser, _ any) (any, error) { d.Next() return caddytls.ParseCaddyfilePreferredChainsOptions(d) }
Go
caddy/caddyconfig/httpcaddyfile/options_test.go
package httpcaddyfile import ( "testing" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" _ "github.com/caddyserver/caddy/v2/modules/logging" ) func TestGlobalLogOptionSyntax(t *testing.T) { for i, tc := range []struct { input string output string expectError bool }{ // NOTE: Additional test cases of successful Caddyfile parsing // are present in: caddytest/integration/caddyfile_adapt/ { input: `{ log default } `, output: `{}`, expectError: false, }, { input: `{ log example { output file foo.log } log example { format json } } `, expectError: true, }, { input: `{ log example /foo { output file foo.log } } `, expectError: true, }, } { adapter := caddyfile.Adapter{ ServerType: ServerType{}, } out, _, err := adapter.Adapt([]byte(tc.input), nil) if err != nil != tc.expectError { t.Errorf("Test %d error expectation failed Expected: %v, got %v", i, tc.expectError, err) continue } if string(out) != tc.output { t.Errorf("Test %d error output mismatch Expected: %s, got %s", i, tc.output, out) } } }
Go
caddy/caddyconfig/httpcaddyfile/pkiapp.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 httpcaddyfile import ( "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/modules/caddypki" ) func init() { RegisterGlobalOption("pki", parsePKIApp) } // parsePKIApp parses the global log option. Syntax: // // pki { // ca [<id>] { // name <name> // root_cn <name> // intermediate_cn <name> // intermediate_lifetime <duration> // root { // cert <path> // key <path> // format <format> // } // intermediate { // cert <path> // key <path> // format <format> // } // } // } // // When the CA ID is unspecified, 'local' is assumed. func parsePKIApp(d *caddyfile.Dispenser, existingVal any) (any, error) { pki := &caddypki.PKI{CAs: make(map[string]*caddypki.CA)} for d.Next() { for nesting := d.Nesting(); d.NextBlock(nesting); { switch d.Val() { case "ca": pkiCa := new(caddypki.CA) if d.NextArg() { pkiCa.ID = d.Val() if d.NextArg() { return nil, d.ArgErr() } } if pkiCa.ID == "" { pkiCa.ID = caddypki.DefaultCAID } for nesting := d.Nesting(); d.NextBlock(nesting); { switch d.Val() { case "name": if !d.NextArg() { return nil, d.ArgErr() } pkiCa.Name = d.Val() case "root_cn": if !d.NextArg() { return nil, d.ArgErr() } pkiCa.RootCommonName = d.Val() case "intermediate_cn": if !d.NextArg() { return nil, d.ArgErr() } pkiCa.IntermediateCommonName = d.Val() case "intermediate_lifetime": if !d.NextArg() { return nil, d.ArgErr() } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return nil, err } pkiCa.IntermediateLifetime = caddy.Duration(dur) case "root": if pkiCa.Root == nil { pkiCa.Root = new(caddypki.KeyPair) } for nesting := d.Nesting(); d.NextBlock(nesting); { switch d.Val() { case "cert": if !d.NextArg() { return nil, d.ArgErr() } pkiCa.Root.Certificate = d.Val() case "key": if !d.NextArg() { return nil, d.ArgErr() } pkiCa.Root.PrivateKey = d.Val() case "format": if !d.NextArg() { return nil, d.ArgErr() } pkiCa.Root.Format = d.Val() default: return nil, d.Errf("unrecognized pki ca root option '%s'", d.Val()) } } case "intermediate": if pkiCa.Intermediate == nil { pkiCa.Intermediate = new(caddypki.KeyPair) } for nesting := d.Nesting(); d.NextBlock(nesting); { switch d.Val() { case "cert": if !d.NextArg() { return nil, d.ArgErr() } pkiCa.Intermediate.Certificate = d.Val() case "key": if !d.NextArg() { return nil, d.ArgErr() } pkiCa.Intermediate.PrivateKey = d.Val() case "format": if !d.NextArg() { return nil, d.ArgErr() } pkiCa.Intermediate.Format = d.Val() default: return nil, d.Errf("unrecognized pki ca intermediate option '%s'", d.Val()) } } default: return nil, d.Errf("unrecognized pki ca option '%s'", d.Val()) } } pki.CAs[pkiCa.ID] = pkiCa default: return nil, d.Errf("unrecognized pki option '%s'", d.Val()) } } } return pki, nil } func (st ServerType) buildPKIApp( pairings []sbAddrAssociation, options map[string]any, warnings []caddyconfig.Warning, ) (*caddypki.PKI, []caddyconfig.Warning, error) { skipInstallTrust := false if _, ok := options["skip_install_trust"]; ok { skipInstallTrust = true } falseBool := false // Load the PKI app configured via global options var pkiApp *caddypki.PKI unwrappedPki, ok := options["pki"].(*caddypki.PKI) if ok { pkiApp = unwrappedPki } else { pkiApp = &caddypki.PKI{CAs: make(map[string]*caddypki.CA)} } for _, ca := range pkiApp.CAs { if skipInstallTrust { ca.InstallTrust = &falseBool } pkiApp.CAs[ca.ID] = ca } // Add in the CAs configured via directives for _, p := range pairings { for _, sblock := range p.serverBlocks { // find all the CAs that were defined and add them to the app config // i.e. from any "acme_server" directives for _, caCfgValue := range sblock.pile["pki.ca"] { ca := caCfgValue.Value.(*caddypki.CA) if skipInstallTrust { ca.InstallTrust = &falseBool } // the CA might already exist from global options, so // don't overwrite it in that case if _, ok := pkiApp.CAs[ca.ID]; !ok { pkiApp.CAs[ca.ID] = ca } } } } // if there was no CAs defined in any of the servers, // and we were requested to not install trust, then // add one for the default/local CA to do so if len(pkiApp.CAs) == 0 && skipInstallTrust { ca := new(caddypki.CA) ca.ID = caddypki.DefaultCAID ca.InstallTrust = &falseBool pkiApp.CAs[ca.ID] = ca } return pkiApp, warnings, nil }
Go
caddy/caddyconfig/httpcaddyfile/serveroptions.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 httpcaddyfile import ( "encoding/json" "fmt" "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/modules/caddyhttp" ) // serverOptions collects server config overrides parsed from Caddyfile global options type serverOptions struct { // If set, will only apply these options to servers that contain a // listener address that matches exactly. If empty, will apply to all // servers that were not already matched by another serverOptions. ListenerAddress string // These will all map 1:1 to the caddyhttp.Server struct Name string ListenerWrappersRaw []json.RawMessage ReadTimeout caddy.Duration ReadHeaderTimeout caddy.Duration WriteTimeout caddy.Duration IdleTimeout caddy.Duration KeepAliveInterval caddy.Duration MaxHeaderBytes int EnableFullDuplex bool Protocols []string StrictSNIHost *bool TrustedProxiesRaw json.RawMessage ClientIPHeaders []string ShouldLogCredentials bool Metrics *caddyhttp.Metrics } func unmarshalCaddyfileServerOptions(d *caddyfile.Dispenser) (any, error) { serverOpts := serverOptions{} for d.Next() { if d.NextArg() { serverOpts.ListenerAddress = d.Val() if d.NextArg() { return nil, d.ArgErr() } } for nesting := d.Nesting(); d.NextBlock(nesting); { switch d.Val() { case "name": if serverOpts.ListenerAddress == "" { return nil, d.Errf("cannot set a name for a server without a listener address") } if !d.NextArg() { return nil, d.ArgErr() } serverOpts.Name = d.Val() case "listener_wrappers": for nesting := d.Nesting(); d.NextBlock(nesting); { modID := "caddy.listeners." + d.Val() unm, err := caddyfile.UnmarshalModule(d, modID) if err != nil { return nil, err } listenerWrapper, ok := unm.(caddy.ListenerWrapper) if !ok { return nil, fmt.Errorf("module %s (%T) is not a listener wrapper", modID, unm) } jsonListenerWrapper := caddyconfig.JSONModuleObject( listenerWrapper, "wrapper", listenerWrapper.(caddy.Module).CaddyModule().ID.Name(), nil, ) serverOpts.ListenerWrappersRaw = append(serverOpts.ListenerWrappersRaw, jsonListenerWrapper) } case "timeouts": for nesting := d.Nesting(); d.NextBlock(nesting); { switch d.Val() { case "read_body": if !d.NextArg() { return nil, d.ArgErr() } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return nil, d.Errf("parsing read_body timeout duration: %v", err) } serverOpts.ReadTimeout = caddy.Duration(dur) case "read_header": if !d.NextArg() { return nil, d.ArgErr() } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return nil, d.Errf("parsing read_header timeout duration: %v", err) } serverOpts.ReadHeaderTimeout = caddy.Duration(dur) case "write": if !d.NextArg() { return nil, d.ArgErr() } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return nil, d.Errf("parsing write timeout duration: %v", err) } serverOpts.WriteTimeout = caddy.Duration(dur) case "idle": if !d.NextArg() { return nil, d.ArgErr() } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return nil, d.Errf("parsing idle timeout duration: %v", err) } serverOpts.IdleTimeout = caddy.Duration(dur) default: return nil, d.Errf("unrecognized timeouts option '%s'", d.Val()) } } case "keepalive_interval": if !d.NextArg() { return nil, d.ArgErr() } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return nil, d.Errf("parsing keepalive interval duration: %v", err) } serverOpts.KeepAliveInterval = caddy.Duration(dur) case "max_header_size": var sizeStr string if !d.AllArgs(&sizeStr) { return nil, d.ArgErr() } size, err := humanize.ParseBytes(sizeStr) if err != nil { return nil, d.Errf("parsing max_header_size: %v", err) } serverOpts.MaxHeaderBytes = int(size) case "enable_full_duplex": if d.NextArg() { return nil, d.ArgErr() } serverOpts.EnableFullDuplex = true case "log_credentials": if d.NextArg() { return nil, d.ArgErr() } serverOpts.ShouldLogCredentials = true case "protocols": protos := d.RemainingArgs() for _, proto := range protos { if proto != "h1" && proto != "h2" && proto != "h2c" && proto != "h3" { return nil, d.Errf("unknown protocol '%s': expected h1, h2, h2c, or h3", proto) } if sliceContains(serverOpts.Protocols, proto) { return nil, d.Errf("protocol %s specified more than once", proto) } serverOpts.Protocols = append(serverOpts.Protocols, proto) } if nesting := d.Nesting(); d.NextBlock(nesting) { return nil, d.ArgErr() } case "strict_sni_host": if d.NextArg() && d.Val() != "insecure_off" && d.Val() != "on" { return nil, d.Errf("strict_sni_host only supports 'on' or 'insecure_off', got '%s'", d.Val()) } boolVal := true if d.Val() == "insecure_off" { boolVal = false } serverOpts.StrictSNIHost = &boolVal case "trusted_proxies": if !d.NextArg() { return nil, d.Err("trusted_proxies expects an IP range source module name as its first argument") } modID := "http.ip_sources." + d.Val() unm, err := caddyfile.UnmarshalModule(d, modID) if err != nil { return nil, err } source, ok := unm.(caddyhttp.IPRangeSource) if !ok { return nil, fmt.Errorf("module %s (%T) is not an IP range source", modID, unm) } jsonSource := caddyconfig.JSONModuleObject( source, "source", source.(caddy.Module).CaddyModule().ID.Name(), nil, ) serverOpts.TrustedProxiesRaw = jsonSource case "client_ip_headers": headers := d.RemainingArgs() for _, header := range headers { if sliceContains(serverOpts.ClientIPHeaders, header) { return nil, d.Errf("client IP header %s specified more than once", header) } serverOpts.ClientIPHeaders = append(serverOpts.ClientIPHeaders, header) } if nesting := d.Nesting(); d.NextBlock(nesting) { return nil, d.ArgErr() } case "metrics": if d.NextArg() { return nil, d.ArgErr() } if nesting := d.Nesting(); d.NextBlock(nesting) { return nil, d.ArgErr() } serverOpts.Metrics = new(caddyhttp.Metrics) // TODO: DEPRECATED. (August 2022) case "protocol": caddy.Log().Named("caddyfile").Warn("DEPRECATED: protocol sub-option will be removed soon") for nesting := d.Nesting(); d.NextBlock(nesting); { switch d.Val() { case "allow_h2c": caddy.Log().Named("caddyfile").Warn("DEPRECATED: allow_h2c will be removed soon; use protocols option instead") if d.NextArg() { return nil, d.ArgErr() } if sliceContains(serverOpts.Protocols, "h2c") { return nil, d.Errf("protocol h2c already specified") } serverOpts.Protocols = append(serverOpts.Protocols, "h2c") case "strict_sni_host": caddy.Log().Named("caddyfile").Warn("DEPRECATED: protocol > strict_sni_host in this position will be removed soon; move up to the servers block instead") if d.NextArg() && d.Val() != "insecure_off" && d.Val() != "on" { return nil, d.Errf("strict_sni_host only supports 'on' or 'insecure_off', got '%s'", d.Val()) } boolVal := true if d.Val() == "insecure_off" { boolVal = false } serverOpts.StrictSNIHost = &boolVal default: return nil, d.Errf("unrecognized protocol option '%s'", d.Val()) } } default: return nil, d.Errf("unrecognized servers option '%s'", d.Val()) } } } return serverOpts, nil } // applyServerOptions sets the server options on the appropriate servers func applyServerOptions( servers map[string]*caddyhttp.Server, options map[string]any, warnings *[]caddyconfig.Warning, ) error { serverOpts, ok := options["servers"].([]serverOptions) if !ok { return nil } // check for duplicate names, which would clobber the config existingNames := map[string]bool{} for _, opts := range serverOpts { if opts.Name == "" { continue } if existingNames[opts.Name] { return fmt.Errorf("cannot use duplicate server name '%s'", opts.Name) } existingNames[opts.Name] = true } // collect the server name overrides nameReplacements := map[string]string{} for key, server := range servers { // find the options that apply to this server opts := func() *serverOptions { for _, entry := range serverOpts { if entry.ListenerAddress == "" { return &entry } for _, listener := range server.Listen { if entry.ListenerAddress == listener { return &entry } } } return nil }() // if none apply, then move to the next server if opts == nil { continue } // set all the options server.ListenerWrappersRaw = opts.ListenerWrappersRaw server.ReadTimeout = opts.ReadTimeout server.ReadHeaderTimeout = opts.ReadHeaderTimeout server.WriteTimeout = opts.WriteTimeout server.IdleTimeout = opts.IdleTimeout server.KeepAliveInterval = opts.KeepAliveInterval server.MaxHeaderBytes = opts.MaxHeaderBytes server.EnableFullDuplex = opts.EnableFullDuplex server.Protocols = opts.Protocols server.StrictSNIHost = opts.StrictSNIHost server.TrustedProxiesRaw = opts.TrustedProxiesRaw server.ClientIPHeaders = opts.ClientIPHeaders server.Metrics = opts.Metrics if opts.ShouldLogCredentials { if server.Logs == nil { server.Logs = &caddyhttp.ServerLogConfig{} } server.Logs.ShouldLogCredentials = opts.ShouldLogCredentials } if opts.Name != "" { nameReplacements[key] = opts.Name } } // rename the servers if marked to do so for old, new := range nameReplacements { servers[new] = servers[old] delete(servers, old) } return nil }
Go
caddy/caddyconfig/httpcaddyfile/tlsapp.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 httpcaddyfile import ( "bytes" "encoding/json" "fmt" "reflect" "sort" "strconv" "strings" "github.com/caddyserver/certmagic" "github.com/mholt/acmez/acme" "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" ) func (st ServerType) buildTLSApp( pairings []sbAddrAssociation, options map[string]any, warnings []caddyconfig.Warning, ) (*caddytls.TLS, []caddyconfig.Warning, error) { tlsApp := &caddytls.TLS{CertificatesRaw: make(caddy.ModuleMap)} var certLoaders []caddytls.CertificateLoader httpPort := strconv.Itoa(caddyhttp.DefaultHTTPPort) if hp, ok := options["http_port"].(int); ok { httpPort = strconv.Itoa(hp) } autoHTTPS := "on" if ah, ok := options["auto_https"].(string); ok { autoHTTPS = ah } // find all hosts that share a server block with a hostless // key, so that they don't get forgotten/omitted by auto-HTTPS // (since they won't appear in route matchers) httpsHostsSharedWithHostlessKey := make(map[string]struct{}) if autoHTTPS != "off" { for _, pair := range pairings { for _, sb := range pair.serverBlocks { for _, addr := range sb.keys { if addr.Host == "" { // this server block has a hostless key, now // go through and add all the hosts to the set for _, otherAddr := range sb.keys { if otherAddr.Original == addr.Original { continue } if otherAddr.Host != "" && otherAddr.Scheme != "http" && otherAddr.Port != httpPort { httpsHostsSharedWithHostlessKey[otherAddr.Host] = struct{}{} } } break } } } } } // a catch-all automation policy is used as a "default" for all subjects that // don't have custom configuration explicitly associated with them; this // is only to add if the global settings or defaults are non-empty catchAllAP, err := newBaseAutomationPolicy(options, warnings, false) if err != nil { return nil, warnings, err } if catchAllAP != nil { if tlsApp.Automation == nil { tlsApp.Automation = new(caddytls.AutomationConfig) } tlsApp.Automation.Policies = append(tlsApp.Automation.Policies, catchAllAP) } for _, p := range pairings { // avoid setting up TLS automation policies for a server that is HTTP-only if !listenersUseAnyPortOtherThan(p.addresses, httpPort) { continue } for _, sblock := range p.serverBlocks { // check the scheme of all the site addresses, // skip building AP if they all had http:// if sblock.isAllHTTP() { continue } // get values that populate an automation policy for this block ap, err := newBaseAutomationPolicy(options, warnings, true) if err != nil { return nil, warnings, err } sblockHosts := sblock.hostsFromKeys(false) if len(sblockHosts) == 0 && catchAllAP != nil { ap = catchAllAP } // on-demand tls if _, ok := sblock.pile["tls.on_demand"]; ok { ap.OnDemand = true } if keyTypeVals, ok := sblock.pile["tls.key_type"]; ok { ap.KeyType = keyTypeVals[0].Value.(string) } // certificate issuers if issuerVals, ok := sblock.pile["tls.cert_issuer"]; ok { var issuers []certmagic.Issuer for _, issuerVal := range issuerVals { issuers = append(issuers, issuerVal.Value.(certmagic.Issuer)) } if ap == catchAllAP && !reflect.DeepEqual(ap.Issuers, issuers) { // this more correctly implements an error check that was removed // below; try it with this config: // // :443 { // bind 127.0.0.1 // } // // :443 { // bind ::1 // tls { // issuer acme // } // } return nil, warnings, fmt.Errorf("automation policy from site block is also default/catch-all policy because of key without hostname, and the two are in conflict: %#v != %#v", ap.Issuers, issuers) } ap.Issuers = issuers } // certificate managers if certManagerVals, ok := sblock.pile["tls.cert_manager"]; ok { for _, certManager := range certManagerVals { certGetterName := certManager.Value.(caddy.Module).CaddyModule().ID.Name() ap.ManagersRaw = append(ap.ManagersRaw, caddyconfig.JSONModuleObject(certManager.Value, "via", certGetterName, &warnings)) } } // custom bind host for _, cfgVal := range sblock.pile["bind"] { for _, iss := range ap.Issuers { // if an issuer was already configured and it is NOT an ACME issuer, // skip, since we intend to adjust only ACME issuers; ensure we // include any issuer that embeds/wraps an underlying ACME issuer var acmeIssuer *caddytls.ACMEIssuer if acmeWrapper, ok := iss.(acmeCapable); ok { acmeIssuer = acmeWrapper.GetACMEIssuer() } if acmeIssuer == nil { continue } // proceed to configure the ACME issuer's bind host, without // overwriting any existing settings if acmeIssuer.Challenges == nil { acmeIssuer.Challenges = new(caddytls.ChallengesConfig) } if acmeIssuer.Challenges.BindHost == "" { // only binding to one host is supported var bindHost string if bindHosts, ok := cfgVal.Value.([]string); ok && len(bindHosts) > 0 { bindHost = bindHosts[0] } acmeIssuer.Challenges.BindHost = bindHost } } } // we used to ensure this block is allowed to create an automation policy; // doing so was forbidden if it has a key with no host (i.e. ":443") // and if there is a different server block that also has a key with no // host -- since a key with no host matches any host, we need its // associated automation policy to have an empty Subjects list, i.e. no // host filter, which is indistinguishable between the two server blocks // because automation is not done in the context of a particular server... // this is an example of a poor mapping from Caddyfile to JSON but that's // the least-leaky abstraction I could figure out -- however, this check // was preventing certain listeners, like those provided by plugins, from // being used as desired (see the Tailscale listener plugin), so I removed // the check: and I think since I originally wrote the check I added a new // check above which *properly* detects this ambiguity without breaking the // listener plugin; see the check above with a commented example config if len(sblockHosts) == 0 && catchAllAP == nil { // this server block has a key with no hosts, but there is not yet // a catch-all automation policy (probably because no global options // were set), so this one becomes it catchAllAP = ap } // associate our new automation policy with this server block's hosts ap.SubjectsRaw = sblock.hostsFromKeysNotHTTP(httpPort) sort.Strings(ap.SubjectsRaw) // solely for deterministic test results // if a combination of public and internal names were given // for this same server block and no issuer was specified, we // need to separate them out in the automation policies so // that the internal names can use the internal issuer and // the other names can use the default/public/ACME issuer var ap2 *caddytls.AutomationPolicy if len(ap.Issuers) == 0 { var internal, external []string for _, s := range ap.SubjectsRaw { // do not create Issuers for Tailscale domains; they will be given a Manager instead if strings.HasSuffix(strings.ToLower(s), ".ts.net") { continue } if !certmagic.SubjectQualifiesForCert(s) { return nil, warnings, fmt.Errorf("subject does not qualify for certificate: '%s'", s) } // we don't use certmagic.SubjectQualifiesForPublicCert() because of one nuance: // names like *.*.tld that may not qualify for a public certificate are actually // fine when used with OnDemand, since OnDemand (currently) does not obtain // wildcards (if it ever does, there will be a separate config option to enable // it that we would need to check here) since the hostname is known at handshake; // and it is unexpected to switch to internal issuer when the user wants to get // regular certificates on-demand for a class of certs like *.*.tld. if subjectQualifiesForPublicCert(ap, s) { external = append(external, s) } else { internal = append(internal, s) } } if len(external) > 0 && len(internal) > 0 { ap.SubjectsRaw = external apCopy := *ap ap2 = &apCopy ap2.SubjectsRaw = internal ap2.IssuersRaw = []json.RawMessage{caddyconfig.JSONModuleObject(caddytls.InternalIssuer{}, "module", "internal", &warnings)} } } if tlsApp.Automation == nil { tlsApp.Automation = new(caddytls.AutomationConfig) } tlsApp.Automation.Policies = append(tlsApp.Automation.Policies, ap) if ap2 != nil { tlsApp.Automation.Policies = append(tlsApp.Automation.Policies, ap2) } // certificate loaders if clVals, ok := sblock.pile["tls.cert_loader"]; ok { for _, clVal := range clVals { certLoaders = append(certLoaders, clVal.Value.(caddytls.CertificateLoader)) } } } } // group certificate loaders by module name, then add to config if len(certLoaders) > 0 { loadersByName := make(map[string]caddytls.CertificateLoader) for _, cl := range certLoaders { name := caddy.GetModuleName(cl) // ugh... technically, we may have multiple FileLoader and FolderLoader // modules (because the tls directive returns one per occurrence), but // the config structure expects only one instance of each kind of loader // module, so we have to combine them... instead of enumerating each // possible cert loader module in a type switch, we can use reflection, // which works on any cert loaders that are slice types if reflect.TypeOf(cl).Kind() == reflect.Slice { combined := reflect.ValueOf(loadersByName[name]) if !combined.IsValid() { combined = reflect.New(reflect.TypeOf(cl)).Elem() } clVal := reflect.ValueOf(cl) for i := 0; i < clVal.Len(); i++ { combined = reflect.Append(combined, clVal.Index(i)) } loadersByName[name] = combined.Interface().(caddytls.CertificateLoader) } } for certLoaderName, loaders := range loadersByName { tlsApp.CertificatesRaw[certLoaderName] = caddyconfig.JSON(loaders, &warnings) } } // set any of the on-demand options, for if/when on-demand TLS is enabled if onDemand, ok := options["on_demand_tls"].(*caddytls.OnDemandConfig); ok { if tlsApp.Automation == nil { tlsApp.Automation = new(caddytls.AutomationConfig) } tlsApp.Automation.OnDemand = onDemand } // set the storage clean interval if configured if storageCleanInterval, ok := options["storage_clean_interval"].(caddy.Duration); ok { if tlsApp.Automation == nil { tlsApp.Automation = new(caddytls.AutomationConfig) } tlsApp.Automation.StorageCleanInterval = storageCleanInterval } // set the expired certificates renew interval if configured if renewCheckInterval, ok := options["renew_interval"].(caddy.Duration); ok { if tlsApp.Automation == nil { tlsApp.Automation = new(caddytls.AutomationConfig) } tlsApp.Automation.RenewCheckInterval = renewCheckInterval } // set the OCSP check interval if configured if ocspCheckInterval, ok := options["ocsp_interval"].(caddy.Duration); ok { if tlsApp.Automation == nil { tlsApp.Automation = new(caddytls.AutomationConfig) } tlsApp.Automation.OCSPCheckInterval = ocspCheckInterval } // set whether OCSP stapling should be disabled for manually-managed certificates if ocspConfig, ok := options["ocsp_stapling"].(certmagic.OCSPConfig); ok { tlsApp.DisableOCSPStapling = ocspConfig.DisableStapling } // if any hostnames appear on the same server block as a key with // no host, they will not be used with route matchers because the // hostless key matches all hosts, therefore, it wouldn't be // considered for auto-HTTPS, so we need to make sure those hosts // are manually considered for managed certificates; we also need // to make sure that any of these names which are internal-only // get internal certificates by default rather than ACME var al caddytls.AutomateLoader internalAP := &caddytls.AutomationPolicy{ IssuersRaw: []json.RawMessage{json.RawMessage(`{"module":"internal"}`)}, } if autoHTTPS != "off" { for h := range httpsHostsSharedWithHostlessKey { al = append(al, h) if !certmagic.SubjectQualifiesForPublicCert(h) { internalAP.SubjectsRaw = append(internalAP.SubjectsRaw, h) } } } if len(al) > 0 { tlsApp.CertificatesRaw["automate"] = caddyconfig.JSON(al, &warnings) } if len(internalAP.SubjectsRaw) > 0 { if tlsApp.Automation == nil { tlsApp.Automation = new(caddytls.AutomationConfig) } tlsApp.Automation.Policies = append(tlsApp.Automation.Policies, internalAP) } // if there are any global options set for issuers (ACME ones in particular), make sure they // take effect in every automation policy that does not have any issuers if tlsApp.Automation != nil { globalEmail := options["email"] globalACMECA := options["acme_ca"] globalACMECARoot := options["acme_ca_root"] globalACMEDNS := options["acme_dns"] globalACMEEAB := options["acme_eab"] globalPreferredChains := options["preferred_chains"] hasGlobalACMEDefaults := globalEmail != nil || globalACMECA != nil || globalACMECARoot != nil || globalACMEDNS != nil || globalACMEEAB != nil || globalPreferredChains != nil if hasGlobalACMEDefaults { for i := 0; i < len(tlsApp.Automation.Policies); i++ { ap := tlsApp.Automation.Policies[i] if len(ap.Issuers) == 0 && automationPolicyHasAllPublicNames(ap) { // for public names, create default issuers which will later be filled in with configured global defaults // (internal names will implicitly use the internal issuer at auto-https time) ap.Issuers = caddytls.DefaultIssuers() // if a specific endpoint is configured, can't use multiple default issuers if globalACMECA != nil { if strings.Contains(globalACMECA.(string), "zerossl") { ap.Issuers = []certmagic.Issuer{&caddytls.ZeroSSLIssuer{ACMEIssuer: new(caddytls.ACMEIssuer)}} } else { ap.Issuers = []certmagic.Issuer{new(caddytls.ACMEIssuer)} } } } } } } // finalize and verify policies; do cleanup if tlsApp.Automation != nil { for i, ap := range tlsApp.Automation.Policies { // ensure all issuers have global defaults filled in for j, issuer := range ap.Issuers { err := fillInGlobalACMEDefaults(issuer, options) if err != nil { return nil, warnings, fmt.Errorf("filling in global issuer defaults for AP %d, issuer %d: %v", i, j, err) } } // encode all issuer values we created, so they will be rendered in the output if len(ap.Issuers) > 0 && ap.IssuersRaw == nil { for _, iss := range ap.Issuers { issuerName := iss.(caddy.Module).CaddyModule().ID.Name() ap.IssuersRaw = append(ap.IssuersRaw, caddyconfig.JSONModuleObject(iss, "module", issuerName, &warnings)) } } } // consolidate automation policies that are the exact same tlsApp.Automation.Policies = consolidateAutomationPolicies(tlsApp.Automation.Policies) // ensure automation policies don't overlap subjects (this should be // an error at provision-time as well, but catch it in the adapt phase // for convenience) automationHostSet := make(map[string]struct{}) for _, ap := range tlsApp.Automation.Policies { for _, s := range ap.SubjectsRaw { if _, ok := automationHostSet[s]; ok { return nil, warnings, fmt.Errorf("hostname appears in more than one automation policy, making certificate management ambiguous: %s", s) } automationHostSet[s] = struct{}{} } } // if nothing remains, remove any excess values to clean up the resulting config if len(tlsApp.Automation.Policies) == 0 { tlsApp.Automation.Policies = nil } if reflect.DeepEqual(tlsApp.Automation, new(caddytls.AutomationConfig)) { tlsApp.Automation = nil } } return tlsApp, warnings, nil } type acmeCapable interface{ GetACMEIssuer() *caddytls.ACMEIssuer } func fillInGlobalACMEDefaults(issuer certmagic.Issuer, options map[string]any) error { acmeWrapper, ok := issuer.(acmeCapable) if !ok { return nil } acmeIssuer := acmeWrapper.GetACMEIssuer() if acmeIssuer == nil { return nil } globalEmail := options["email"] globalACMECA := options["acme_ca"] globalACMECARoot := options["acme_ca_root"] globalACMEDNS := options["acme_dns"] globalACMEEAB := options["acme_eab"] globalPreferredChains := options["preferred_chains"] if globalEmail != nil && acmeIssuer.Email == "" { acmeIssuer.Email = globalEmail.(string) } if globalACMECA != nil && acmeIssuer.CA == "" { acmeIssuer.CA = globalACMECA.(string) } if globalACMECARoot != nil && !sliceContains(acmeIssuer.TrustedRootsPEMFiles, globalACMECARoot.(string)) { acmeIssuer.TrustedRootsPEMFiles = append(acmeIssuer.TrustedRootsPEMFiles, globalACMECARoot.(string)) } if globalACMEDNS != nil && (acmeIssuer.Challenges == nil || acmeIssuer.Challenges.DNS == nil) { acmeIssuer.Challenges = &caddytls.ChallengesConfig{ DNS: &caddytls.DNSChallengeConfig{ ProviderRaw: caddyconfig.JSONModuleObject(globalACMEDNS, "name", globalACMEDNS.(caddy.Module).CaddyModule().ID.Name(), nil), }, } } if globalACMEEAB != nil && acmeIssuer.ExternalAccount == nil { acmeIssuer.ExternalAccount = globalACMEEAB.(*acme.EAB) } if globalPreferredChains != nil && acmeIssuer.PreferredChains == nil { acmeIssuer.PreferredChains = globalPreferredChains.(*caddytls.ChainPreference) } return nil } // newBaseAutomationPolicy returns a new TLS automation policy that gets // its values from the global options map. It should be used as the base // for any other automation policies. A nil policy (and no error) will be // returned if there are no default/global options. However, if always is // true, a non-nil value will always be returned (unless there is an error). func newBaseAutomationPolicy(options map[string]any, warnings []caddyconfig.Warning, always bool) (*caddytls.AutomationPolicy, error) { issuers, hasIssuers := options["cert_issuer"] _, hasLocalCerts := options["local_certs"] keyType, hasKeyType := options["key_type"] ocspStapling, hasOCSPStapling := options["ocsp_stapling"] hasGlobalAutomationOpts := hasIssuers || hasLocalCerts || hasKeyType || hasOCSPStapling // if there are no global options related to automation policies // set, then we can just return right away if !hasGlobalAutomationOpts { if always { return new(caddytls.AutomationPolicy), nil } return nil, nil } ap := new(caddytls.AutomationPolicy) if hasKeyType { ap.KeyType = keyType.(string) } if hasIssuers && hasLocalCerts { return nil, fmt.Errorf("global options are ambiguous: local_certs is confusing when combined with cert_issuer, because local_certs is also a specific kind of issuer") } if hasIssuers { ap.Issuers = issuers.([]certmagic.Issuer) } else if hasLocalCerts { ap.Issuers = []certmagic.Issuer{new(caddytls.InternalIssuer)} } if hasOCSPStapling { ocspConfig := ocspStapling.(certmagic.OCSPConfig) ap.DisableOCSPStapling = ocspConfig.DisableStapling ap.OCSPOverrides = ocspConfig.ResponderOverrides } return ap, nil } // consolidateAutomationPolicies combines automation policies that are the same, // for a cleaner overall output. func consolidateAutomationPolicies(aps []*caddytls.AutomationPolicy) []*caddytls.AutomationPolicy { // sort from most specific to least specific; we depend on this ordering sort.SliceStable(aps, func(i, j int) bool { if automationPolicyIsSubset(aps[i], aps[j]) { return true } if automationPolicyIsSubset(aps[j], aps[i]) { return false } return len(aps[i].SubjectsRaw) > len(aps[j].SubjectsRaw) }) emptyAPCount := 0 origLenAPs := len(aps) // compute the number of empty policies (disregarding subjects) - see #4128 emptyAP := new(caddytls.AutomationPolicy) for i := 0; i < len(aps); i++ { emptyAP.SubjectsRaw = aps[i].SubjectsRaw if reflect.DeepEqual(aps[i], emptyAP) { emptyAPCount++ if !automationPolicyHasAllPublicNames(aps[i]) { // if this automation policy has internal names, we might as well remove it // so auto-https can implicitly use the internal issuer aps = append(aps[:i], aps[i+1:]...) i-- } } } // If all policies are empty, we can return nil, as there is no need to set any policy if emptyAPCount == origLenAPs { return nil } // remove or combine duplicate policies outer: for i := 0; i < len(aps); i++ { // compare only with next policies; we sorted by specificity so we must not delete earlier policies for j := i + 1; j < len(aps); j++ { // if they're exactly equal in every way, just keep one of them if reflect.DeepEqual(aps[i], aps[j]) { aps = append(aps[:j], aps[j+1:]...) // must re-evaluate current i against next j; can't skip it! // even if i decrements to -1, will be incremented to 0 immediately i-- continue outer } // if the policy is the same, we can keep just one, but we have // to be careful which one we keep; if only one has any hostnames // defined, then we need to keep the one without any hostnames, // otherwise the one without any subjects (a catch-all) would be // eaten up by the one with subjects; and if both have subjects, we // need to combine their lists if reflect.DeepEqual(aps[i].IssuersRaw, aps[j].IssuersRaw) && bytes.Equal(aps[i].StorageRaw, aps[j].StorageRaw) && aps[i].MustStaple == aps[j].MustStaple && aps[i].KeyType == aps[j].KeyType && aps[i].OnDemand == aps[j].OnDemand && aps[i].RenewalWindowRatio == aps[j].RenewalWindowRatio { if len(aps[i].SubjectsRaw) > 0 && len(aps[j].SubjectsRaw) == 0 { // later policy (at j) has no subjects ("catch-all"), so we can // remove the identical-but-more-specific policy that comes first // AS LONG AS it is not shadowed by another policy before it; e.g. // if policy i is for example.com, policy i+1 is '*.com', and policy // j is catch-all, we cannot remove policy i because that would // cause example.com to be served by the less specific policy for // '*.com', which might be different (yes we've seen this happen) if automationPolicyShadows(i, aps) >= j { aps = append(aps[:i], aps[i+1:]...) i-- continue outer } } else { // avoid repeated subjects for _, subj := range aps[j].SubjectsRaw { if !sliceContains(aps[i].SubjectsRaw, subj) { aps[i].SubjectsRaw = append(aps[i].SubjectsRaw, subj) } } aps = append(aps[:j], aps[j+1:]...) j-- } } } } return aps } // automationPolicyIsSubset returns true if a's subjects are a subset // of b's subjects. func automationPolicyIsSubset(a, b *caddytls.AutomationPolicy) bool { if len(b.SubjectsRaw) == 0 { return true } if len(a.SubjectsRaw) == 0 { return false } for _, aSubj := range a.SubjectsRaw { var inSuperset bool for _, bSubj := range b.SubjectsRaw { if certmagic.MatchWildcard(aSubj, bSubj) { inSuperset = true break } } if !inSuperset { return false } } return true } // automationPolicyShadows returns the index of a policy that aps[i] shadows; // in other words, for all policies after position i, if that policy covers // the same subjects but is less specific, that policy's position is returned, // or -1 if no shadowing is found. For example, if policy i is for // "foo.example.com" and policy i+2 is for "*.example.com", then i+2 will be // returned, since that policy is shadowed by i, which is in front. func automationPolicyShadows(i int, aps []*caddytls.AutomationPolicy) int { for j := i + 1; j < len(aps); j++ { if automationPolicyIsSubset(aps[i], aps[j]) { return j } } return -1 } // subjectQualifiesForPublicCert is like certmagic.SubjectQualifiesForPublicCert() except // that this allows domains with multiple wildcard levels like '*.*.example.com' to qualify // if the automation policy has OnDemand enabled (i.e. this function is more lenient). func subjectQualifiesForPublicCert(ap *caddytls.AutomationPolicy, subj string) bool { return !certmagic.SubjectIsIP(subj) && !certmagic.SubjectIsInternal(subj) && (strings.Count(subj, "*.") < 2 || ap.OnDemand) } func automationPolicyHasAllPublicNames(ap *caddytls.AutomationPolicy) bool { for _, subj := range ap.SubjectsRaw { if !subjectQualifiesForPublicCert(ap, subj) { return false } } return true }
Go
caddy/caddyconfig/httpcaddyfile/tlsapp_test.go
package httpcaddyfile import ( "testing" "github.com/caddyserver/caddy/v2/modules/caddytls" ) func TestAutomationPolicyIsSubset(t *testing.T) { for i, test := range []struct { a, b []string expect bool }{ { a: []string{"example.com"}, b: []string{}, expect: true, }, { a: []string{}, b: []string{"example.com"}, expect: false, }, { a: []string{"foo.example.com"}, b: []string{"*.example.com"}, expect: true, }, { a: []string{"foo.example.com"}, b: []string{"foo.example.com"}, expect: true, }, { a: []string{"foo.example.com"}, b: []string{"example.com"}, expect: false, }, { a: []string{"example.com", "foo.example.com"}, b: []string{"*.com", "*.*.com"}, expect: true, }, { a: []string{"example.com", "foo.example.com"}, b: []string{"*.com"}, expect: false, }, } { apA := &caddytls.AutomationPolicy{SubjectsRaw: test.a} apB := &caddytls.AutomationPolicy{SubjectsRaw: test.b} if actual := automationPolicyIsSubset(apA, apB); actual != test.expect { t.Errorf("Test %d: Expected %t but got %t (A: %v B: %v)", i, test.expect, actual, test.a, test.b) } } }
caddy/caddytest/a.caddy.localhost.crt
-----BEGIN CERTIFICATE----- MIID5zCCAs8CFG4+w/pqR5AZQ+aVB330uRRRKMF0MA0GCSqGSIb3DQEBCwUAMIGv MQswCQYDVQQGEwJVUzELMAkGA1UECAwCTlkxGzAZBgNVBAoMEkxvY2FsIERldmVs b3BlbWVudDEbMBkGA1UEBwwSTG9jYWwgRGV2ZWxvcGVtZW50MRowGAYDVQQDDBFh LmNhZGR5LmxvY2FsaG9zdDEbMBkGA1UECwwSTG9jYWwgRGV2ZWxvcGVtZW50MSAw HgYJKoZIhvcNAQkBFhFhZG1pbkBjYWRkeS5sb2NhbDAeFw0yMDAzMTMxODUwMTda Fw0zMDAzMTExODUwMTdaMIGvMQswCQYDVQQGEwJVUzELMAkGA1UECAwCTlkxGzAZ BgNVBAoMEkxvY2FsIERldmVsb3BlbWVudDEbMBkGA1UEBwwSTG9jYWwgRGV2ZWxv cGVtZW50MRowGAYDVQQDDBFhLmNhZGR5LmxvY2FsaG9zdDEbMBkGA1UECwwSTG9j YWwgRGV2ZWxvcGVtZW50MSAwHgYJKoZIhvcNAQkBFhFhZG1pbkBjYWRkeS5sb2Nh bDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMd9pC9wF7j0459FndPs Deud/rq41jEZFsVOVtjQgjS1A5ct6NfeMmSlq8i1F7uaTMPZjbOHzY6y6hzLc9+y /VWNgyUC543HjXnNTnp9Xug6tBBxOxvRMw5mv2nAyzjBGDePPgN84xKhOXG2Wj3u fOZ+VPVISefRNvjKfN87WLJ0B0HI9wplG5ASVdPQsWDY1cndrZgt2sxQ/3fjIno4 VvrgRWC9Penizgps/a0ZcFZMD/6HJoX/mSZVa1LjopwbMTXvyHCpXkth21E+rBt6 I9DMHerdioVQcX25CqPmAwePxPZSNGEQo/Qu32kzcmscmYxTtYBhDa+yLuHgGggI j7ECAwEAATANBgkqhkiG9w0BAQsFAAOCAQEAP/94KPtkpYtkWADnhtzDmgQ6Q1pH SubTUZdCwQtm6/LrvpT+uFNsOj4L3Mv3TVUnIQDmKd5VvR42W2MRBiTN2LQptgEn C7g9BB+UA9kjL3DPk1pJMjzxLHohh0uNLi7eh4mAj8eNvjz9Z4qMWPQoVS0y7/ZK cCBRKh2GkIqKm34ih6pX7xmMpPEQsFoTVPRHYJfYD1SZ8Iui+EN+7WqLuJWPsPXw JM1HuZKn7pZmJU2MZZBsrupHGUvNMbBg2mFJcxt4D1VvU+p+a67PSjpFQ6dJG2re pZoF+N1vMGAFkxe6UqhcC/bXDX+ILVQHJ+RNhzDO6DcWf8dRrC2LaJk3WA== -----END CERTIFICATE-----
caddy/caddytest/a.caddy.localhost.key
-----BEGIN RSA PRIVATE KEY----- MIIEpAIBAAKCAQEAx32kL3AXuPTjn0Wd0+wN653+urjWMRkWxU5W2NCCNLUDly3o 194yZKWryLUXu5pMw9mNs4fNjrLqHMtz37L9VY2DJQLnjceNec1Oen1e6Dq0EHE7 G9EzDma/acDLOMEYN48+A3zjEqE5cbZaPe585n5U9UhJ59E2+Mp83ztYsnQHQcj3 CmUbkBJV09CxYNjVyd2tmC3azFD/d+MiejhW+uBFYL096eLOCmz9rRlwVkwP/ocm hf+ZJlVrUuOinBsxNe/IcKleS2HbUT6sG3oj0Mwd6t2KhVBxfbkKo+YDB4/E9lI0 YRCj9C7faTNyaxyZjFO1gGENr7Iu4eAaCAiPsQIDAQABAoIBAQDD/YFIBeWYlifn e9risQDAIrp3sk7lb9O6Rwv1+Wxi4hBEABvJsYhq74VFK/3EF4UhyWR5JIvkjYyK e6w887oGyoA05ZSe65XoO7fFidSrbbkoikZbPv3dQT7/ZCWEfdkQBNAVVyY0UGeC e3hPbjYRsb5AOSQ694X9idqC6uhqcOrBDjITFrctUoP4S6l9A6a+mLSUIwiICcuh mrNl+j0lzy7DMXRp/Z5Hyo5kuUlrC0dCLa1UHqtrrK7MR55AVEOihSNp1w+OC+vw f0VjE4JUtO7RQEQUmD1tDfLXwNfMFeWaobB2W0WMvRg0IqoitiqPxsPHRm56OxfM SRo/Q7QBAoGBAP8DapzBMuaIcJ7cE8Yl07ZGndWWf8buIKIItGF8rkEO3BXhrIke EmpOi+ELtpbMOG0APhORZyQ58f4ZOVrqZfneNKtDiEZV4mJZaYUESm1pU+2Y6+y5 g4bpQSVKN0ow0xR+MH7qDYtSlsmBU7qAOz775L7BmMA1Bnu72aN/H1JBAoGBAMhD OzqCSakHOjUbEd22rPwqWmcIyVyo04gaSmcVVT2dHbqR4/t0gX5a9D9U2qwyO6xi /R+PXyMd32xIeVR2D/7SQ0x6dK68HXICLV8ofHZ5UQcHbxy5og4v/YxSZVTkN374 cEsUeyB0s/UPOHLktFU5hpIlON72/Rp7b+pNIwFxAoGAczpq+Qu/YTWzlcSh1r4O 7OT5uqI3eH7vFehTAV3iKxl4zxZa7NY+wfRd9kFhrr/2myIp6pOgBFl+hC+HoBIc JAyIxf5M3GNAWOpH6MfojYmzV7/qktu8l8BcJGplk0t+hVsDtMUze4nFAqZCXBpH Kw2M7bjyuZ78H/rgu6TcVUECgYEAo1M5ldE2U/VCApeuLX1TfWDpU8i1uK0zv3d5 oLKkT1i5KzTak3SEO9HgC1qf8PoS8tfUio26UICHe99rnHehOfivzEq+qNdgyF+A M3BoeZMdgzcL5oh640k+Zte4LtDlddcWdhUhCepD7iPYrNNbQ3pkBwL2a9lRuOxc 7OC2IPECgYBH8f3OrwXjDltIG1dDvuDPNljxLZbFEFbQyVzMePYNftgZknAyGEdh NW/LuWeTzstnmz/s6RE3jN5ZrrMa4sW77VA9+yU9QW2dkHqFyukQ4sfuNg6kDDNZ +lqZYMCLw0M5P9fIbmnIYwey7tXkHfmzoCpnYHGQDN6hL0Bh0zGwmg== -----END RSA PRIVATE KEY-----
caddy/caddytest/caddy.ca.cer
-----BEGIN CERTIFICATE----- MIIDSzCCAjOgAwIBAgIUfIRObjWNUA4jxQ/0x8BOCvE2Vw4wDQYJKoZIhvcNAQEL BQAwFjEUMBIGA1UEAwwLRWFzeS1SU0EgQ0EwHhcNMTkwODI4MTYyNTU5WhcNMjkw ODI1MTYyNTU5WjAWMRQwEgYDVQQDDAtFYXN5LVJTQSBDQTCCASIwDQYJKoZIhvcN AQEBBQADggEPADCCAQoCggEBAK5m5elxhQfMp/3aVJ4JnpN9PUSz6LlP6LePAPFU 7gqohVVFVtDkChJAG3FNkNQNlieVTja/bgH9IcC6oKbROwdY1h0MvNV8AHHigvl0 3WuJD8g2ReVFXXwsnrPmKXCFzQyMI6TYk3m2gYrXsZOU1GLnfMRC3KAMRgE2F45t wOs9hqG169YJ6mM2eQjzjCHWI6S2/iUYvYxRkCOlYUbLsMD/AhgAf1plzg6LPqNx tdlwxZnA0ytgkmhK67HtzJu0+ovUCsMv0RwcMhsEo9T8nyFAGt9XLZ63X5WpBCTU ApaAUhnG0XnerjmUWb6eUWw4zev54sEfY5F3x002iQaW6cECAwEAAaOBkDCBjTAd BgNVHQ4EFgQU4CBUbZsS2GaNIkGRz/cBsD5ivjswUQYDVR0jBEowSIAU4CBUbZsS 2GaNIkGRz/cBsD5ivjuhGqQYMBYxFDASBgNVBAMMC0Vhc3ktUlNBIENBghR8hE5u NY1QDiPFD/THwE4K8TZXDjAMBgNVHRMEBTADAQH/MAsGA1UdDwQEAwIBBjANBgkq hkiG9w0BAQsFAAOCAQEAKB3V4HIzoiO/Ch6WMj9bLJ2FGbpkMrcb/Eq01hT5zcfK D66lVS1MlK+cRL446Z2b2KDP1oFyVs+qmrmtdwrWgD+nfe2sBmmIHo9m9KygMkEO fG3MghGTEcS+0cTKEcoHYWYyOqQh6jnedXY8Cdm4GM1hAc9MiL3/sqV8YCVSLNnk oNysmr06/rZ0MCUZPGUtRmfd0heWhrfzAKw2HLgX+RAmpOE2MZqWcjvqKGyaRiaZ ks4nJkP6521aC2Lgp0HhCz1j8/uQ5ldoDszCnu/iro0NAsNtudTMD+YoLQxLqdle Ih6CW+illc2VdXwj7mn6J04yns9jfE2jRjW/yTLFuQ== -----END CERTIFICATE-----
caddy/caddytest/caddy.localhost.crt
-----BEGIN CERTIFICATE----- MIID5zCCAs8CFFmAAFKV79uhzxc5qXbUw3oBNsYXMA0GCSqGSIb3DQEBCwUAMIGv MQswCQYDVQQGEwJVUzELMAkGA1UECAwCTlkxGzAZBgNVBAoMEkxvY2FsIERldmVs b3BlbWVudDEbMBkGA1UEBwwSTG9jYWwgRGV2ZWxvcGVtZW50MRowGAYDVQQDDBEq LmNhZGR5LmxvY2FsaG9zdDEbMBkGA1UECwwSTG9jYWwgRGV2ZWxvcGVtZW50MSAw HgYJKoZIhvcNAQkBFhFhZG1pbkBjYWRkeS5sb2NhbDAeFw0yMDAzMDIwODAxMTZa Fw0zMDAyMjgwODAxMTZaMIGvMQswCQYDVQQGEwJVUzELMAkGA1UECAwCTlkxGzAZ BgNVBAoMEkxvY2FsIERldmVsb3BlbWVudDEbMBkGA1UEBwwSTG9jYWwgRGV2ZWxv cGVtZW50MRowGAYDVQQDDBEqLmNhZGR5LmxvY2FsaG9zdDEbMBkGA1UECwwSTG9j YWwgRGV2ZWxvcGVtZW50MSAwHgYJKoZIhvcNAQkBFhFhZG1pbkBjYWRkeS5sb2Nh bDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJngfeirQkWaU8ihgIC5 SKpRQX/3koRjljDK/oCbhLs+wg592kIwVv06l7+mn7NSaNBloabjuA1GqyLRsNLL ptrv0HvXa5qLx28+icsb2Ny3dJnQaj9w9PwjxQ1qZqEJfWRH1D8Vz9AmB+QSV/Gu 8e8alGFewlYZVfH1kbxoTT6QorF37TeA3bh1fgKFtzsGYKswcaZNdDBBHzLunCKZ HU6U6L45hm+yLADj3mmDLafUeiVOt6MRLLoSD1eLRVSXGrNo+brJ87zkZntI9+W1 JxOBoXtZCwka7k2DlAtLihsrmBZA2ZC9yVeu/SQy3qb3iCNnTFTCyAnWeTCr6Tcq 6w8CAwEAATANBgkqhkiG9w0BAQsFAAOCAQEAOWfXqpAmD4C3wGiMeZAeaaS4hDAR +JmN+avPDA6F6Bq7DB4NJuIwVUlaDL2s07w5VJJtW52aZVKoBlgHR5yG/XUli6J7 YUJRmdQJvHUSu26cmKvyoOaTrEYbmvtGICWtZc8uTlMf9wQZbJA4KyxTgEQJDXsZ B2XFe+wVdhAgEpobYDROi+l/p8TL5z3U24LpwVTcJy5sEZVv7Wfs886IyxU8ORt8 VZNcDiH6V53OIGeiufIhia/mPe6jbLntfGZfIFxtCcow4IA/lTy1ned7K5fmvNNb ZilxOQUk+wVK8genjdrZVAnAxsYLHJIb5yf9O7rr6fWciVMF3a0k5uNK1w== -----END CERTIFICATE-----
caddy/caddytest/caddy.localhost.key
-----BEGIN RSA PRIVATE KEY----- MIIEogIBAAKCAQEAmeB96KtCRZpTyKGAgLlIqlFBf/eShGOWMMr+gJuEuz7CDn3a QjBW/TqXv6afs1Jo0GWhpuO4DUarItGw0sum2u/Qe9drmovHbz6JyxvY3Ld0mdBq P3D0/CPFDWpmoQl9ZEfUPxXP0CYH5BJX8a7x7xqUYV7CVhlV8fWRvGhNPpCisXft N4DduHV+AoW3OwZgqzBxpk10MEEfMu6cIpkdTpTovjmGb7IsAOPeaYMtp9R6JU63 oxEsuhIPV4tFVJcas2j5usnzvORme0j35bUnE4Ghe1kLCRruTYOUC0uKGyuYFkDZ kL3JV679JDLepveII2dMVMLICdZ5MKvpNyrrDwIDAQABAoIBAFcPK01zb6hfm12c +k5aBiHOnUdgc/YRPg1XHEz5MEycQkDetZjTLrRQ7UBSbnKPgpu9lIsOtbhVLkgh 6XAqJroiCou2oruqr+hhsqZGmBiwdvj7cNF6ADGTr05az7v22YneFdinZ481pStF sZocx+bm2+KHMV5zMSwXKyA0xtdJLxs2yklniDBxSZRppgppq1pDPprP5DkgKPfe 3ekUmbQd5bHmivhW8ItbJLuf82XSsMBZ9ZhKiKIlWlbKAgiSV3SqnUQb5fi7l8hG yYZxbuCUIGFwKmEpUBBt/nyxrOlMiNtDh9JhrPmijTV3slq70pCLwLL/Ai2aeear EVA5VhkCgYEAyAmxfPqc2P7BsDAp67/sA7OEPso9qM4WyuWiVdlX2gb9TLNLYbPX Kk/UmpAIVzpoTAGY5Zp3wkvdD/ou8uUQsE8ioNn4S1a4G9XURH1wVhcEbUiAKI1S QVBH9B/Pj3eIp5OTKwob0Wj7DNdxoH7ed/Eok0EaTWzOA8pCWADKv/MCgYEAxOzY YsX7Nl+eyZr2+9unKyeAK/D1DCT/o99UUAHx72/xaBVP/06cfzpvKBNcF9iYc+fq R1yIUIrDRoSmYKBq+Kb3+nOg1nrqih/NBTokbTiI4Q+/30OQt0Al1e7y9iNKqV8H jYZItzluGNrWKedZbATwBwbVCY2jnNl6RMDnS3UCgYBxj3cwQUHLuoyQjjcuO80r qLzZvIxWiXDNDKIk5HcIMlGYOmz/8U2kGp/SgxQJGQJeq8V2C0QTjGfaCyieAcaA oNxCvptDgd6RBsoze5bLeNOtiqwe2WOp6n5+q5R0mOJ+Z7vzghCayGNFPgWmnH+F TeW/+wSIkc0+v5L8TK7NWwKBgBrlWlyLO9deUfqpHqihhICBYaEexOlGuF+yZfqT eW7BdFBJ8OYm33sFCR+JHV/oZlIWT8o1Wizd9vPPtEWoQ1P4wg/D8Si6GwSIeWEI YudD/HX4x7T/rmlI6qIAg9CYW18sqoRq3c2gm2fro6qPfYgiWIItLbWjUcBfd7Ki QjTtAoGARKdRv3jMWL84rlEx1nBRgL3pe9Dt+Uxzde2xT3ZeF+5Hp9NfU01qE6M6 1I6H64smqpetlsXmCEVKwBemP3pJa6avLKgIYiQvHAD/v4rs9mqgy1RTqtYyGNhR 1A/6dKkbiZ6wzePLLPasXVZxSKEviXf5gJooqumQVSVhCswyCZ0= -----END RSA PRIVATE KEY-----
Go
caddy/caddytest/caddytest.go
package caddytest import ( "bytes" "context" "crypto/tls" "encoding/json" "errors" "fmt" "io" "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" ) // Defaults store any configuration required to make the tests run type Defaults struct { // Port we expect caddy to listening on AdminPort int // Certificates we expect to be loaded before attempting to run the tests Certifcates []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 = Defaults{ AdminPort: 2999, // different from what a real server also running on a developer's machine might be Certifcates: []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.T } // NewTester will create a new testing client with an attached cookie jar func NewTester(t *testing.T) *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, } } 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.t) 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/", Default.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) client := &http.Client{ Timeout: Default.LoadRequestTimeout, } start := time.Now() req, err := http.NewRequest("POST", fmt.Sprintf("http://localhost:%d/load", Default.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: Default.LoadRequestTimeout, } fetchConfig := func(client *http.Client) any { resp, err := client.Get(fmt.Sprintf("http://localhost:%d/config/", Default.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:2999 } ` // validateTestPrerequisites ensures the certificates are available in the // designated path and Caddy sub-process is running. func validateTestPrerequisites(t *testing.T) error { // check certificates are found for _, certName := range Default.Certifcates { if _, err := os.Stat(getIntegrationDir() + certName); os.IsNotExist(err) { return fmt.Errorf("caddy integration test certificates (%s) not found", certName) } } if isCaddyAdminRunning() != nil { // setup the init config file, and set the cleanup afterwards f, err := os.CreateTemp("", "") if err != nil { return err } t.Cleanup(func() { os.Remove(f.Name()) }) if _, err := f.WriteString(initConfig); 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() != nil; retries-- { time.Sleep(1 * time.Second) } } // one more time to return the error return isCaddyAdminRunning() } func isCaddyAdminRunning() error { // assert that caddy is running client := &http.Client{ Timeout: Default.LoadRequestTimeout, } resp, err := client.Get(fmt.Sprintf("http://localhost:%d/config/", Default.AdminPort)) if err != nil { return fmt.Errorf("caddy integration test caddy server not running. Expected to be listening on localhost:%d", Default.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) { 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 { 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.T, filename, rawConfig string, adapterName string, expectedResponse string) bool { 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.T, rawConfig string, adapterName string, expectedResponse string) { ok := CompareAdapt(t, "Caddyfile", rawConfig, adapterName, expectedResponse) if !ok { t.Fail() } } // Generic request functions func applyHeaders(t *testing.T, 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 { 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.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) { 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) { 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) { 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) { 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) { 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) { 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
caddy/caddytest/caddytest_test.go
package caddytest import ( "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") } }
Go
caddy/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
caddy/caddytest/integration/caddyfile_adapt_test.go
package integration import ( jsonMod "encoding/json" "fmt" "os" "path/filepath" "regexp" "strings" "testing" "github.com/caddyserver/caddy/v2/caddytest" ) 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 } // read the test file filename := f.Name() 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, json := strings.TrimSpace(parts[0])+"\n", strings.TrimSpace(parts[1]) // replace windows newlines in the json with unix newlines json = winNewlines.ReplaceAllString(json, "\n") // replace os-specific default path for file_server's hide field replacePath, _ := jsonMod.Marshal(fmt.Sprint(".", string(filepath.Separator), "Caddyfile")) json = strings.ReplaceAll(json, `"./Caddyfile"`, string(replacePath)) // run the test ok := caddytest.CompareAdapt(t, filename, caddyfile, "caddyfile", json) if !ok { t.Errorf("failed to adapt %s", filename) } } }
Go
caddy/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) } }
Go
caddy/caddytest/integration/handler_test.go
package integration import ( "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) }
Go
caddy/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
caddy/caddytest/integration/pki_test.go
package integration import ( "testing" "github.com/caddyserver/caddy/v2/caddytest" ) func TestLeafCertLifetimeLessThanIntermediate(t *testing.T) { caddytest.AssertLoadError(t, ` { "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, ` { "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
caddy/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 } } `, "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
caddy/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
caddy/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" "github.com/caddyserver/caddy/v2/caddytest" "golang.org/x/net/http2" "golang.org/x/net/http2/h2c" ) // (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 automaticlly 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
caddy/cmd/cobra.go
package caddycmd import ( "github.com/spf13/cobra" ) var rootCmd = &cobra.Command{ Use: "caddy", Long: `Caddy is an extensible server platform written in Go. At its core, Caddy merely manages configuration. Modules are plugged in statically at compile-time to provide useful functionality. Caddy's standard distribution includes common modules to serve HTTP, TLS, and PKI applications, including the automation of certificates. To run Caddy, use: - 'caddy run' to run Caddy in the foreground (recommended). - 'caddy start' to start Caddy in the background; only do this if you will be keeping the terminal window open until you run 'caddy stop' to close the server. When Caddy is started, it opens a locally-bound administrative socket to which configuration can be POSTed via a restful HTTP API (see https://caddyserver.com/docs/api). Caddy's native configuration format is JSON. However, config adapters can be used to convert other config formats to JSON when Caddy receives its configuration. The Caddyfile is a built-in config adapter that is popular for hand-written configurations due to its straightforward syntax (see https://caddyserver.com/docs/caddyfile). Many third-party adapters are available (see https://caddyserver.com/docs/config-adapters). Use 'caddy adapt' to see how a config translates to JSON. For convenience, the CLI can act as an HTTP client to give Caddy its initial configuration for you. If a file named Caddyfile is in the current working directory, it will do this automatically. Otherwise, you can use the --config flag to specify the path to a config file. Some special-purpose subcommands build and load a configuration file for you directly from command line input; for example: - caddy file-server - caddy reverse-proxy - caddy respond These commands disable the administration endpoint because their configuration is specified solely on the command line. In general, the most common way to run Caddy is simply: $ caddy run Or, with a configuration file: $ caddy run --config caddy.json If running interactively in a terminal, running Caddy in the background may be more convenient: $ caddy start ... $ caddy stop This allows you to run other commands while Caddy stays running. Be sure to stop Caddy before you close the terminal! Depending on the system, Caddy may need permission to bind to low ports. One way to do this on Linux is to use setcap: $ sudo setcap cap_net_bind_service=+ep $(which caddy) Remember to run that command again after replacing the binary. See the Caddy website for tutorials, configuration structure, syntax, and module documentation: https://caddyserver.com/docs/ Custom Caddy builds are available on the Caddy download page at: https://caddyserver.com/download The xcaddy command can be used to build Caddy from source with or without additional plugins: https://github.com/caddyserver/xcaddy Where possible, Caddy should be installed using officially-supported package installers: https://caddyserver.com/docs/install Instructions for running Caddy in production are also available: https://caddyserver.com/docs/running `, Example: ` $ caddy run $ caddy run --config caddy.json $ caddy reload --config caddy.json $ caddy stop`, // kind of annoying to have all the help text printed out if // caddy has an error provisioning its modules, for instance... SilenceUsage: true, } const fullDocsFooter = `Full documentation is available at: https://caddyserver.com/docs/command-line` func init() { rootCmd.SetHelpTemplate(rootCmd.HelpTemplate() + "\n" + fullDocsFooter + "\n") } func caddyCmdToCobra(caddyCmd Command) *cobra.Command { cmd := &cobra.Command{ Use: caddyCmd.Name, Short: caddyCmd.Short, Long: caddyCmd.Long, } if caddyCmd.CobraFunc != nil { caddyCmd.CobraFunc(cmd) } else { cmd.RunE = WrapCommandFuncForCobra(caddyCmd.Func) cmd.Flags().AddGoFlagSet(caddyCmd.Flags) } return cmd } // WrapCommandFuncForCobra wraps a Caddy CommandFunc for use // in a cobra command's RunE field. func WrapCommandFuncForCobra(f CommandFunc) func(cmd *cobra.Command, _ []string) error { return func(cmd *cobra.Command, _ []string) error { _, err := f(Flags{cmd.Flags()}) return err } }
Go
caddy/cmd/commandfuncs.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 caddycmd import ( "bytes" "context" "crypto/rand" "encoding/json" "errors" "fmt" "io" "io/fs" "log" "net" "net/http" "os" "os/exec" "runtime" "runtime/debug" "strings" "github.com/aryann/difflib" "go.uber.org/zap" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/internal" ) func cmdStart(fl Flags) (int, error) { startCmdConfigFlag := fl.String("config") startCmdConfigAdapterFlag := fl.String("adapter") startCmdPidfileFlag := fl.String("pidfile") startCmdWatchFlag := fl.Bool("watch") startCmdEnvfileFlag := fl.String("envfile") // open a listener to which the child process will connect when // it is ready to confirm that it has successfully started ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("opening listener for success confirmation: %v", err) } defer ln.Close() // craft the command with a pingback address and with a // pipe for its stdin, so we can tell it our confirmation // code that we expect so that some random port scan at // the most unfortunate time won't fool us into thinking // the child succeeded (i.e. the alternative is to just // wait for any connection on our listener, but better to // ensure it's the process we're expecting - we can be // sure by giving it some random bytes and having it echo // them back to us) cmd := exec.Command(os.Args[0], "run", "--pingback", ln.Addr().String()) if startCmdConfigFlag != "" { cmd.Args = append(cmd.Args, "--config", startCmdConfigFlag) } if startCmdEnvfileFlag != "" { cmd.Args = append(cmd.Args, "--envfile", startCmdEnvfileFlag) } if startCmdConfigAdapterFlag != "" { cmd.Args = append(cmd.Args, "--adapter", startCmdConfigAdapterFlag) } if startCmdWatchFlag { cmd.Args = append(cmd.Args, "--watch") } if startCmdPidfileFlag != "" { cmd.Args = append(cmd.Args, "--pidfile", startCmdPidfileFlag) } stdinpipe, err := cmd.StdinPipe() if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("creating stdin pipe: %v", err) } cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr // generate the random bytes we'll send to the child process expect := make([]byte, 32) _, err = rand.Read(expect) if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("generating random confirmation bytes: %v", err) } // begin writing the confirmation bytes to the child's // stdin; use a goroutine since the child hasn't been // started yet, and writing synchronously would result // in a deadlock go func() { _, _ = stdinpipe.Write(expect) stdinpipe.Close() }() // start the process err = cmd.Start() if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("starting caddy process: %v", err) } // there are two ways we know we're done: either // the process will connect to our listener, or // it will exit with an error success, exit := make(chan struct{}), make(chan error) // in one goroutine, we await the success of the child process go func() { for { conn, err := ln.Accept() if err != nil { if !errors.Is(err, net.ErrClosed) { log.Println(err) } break } err = handlePingbackConn(conn, expect) if err == nil { close(success) break } log.Println(err) } }() // in another goroutine, we await the failure of the child process go func() { err := cmd.Wait() // don't send on this line! Wait blocks, but send starts before it unblocks exit <- err // sending on separate line ensures select won't trigger until after Wait unblocks }() // when one of the goroutines unblocks, we're done and can exit select { case <-success: fmt.Printf("Successfully started Caddy (pid=%d) - Caddy is running in the background\n", cmd.Process.Pid) case err := <-exit: return caddy.ExitCodeFailedStartup, fmt.Errorf("caddy process exited with error: %v", err) } return caddy.ExitCodeSuccess, nil } func cmdRun(fl Flags) (int, error) { caddy.TrapSignals() runCmdConfigFlag := fl.String("config") runCmdConfigAdapterFlag := fl.String("adapter") runCmdResumeFlag := fl.Bool("resume") runCmdLoadEnvfileFlag := fl.String("envfile") runCmdPrintEnvFlag := fl.Bool("environ") runCmdWatchFlag := fl.Bool("watch") runCmdPidfileFlag := fl.String("pidfile") runCmdPingbackFlag := fl.String("pingback") // load all additional envs as soon as possible if runCmdLoadEnvfileFlag != "" { if err := loadEnvFromFile(runCmdLoadEnvfileFlag); err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("loading additional environment variables: %v", err) } } // if we are supposed to print the environment, do that first if runCmdPrintEnvFlag { printEnvironment() } // load the config, depending on flags var config []byte var err error if runCmdResumeFlag { config, err = os.ReadFile(caddy.ConfigAutosavePath) if os.IsNotExist(err) { // not a bad error; just can't resume if autosave file doesn't exist caddy.Log().Info("no autosave file exists", zap.String("autosave_file", caddy.ConfigAutosavePath)) runCmdResumeFlag = false } else if err != nil { return caddy.ExitCodeFailedStartup, err } else { if runCmdConfigFlag == "" { caddy.Log().Info("resuming from last configuration", zap.String("autosave_file", caddy.ConfigAutosavePath)) } else { // if they also specified a config file, user should be aware that we're not // using it (doing so could lead to data/config loss by overwriting!) caddy.Log().Warn("--config and --resume flags were used together; ignoring --config and resuming from last configuration", zap.String("autosave_file", caddy.ConfigAutosavePath)) } } } // we don't use 'else' here since this value might have been changed in 'if' block; i.e. not mutually exclusive var configFile string if !runCmdResumeFlag { config, configFile, err = LoadConfig(runCmdConfigFlag, runCmdConfigAdapterFlag) if err != nil { return caddy.ExitCodeFailedStartup, err } } // create pidfile now, in case loading config takes a while (issue #5477) if runCmdPidfileFlag != "" { err := caddy.PIDFile(runCmdPidfileFlag) if err != nil { caddy.Log().Error("unable to write PID file", zap.String("pidfile", runCmdPidfileFlag), zap.Error(err)) } } // run the initial config err = caddy.Load(config, true) if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("loading initial config: %v", err) } caddy.Log().Info("serving initial configuration") // if we are to report to another process the successful start // of the server, do so now by echoing back contents of stdin if runCmdPingbackFlag != "" { confirmationBytes, err := io.ReadAll(os.Stdin) if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("reading confirmation bytes from stdin: %v", err) } conn, err := net.Dial("tcp", runCmdPingbackFlag) if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("dialing confirmation address: %v", err) } defer conn.Close() _, err = conn.Write(confirmationBytes) if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("writing confirmation bytes to %s: %v", runCmdPingbackFlag, err) } } // if enabled, reload config file automatically on changes // (this better only be used in dev!) if runCmdWatchFlag { go watchConfigFile(configFile, runCmdConfigAdapterFlag) } // warn if the environment does not provide enough information about the disk hasXDG := os.Getenv("XDG_DATA_HOME") != "" && os.Getenv("XDG_CONFIG_HOME") != "" && os.Getenv("XDG_CACHE_HOME") != "" switch runtime.GOOS { case "windows": if os.Getenv("HOME") == "" && os.Getenv("USERPROFILE") == "" && !hasXDG { caddy.Log().Warn("neither HOME nor USERPROFILE environment variables are set - please fix; some assets might be stored in ./caddy") } case "plan9": if os.Getenv("home") == "" && !hasXDG { caddy.Log().Warn("$home environment variable is empty - please fix; some assets might be stored in ./caddy") } default: if os.Getenv("HOME") == "" && !hasXDG { caddy.Log().Warn("$HOME environment variable is empty - please fix; some assets might be stored in ./caddy") } } select {} } func cmdStop(fl Flags) (int, error) { addrFlag := fl.String("address") configFlag := fl.String("config") configAdapterFlag := fl.String("adapter") adminAddr, err := DetermineAdminAPIAddress(addrFlag, nil, configFlag, configAdapterFlag) if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("couldn't determine admin API address: %v", err) } resp, err := AdminAPIRequest(adminAddr, http.MethodPost, "/stop", nil, nil) if err != nil { caddy.Log().Warn("failed using API to stop instance", zap.Error(err)) return caddy.ExitCodeFailedStartup, err } defer resp.Body.Close() return caddy.ExitCodeSuccess, nil } func cmdReload(fl Flags) (int, error) { configFlag := fl.String("config") configAdapterFlag := fl.String("adapter") addrFlag := fl.String("address") forceFlag := fl.Bool("force") // get the config in caddy's native format config, configFile, err := LoadConfig(configFlag, configAdapterFlag) if err != nil { return caddy.ExitCodeFailedStartup, err } if configFile == "" { return caddy.ExitCodeFailedStartup, fmt.Errorf("no config file to load") } adminAddr, err := DetermineAdminAPIAddress(addrFlag, config, configFlag, configAdapterFlag) if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("couldn't determine admin API address: %v", err) } // optionally force a config reload headers := make(http.Header) if forceFlag { headers.Set("Cache-Control", "must-revalidate") } resp, err := AdminAPIRequest(adminAddr, http.MethodPost, "/load", headers, bytes.NewReader(config)) if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("sending configuration to instance: %v", err) } defer resp.Body.Close() return caddy.ExitCodeSuccess, nil } func cmdVersion(_ Flags) (int, error) { _, full := caddy.Version() fmt.Println(full) return caddy.ExitCodeSuccess, nil } func cmdBuildInfo(_ Flags) (int, error) { bi, ok := debug.ReadBuildInfo() if !ok { return caddy.ExitCodeFailedStartup, fmt.Errorf("no build information") } fmt.Println(bi) return caddy.ExitCodeSuccess, nil } func cmdListModules(fl Flags) (int, error) { packages := fl.Bool("packages") versions := fl.Bool("versions") skipStandard := fl.Bool("skip-standard") printModuleInfo := func(mi moduleInfo) { fmt.Print(mi.caddyModuleID) if versions && mi.goModule != nil { fmt.Print(" " + mi.goModule.Version) } if packages && mi.goModule != nil { fmt.Print(" " + mi.goModule.Path) if mi.goModule.Replace != nil { fmt.Print(" => " + mi.goModule.Replace.Path) } } if mi.err != nil { fmt.Printf(" [%v]", mi.err) } fmt.Println() } // organize modules by whether they come with the standard distribution standard, nonstandard, unknown, err := getModules() if err != nil { // oh well, just print the module IDs and exit for _, m := range caddy.Modules() { fmt.Println(m) } return caddy.ExitCodeSuccess, nil } // Standard modules (always shipped with Caddy) if !skipStandard { if len(standard) > 0 { for _, mod := range standard { printModuleInfo(mod) } } fmt.Printf("\n Standard modules: %d\n", len(standard)) } // Non-standard modules (third party plugins) if len(nonstandard) > 0 { if len(standard) > 0 && !skipStandard { fmt.Println() } for _, mod := range nonstandard { printModuleInfo(mod) } } fmt.Printf("\n Non-standard modules: %d\n", len(nonstandard)) // Unknown modules (couldn't get Caddy module info) if len(unknown) > 0 { if (len(standard) > 0 && !skipStandard) || len(nonstandard) > 0 { fmt.Println() } for _, mod := range unknown { printModuleInfo(mod) } } fmt.Printf("\n Unknown modules: %d\n", len(unknown)) return caddy.ExitCodeSuccess, nil } func cmdEnviron(_ Flags) (int, error) { printEnvironment() return caddy.ExitCodeSuccess, nil } func cmdAdaptConfig(fl Flags) (int, error) { adaptCmdInputFlag := fl.String("config") adaptCmdAdapterFlag := fl.String("adapter") adaptCmdPrettyFlag := fl.Bool("pretty") adaptCmdValidateFlag := fl.Bool("validate") var err error adaptCmdInputFlag, err = configFileWithRespectToDefault(caddy.Log(), adaptCmdInputFlag) if err != nil { return caddy.ExitCodeFailedStartup, err } if adaptCmdAdapterFlag == "" { return caddy.ExitCodeFailedStartup, fmt.Errorf("adapter name is required (use --adapt flag or leave unspecified for default)") } cfgAdapter := caddyconfig.GetAdapter(adaptCmdAdapterFlag) if cfgAdapter == nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("unrecognized config adapter: %s", adaptCmdAdapterFlag) } input, err := os.ReadFile(adaptCmdInputFlag) if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("reading input file: %v", err) } opts := map[string]any{"filename": adaptCmdInputFlag} adaptedConfig, warnings, err := cfgAdapter.Adapt(input, opts) if err != nil { return caddy.ExitCodeFailedStartup, err } if adaptCmdPrettyFlag { var prettyBuf bytes.Buffer err = json.Indent(&prettyBuf, adaptedConfig, "", "\t") if err != nil { return caddy.ExitCodeFailedStartup, err } adaptedConfig = prettyBuf.Bytes() } // print result to stdout fmt.Println(string(adaptedConfig)) // print warnings to stderr for _, warn := range warnings { msg := warn.Message if warn.Directive != "" { msg = fmt.Sprintf("%s: %s", warn.Directive, warn.Message) } caddy.Log().Named(adaptCmdAdapterFlag).Warn(msg, zap.String("file", warn.File), zap.Int("line", warn.Line)) } // validate output if requested if adaptCmdValidateFlag { var cfg *caddy.Config err = caddy.StrictUnmarshalJSON(adaptedConfig, &cfg) if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("decoding config: %v", err) } err = caddy.Validate(cfg) if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("validation: %v", err) } } return caddy.ExitCodeSuccess, nil } func cmdValidateConfig(fl Flags) (int, error) { validateCmdConfigFlag := fl.String("config") validateCmdAdapterFlag := fl.String("adapter") runCmdLoadEnvfileFlag := fl.String("envfile") // load all additional envs as soon as possible if runCmdLoadEnvfileFlag != "" { if err := loadEnvFromFile(runCmdLoadEnvfileFlag); err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("loading additional environment variables: %v", err) } } // use default config and ensure a config file is specified var err error validateCmdConfigFlag, err = configFileWithRespectToDefault(caddy.Log(), validateCmdConfigFlag) if err != nil { return caddy.ExitCodeFailedStartup, err } if validateCmdConfigFlag == "" { return caddy.ExitCodeFailedStartup, fmt.Errorf("input file required when there is no Caddyfile in current directory (use --config flag)") } input, _, err := LoadConfig(validateCmdConfigFlag, validateCmdAdapterFlag) if err != nil { return caddy.ExitCodeFailedStartup, err } input = caddy.RemoveMetaFields(input) var cfg *caddy.Config err = caddy.StrictUnmarshalJSON(input, &cfg) if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("decoding config: %v", err) } err = caddy.Validate(cfg) if err != nil { return caddy.ExitCodeFailedStartup, err } fmt.Println("Valid configuration") return caddy.ExitCodeSuccess, nil } func cmdFmt(fl Flags) (int, error) { formatCmdConfigFile := fl.Arg(0) if formatCmdConfigFile == "" { formatCmdConfigFile = "Caddyfile" } // as a special case, read from stdin if the file name is "-" if formatCmdConfigFile == "-" { input, err := io.ReadAll(os.Stdin) if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("reading stdin: %v", err) } fmt.Print(string(caddyfile.Format(input))) return caddy.ExitCodeSuccess, nil } input, err := os.ReadFile(formatCmdConfigFile) if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("reading input file: %v", err) } output := caddyfile.Format(input) if fl.Bool("overwrite") { if err := os.WriteFile(formatCmdConfigFile, output, 0o600); err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("overwriting formatted file: %v", err) } return caddy.ExitCodeSuccess, nil } if fl.Bool("diff") { diff := difflib.Diff( strings.Split(string(input), "\n"), strings.Split(string(output), "\n")) 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) } } } else { fmt.Print(string(output)) } if warning, diff := caddyfile.FormattingDifference(formatCmdConfigFile, input); diff { return caddy.ExitCodeFailedStartup, fmt.Errorf(`%s:%d: Caddyfile input is not formatted; Tip: use '--overwrite' to update your Caddyfile in-place instead of previewing it. Consult '--help' for more options`, warning.File, warning.Line, ) } return caddy.ExitCodeSuccess, nil } // AdminAPIRequest makes an API request according to the CLI flags given, // with the given HTTP method and request URI. If body is non-nil, it will // be assumed to be Content-Type application/json. The caller should close // the response body. Should only be used by Caddy CLI commands which // need to interact with a running instance of Caddy via the admin API. func AdminAPIRequest(adminAddr, method, uri string, headers http.Header, body io.Reader) (*http.Response, error) { parsedAddr, err := caddy.ParseNetworkAddress(adminAddr) if err != nil || parsedAddr.PortRangeSize() > 1 { return nil, fmt.Errorf("invalid admin address %s: %v", adminAddr, err) } origin := "http://" + parsedAddr.JoinHostPort(0) if parsedAddr.IsUnixNetwork() { origin = "http://127.0.0.1" // bogus host is a hack so that http.NewRequest() is happy // the unix address at this point might still contain the optional // unix socket permissions, which are part of the address/host. // those need to be removed first, as they aren't part of the // resulting unix file path addr, _, err := internal.SplitUnixSocketPermissionsBits(parsedAddr.Host) if err != nil { return nil, err } parsedAddr.Host = addr } // form the request req, err := http.NewRequest(method, origin+uri, body) if err != nil { return nil, fmt.Errorf("making request: %v", err) } if parsedAddr.IsUnixNetwork() { // We used to conform to RFC 2616 Section 14.26 which requires // an empty host header when there is no host, as is the case // with unix sockets. However, Go required a Host value so we // used a hack of a space character as the host (it would see // the Host was non-empty, then trim the space later). As of // Go 1.20.6 (July 2023), this hack no longer works. See: // https://github.com/golang/go/issues/60374 // See also the discussion here: // https://github.com/golang/go/issues/61431 // // After that, we now require a Host value of either 127.0.0.1 // or ::1 if one is set. Above I choose to use 127.0.0.1. Even // though the value should be completely irrelevant (it could be // "srldkjfsd"), if for some reason the Host *is* used, at least // we can have some reasonable assurance it will stay on the local // machine and that browsers, if they ever allow access to unix // sockets, can still enforce CORS, ensuring it is still coming // from the local machine. } else { req.Header.Set("Origin", origin) } if body != nil { req.Header.Set("Content-Type", "application/json") } for k, v := range headers { req.Header[k] = v } // make an HTTP client that dials our network type, since admin // endpoints aren't always TCP, which is what the default transport // expects; reuse is not of particular concern here client := http.Client{ Transport: &http.Transport{ DialContext: func(_ context.Context, _, _ string) (net.Conn, error) { return net.Dial(parsedAddr.Network, parsedAddr.JoinHostPort(0)) }, }, } resp, err := client.Do(req) if err != nil { return nil, fmt.Errorf("performing request: %v", err) } // if it didn't work, let the user know if resp.StatusCode >= 400 { respBody, err := io.ReadAll(io.LimitReader(resp.Body, 1024*10)) if err != nil { return nil, fmt.Errorf("HTTP %d: reading error message: %v", resp.StatusCode, err) } return nil, fmt.Errorf("caddy responded with error: HTTP %d: %s", resp.StatusCode, respBody) } return resp, nil } // DetermineAdminAPIAddress determines which admin API endpoint address should // be used based on the inputs. By priority: if `address` is specified, then // it is returned; if `config` is specified, then that config will be used for // finding the admin address; if `configFile` (and `configAdapter`) are specified, // then that config will be loaded to find the admin address; otherwise, the // default admin listen address will be returned. func DetermineAdminAPIAddress(address string, config []byte, configFile, configAdapter string) (string, error) { // Prefer the address if specified and non-empty if address != "" { return address, nil } // Try to load the config from file if specified, with the given adapter name if configFile != "" { var loadedConfigFile string var err error // use the provided loaded config if non-empty // otherwise, load it from the specified file/adapter loadedConfig := config if len(loadedConfig) == 0 { // get the config in caddy's native format loadedConfig, loadedConfigFile, err = LoadConfig(configFile, configAdapter) if err != nil { return "", err } if loadedConfigFile == "" { return "", fmt.Errorf("no config file to load; either use --config flag or ensure Caddyfile exists in current directory") } } // get the address of the admin listener from the config if len(loadedConfig) > 0 { var tmpStruct struct { Admin caddy.AdminConfig `json:"admin"` } err := json.Unmarshal(loadedConfig, &tmpStruct) if err != nil { return "", fmt.Errorf("unmarshaling admin listener address from config: %v", err) } if tmpStruct.Admin.Listen != "" { return tmpStruct.Admin.Listen, nil } } } // Fallback to the default listen address otherwise return caddy.DefaultAdminListen, nil } // configFileWithRespectToDefault returns the filename to use for loading the config, based // on whether a config file is already specified and a supported default config file exists. func configFileWithRespectToDefault(logger *zap.Logger, configFile string) (string, error) { const defaultCaddyfile = "Caddyfile" // if no input file was specified, try a default Caddyfile if the Caddyfile adapter is plugged in if configFile == "" && caddyconfig.GetAdapter("caddyfile") != nil { _, err := os.Stat(defaultCaddyfile) if err == nil { // default Caddyfile exists if logger != nil { logger.Info("using adjacent Caddyfile") } return defaultCaddyfile, nil } if !errors.Is(err, fs.ErrNotExist) { // problem checking return configFile, fmt.Errorf("checking if default Caddyfile exists: %v", err) } } // default config file does not exist or is irrelevant return configFile, nil } type moduleInfo struct { caddyModuleID string goModule *debug.Module err error }
Go
caddy/cmd/commands.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 caddycmd import ( "flag" "fmt" "os" "regexp" "strings" "github.com/spf13/cobra" "github.com/spf13/cobra/doc" "github.com/caddyserver/caddy/v2" ) // Command represents a subcommand. Name, Func, // and Short are required. type Command struct { // The name of the subcommand. Must conform to the // format described by the RegisterCommand() godoc. // Required. Name string // Usage is a brief message describing the syntax of // the subcommand's flags and args. Use [] to indicate // optional parameters and <> to enclose literal values // intended to be replaced by the user. Do not prefix // the string with "caddy" or the name of the command // since these will be prepended for you; only include // the actual parameters for this command. Usage string // Short is a one-line message explaining what the // command does. Should not end with punctuation. // Required. Short string // Long is the full help text shown to the user. // Will be trimmed of whitespace on both ends before // being printed. Long string // Flags is the flagset for command. // This is ignored if CobraFunc is set. Flags *flag.FlagSet // Func is a function that executes a subcommand using // the parsed flags. It returns an exit code and any // associated error. // Required if CobraFunc is not set. Func CommandFunc // CobraFunc allows further configuration of the command // via cobra's APIs. If this is set, then Func and Flags // are ignored, with the assumption that they are set in // this function. A caddycmd.WrapCommandFuncForCobra helper // exists to simplify porting CommandFunc to Cobra's RunE. CobraFunc func(*cobra.Command) } // CommandFunc is a command's function. It runs the // command and returns the proper exit code along with // any error that occurred. type CommandFunc func(Flags) (int, error) // Commands returns a list of commands initialised by // RegisterCommand func Commands() map[string]Command { return commands } var commands = make(map[string]Command) func init() { RegisterCommand(Command{ Name: "start", Usage: "[--config <path> [--adapter <name>]] [--envfile <path>] [--watch] [--pidfile <file>]", Short: "Starts the Caddy process in the background and then returns", Long: ` Starts the Caddy process, optionally bootstrapped with an initial config file. This command unblocks after the server starts running or fails to run. If --envfile is specified, an environment file with environment variables in the KEY=VALUE format will be loaded into the Caddy process. On Windows, the spawned child process will remain attached to the terminal, so closing the window will forcefully stop Caddy; to avoid forgetting this, try using 'caddy run' instead to keep it in the foreground. `, CobraFunc: func(cmd *cobra.Command) { cmd.Flags().StringP("config", "c", "", "Configuration file") cmd.Flags().StringP("adapter", "a", "", "Name of config adapter to apply") cmd.Flags().StringP("envfile", "", "", "Environment file to load") cmd.Flags().BoolP("watch", "w", false, "Reload changed config file automatically") cmd.Flags().StringP("pidfile", "", "", "Path of file to which to write process ID") cmd.RunE = WrapCommandFuncForCobra(cmdStart) }, }) RegisterCommand(Command{ Name: "run", Usage: "[--config <path> [--adapter <name>]] [--envfile <path>] [--environ] [--resume] [--watch] [--pidfile <file>]", Short: `Starts the Caddy process and blocks indefinitely`, Long: ` Starts the Caddy process, optionally bootstrapped with an initial config file, and blocks indefinitely until the server is stopped; i.e. runs Caddy in "daemon" mode (foreground). If a config file is specified, it will be applied immediately after the process is running. If the config file is not in Caddy's native JSON format, you can specify an adapter with --adapter to adapt the given config file to Caddy's native format. The config adapter must be a registered module. Any warnings will be printed to the log, but beware that any adaptation without errors will immediately be used. If you want to review the results of the adaptation first, use the 'adapt' subcommand. As a special case, if the current working directory has a file called "Caddyfile" and the caddyfile config adapter is plugged in (default), then that file will be loaded and used to configure Caddy, even without any command line flags. If --envfile is specified, an environment file with environment variables in the KEY=VALUE format will be loaded into the Caddy process. If --environ is specified, the environment as seen by the Caddy process will be printed before starting. This is the same as the environ command but does not quit after printing, and can be useful for troubleshooting. The --resume flag will override the --config flag if there is a config auto- save file. It is not an error if --resume is used and no autosave file exists. If --watch is specified, the config file will be loaded automatically after changes. โš ๏ธ This can make unintentional config changes easier; only use this option in a local development environment. `, CobraFunc: func(cmd *cobra.Command) { cmd.Flags().StringP("config", "c", "", "Configuration file") cmd.Flags().StringP("adapter", "a", "", "Name of config adapter to apply") cmd.Flags().StringP("envfile", "", "", "Environment file to load") cmd.Flags().BoolP("environ", "e", false, "Print environment") cmd.Flags().BoolP("resume", "r", false, "Use saved config, if any (and prefer over --config file)") cmd.Flags().BoolP("watch", "w", false, "Watch config file for changes and reload it automatically") cmd.Flags().StringP("pidfile", "", "", "Path of file to which to write process ID") cmd.Flags().StringP("pingback", "", "", "Echo confirmation bytes to this address on success") cmd.RunE = WrapCommandFuncForCobra(cmdRun) }, }) RegisterCommand(Command{ Name: "stop", Usage: "[--config <path> [--adapter <name>]] [--address <interface>]", Short: "Gracefully stops a started Caddy process", Long: ` Stops the background Caddy process as gracefully as possible. It requires that the admin API is enabled and accessible, since it will use the API's /stop endpoint. The address of this request can be customized using the --address flag, or from the given --config, if not the default. `, CobraFunc: func(cmd *cobra.Command) { cmd.Flags().StringP("config", "c", "", "Configuration file to use to parse the admin address, if --address is not used") cmd.Flags().StringP("adapter", "a", "", "Name of config adapter to apply (when --config is used)") cmd.Flags().StringP("address", "", "", "The address to use to reach the admin API endpoint, if not the default") cmd.RunE = WrapCommandFuncForCobra(cmdStop) }, }) RegisterCommand(Command{ Name: "reload", Usage: "--config <path> [--adapter <name>] [--address <interface>]", Short: "Changes the config of the running Caddy instance", Long: ` Gives the running Caddy instance a new configuration. This has the same effect as POSTing a document to the /load API endpoint, but is convenient for simple workflows revolving around config files. Since the admin endpoint is configurable, the endpoint configuration is loaded from the --address flag if specified; otherwise it is loaded from the given config file; otherwise the default is assumed. `, CobraFunc: func(cmd *cobra.Command) { cmd.Flags().StringP("config", "c", "", "Configuration file (required)") cmd.Flags().StringP("adapter", "a", "", "Name of config adapter to apply") cmd.Flags().StringP("address", "", "", "Address of the administration listener, if different from config") cmd.Flags().BoolP("force", "f", false, "Force config reload, even if it is the same") cmd.RunE = WrapCommandFuncForCobra(cmdReload) }, }) RegisterCommand(Command{ Name: "version", Short: "Prints the version", Long: ` Prints the version of this Caddy binary. Version information must be embedded into the binary at compile-time in order for Caddy to display anything useful with this command. If Caddy is built from within a version control repository, the Go command will embed the revision hash if available. However, if Caddy is built in the way specified by our online documentation (or by using xcaddy), more detailed version information is printed as given by Go modules. For more details about the full version string, see the Go module documentation: https://go.dev/doc/modules/version-numbers `, Func: cmdVersion, }) RegisterCommand(Command{ Name: "list-modules", Usage: "[--packages] [--versions] [--skip-standard]", Short: "Lists the installed Caddy modules", CobraFunc: func(cmd *cobra.Command) { cmd.Flags().BoolP("packages", "", false, "Print package paths") cmd.Flags().BoolP("versions", "", false, "Print version information") cmd.Flags().BoolP("skip-standard", "s", false, "Skip printing standard modules") cmd.RunE = WrapCommandFuncForCobra(cmdListModules) }, }) RegisterCommand(Command{ Name: "build-info", Short: "Prints information about this build", Func: cmdBuildInfo, }) RegisterCommand(Command{ Name: "environ", Short: "Prints the environment", Long: ` Prints the environment as seen by this Caddy process. The environment includes variables set in the system. If your Caddy configuration uses environment variables (e.g. "{env.VARIABLE}") then this command can be useful for verifying that the variables will have the values you expect in your config. Note that environments may be different depending on how you run Caddy. Environments for Caddy instances started by service managers such as systemd are often different than the environment inherited from your shell or terminal. You can also print the environment the same time you use "caddy run" by adding the "--environ" flag. Environments may contain sensitive data. `, Func: cmdEnviron, }) RegisterCommand(Command{ Name: "adapt", Usage: "--config <path> [--adapter <name>] [--pretty] [--validate]", Short: "Adapts a configuration to Caddy's native JSON", Long: ` Adapts a configuration to Caddy's native JSON format and writes the output to stdout, along with any warnings to stderr. If --pretty is specified, the output will be formatted with indentation for human readability. If --validate is used, the adapted config will be checked for validity. If the config is invalid, an error will be printed to stderr and a non- zero exit status will be returned. `, CobraFunc: func(cmd *cobra.Command) { cmd.Flags().StringP("config", "c", "", "Configuration file to adapt (required)") cmd.Flags().StringP("adapter", "a", "caddyfile", "Name of config adapter") cmd.Flags().BoolP("pretty", "p", false, "Format the output for human readability") cmd.Flags().BoolP("validate", "", false, "Validate the output") cmd.RunE = WrapCommandFuncForCobra(cmdAdaptConfig) }, }) RegisterCommand(Command{ Name: "validate", Usage: "--config <path> [--adapter <name>] [--envfile <path>]", Short: "Tests whether a configuration file is valid", Long: ` Loads and provisions the provided config, but does not start running it. This reveals any errors with the configuration through the loading and provisioning stages. If --envfile is specified, an environment file with environment variables in the KEY=VALUE format will be loaded into the Caddy process. `, CobraFunc: func(cmd *cobra.Command) { cmd.Flags().StringP("config", "c", "", "Input configuration file") cmd.Flags().StringP("adapter", "a", "", "Name of config adapter") cmd.Flags().StringP("envfile", "", "", "Environment file to load") cmd.RunE = WrapCommandFuncForCobra(cmdValidateConfig) }, }) RegisterCommand(Command{ Name: "storage", Short: "Commands for working with Caddy's storage (EXPERIMENTAL)", Long: ` Allows exporting and importing Caddy's storage contents. The two commands can be combined in a pipeline to transfer directly from one storage to another: $ caddy storage export --config Caddyfile.old --output - | > caddy storage import --config Caddyfile.new --input - The - argument refers to stdout and stdin, respectively. NOTE: When importing to or exporting from file_system storage (the default), the command should be run as the user that owns the associated root path. EXPERIMENTAL: May be changed or removed. `, CobraFunc: func(cmd *cobra.Command) { exportCmd := &cobra.Command{ Use: "export --config <path> --output <path>", Short: "Exports storage assets as a tarball", Long: ` The contents of the configured storage module (TLS certificates, etc) are exported via a tarball. --output is required, - can be given for stdout. `, RunE: WrapCommandFuncForCobra(cmdExportStorage), } exportCmd.Flags().StringP("config", "c", "", "Input configuration file (required)") exportCmd.Flags().StringP("output", "o", "", "Output path") cmd.AddCommand(exportCmd) importCmd := &cobra.Command{ Use: "import --config <path> --input <path>", Short: "Imports storage assets from a tarball.", Long: ` Imports storage assets to the configured storage module. The import file must be a tar archive. --input is required, - can be given for stdin. `, RunE: WrapCommandFuncForCobra(cmdImportStorage), } importCmd.Flags().StringP("config", "c", "", "Configuration file to load (required)") importCmd.Flags().StringP("input", "i", "", "Tar of assets to load (required)") cmd.AddCommand(importCmd) }, }) RegisterCommand(Command{ Name: "fmt", Usage: "[--overwrite] [--diff] [<path>]", Short: "Formats a Caddyfile", Long: ` Formats the Caddyfile by adding proper indentation and spaces to improve human readability. It prints the result to stdout. If --overwrite is specified, the output will be written to the config file directly instead of printing it. If --diff is specified, the output will be compared against the input, and lines will be prefixed with '-' and '+' where they differ. Note that unchanged lines are prefixed with two spaces for alignment, and that this is not a valid patch format. If you wish you use stdin instead of a regular file, use - as the path. When reading from stdin, the --overwrite flag has no effect: the result is always printed to stdout. `, CobraFunc: func(cmd *cobra.Command) { cmd.Flags().BoolP("overwrite", "w", false, "Overwrite the input file with the results") cmd.Flags().BoolP("diff", "d", false, "Print the differences between the input file and the formatted output") cmd.RunE = WrapCommandFuncForCobra(cmdFmt) }, }) RegisterCommand(Command{ Name: "upgrade", Short: "Upgrade Caddy (EXPERIMENTAL)", Long: ` Downloads an updated Caddy binary with the same modules/plugins at the latest versions. EXPERIMENTAL: May be changed or removed. `, CobraFunc: func(cmd *cobra.Command) { cmd.Flags().BoolP("keep-backup", "k", false, "Keep the backed up binary, instead of deleting it") cmd.RunE = WrapCommandFuncForCobra(cmdUpgrade) }, }) RegisterCommand(Command{ Name: "add-package", Usage: "<packages...>", Short: "Adds Caddy packages (EXPERIMENTAL)", Long: ` Downloads an updated Caddy binary with the specified packages (module/plugin) added. Retains existing packages. Returns an error if the any of packages are already included. EXPERIMENTAL: May be changed or removed. `, CobraFunc: func(cmd *cobra.Command) { cmd.Flags().BoolP("keep-backup", "k", false, "Keep the backed up binary, instead of deleting it") cmd.RunE = WrapCommandFuncForCobra(cmdAddPackage) }, }) RegisterCommand(Command{ Name: "remove-package", Func: cmdRemovePackage, Usage: "<packages...>", Short: "Removes Caddy packages (EXPERIMENTAL)", Long: ` Downloads an updated Caddy binaries without the specified packages (module/plugin). Returns an error if any of the packages are not included. EXPERIMENTAL: May be changed or removed. `, CobraFunc: func(cmd *cobra.Command) { cmd.Flags().BoolP("keep-backup", "k", false, "Keep the backed up binary, instead of deleting it") cmd.RunE = WrapCommandFuncForCobra(cmdRemovePackage) }, }) RegisterCommand(Command{ Name: "manpage", Usage: "--directory <path>", Short: "Generates the manual pages for Caddy commands", Long: ` Generates the manual pages for Caddy commands into the designated directory tagged into section 8 (System Administration). The manual page files are generated into the directory specified by the argument of --directory. If the directory does not exist, it will be created. `, CobraFunc: func(cmd *cobra.Command) { cmd.Flags().StringP("directory", "o", "", "The output directory where the manpages are generated") cmd.RunE = WrapCommandFuncForCobra(func(fl Flags) (int, error) { dir := strings.TrimSpace(fl.String("directory")) if dir == "" { return caddy.ExitCodeFailedQuit, fmt.Errorf("designated output directory and specified section are required") } if err := os.MkdirAll(dir, 0o755); err != nil { return caddy.ExitCodeFailedQuit, err } if err := doc.GenManTree(rootCmd, &doc.GenManHeader{ Title: "Caddy", Section: "8", // https://en.wikipedia.org/wiki/Man_page#Manual_sections }, dir); err != nil { return caddy.ExitCodeFailedQuit, err } return caddy.ExitCodeSuccess, nil }) }, }) // source: https://github.com/spf13/cobra/blob/main/shell_completions.md rootCmd.AddCommand(&cobra.Command{ Use: "completion [bash|zsh|fish|powershell]", Short: "Generate completion script", Long: fmt.Sprintf(`To load completions: Bash: $ source <(%[1]s completion bash) # To load completions for each session, execute once: # Linux: $ %[1]s completion bash > /etc/bash_completion.d/%[1]s # macOS: $ %[1]s completion bash > $(brew --prefix)/etc/bash_completion.d/%[1]s Zsh: # If shell completion is not already enabled in your environment, # you will need to enable it. You can execute the following once: $ echo "autoload -U compinit; compinit" >> ~/.zshrc # To load completions for each session, execute once: $ %[1]s completion zsh > "${fpath[1]}/_%[1]s" # You will need to start a new shell for this setup to take effect. fish: $ %[1]s completion fish | source # To load completions for each session, execute once: $ %[1]s completion fish > ~/.config/fish/completions/%[1]s.fish PowerShell: PS> %[1]s completion powershell | Out-String | Invoke-Expression # To load completions for every new session, run: PS> %[1]s completion powershell > %[1]s.ps1 # and source this file from your PowerShell profile. `, rootCmd.Root().Name()), DisableFlagsInUseLine: true, ValidArgs: []string{"bash", "zsh", "fish", "powershell"}, Args: cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs), RunE: func(cmd *cobra.Command, args []string) error { switch args[0] { case "bash": return cmd.Root().GenBashCompletion(os.Stdout) case "zsh": return cmd.Root().GenZshCompletion(os.Stdout) case "fish": return cmd.Root().GenFishCompletion(os.Stdout, true) case "powershell": return cmd.Root().GenPowerShellCompletionWithDesc(os.Stdout) default: return fmt.Errorf("unrecognized shell: %s", args[0]) } }, }) } // RegisterCommand registers the command cmd. // cmd.Name must be unique and conform to the // following format: // // - lowercase // - alphanumeric and hyphen characters only // - cannot start or end with a hyphen // - hyphen cannot be adjacent to another hyphen // // This function panics if the name is already registered, // if the name does not meet the described format, or if // any of the fields are missing from cmd. // // This function should be used in init(). func RegisterCommand(cmd Command) { if cmd.Name == "" { panic("command name is required") } if cmd.Func == nil && cmd.CobraFunc == nil { panic("command function missing") } if cmd.Short == "" { panic("command short string is required") } if _, exists := commands[cmd.Name]; exists { panic("command already registered: " + cmd.Name) } if !commandNameRegex.MatchString(cmd.Name) { panic("invalid command name") } rootCmd.AddCommand(caddyCmdToCobra(cmd)) } var commandNameRegex = regexp.MustCompile(`^[a-z0-9]$|^([a-z0-9]+-?[a-z0-9]*)+[a-z0-9]$`)
Go
caddy/cmd/main.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 caddycmd import ( "bufio" "bytes" "flag" "fmt" "io" "log" "net" "os" "path/filepath" "runtime" "runtime/debug" "strconv" "strings" "time" "github.com/caddyserver/certmagic" "github.com/spf13/pflag" "go.uber.org/zap" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" ) func init() { // set a fitting User-Agent for ACME requests version, _ := caddy.Version() cleanModVersion := strings.TrimPrefix(version, "v") ua := "Caddy/" + cleanModVersion if uaEnv, ok := os.LookupEnv("USERAGENT"); ok { ua = uaEnv + " " + ua } certmagic.UserAgent = ua // by using Caddy, user indicates agreement to CA terms // (very important, as Caddy is often non-interactive // and thus ACME account creation will fail!) certmagic.DefaultACME.Agreed = true } // Main implements the main function of the caddy command. // Call this if Caddy is to be the main() of your program. func Main() { if len(os.Args) == 0 { fmt.Printf("[FATAL] no arguments provided by OS; args[0] must be command\n") os.Exit(caddy.ExitCodeFailedStartup) } if err := rootCmd.Execute(); err != nil { os.Exit(1) } } // handlePingbackConn reads from conn and ensures it matches // the bytes in expect, or returns an error if it doesn't. func handlePingbackConn(conn net.Conn, expect []byte) error { defer conn.Close() confirmationBytes, err := io.ReadAll(io.LimitReader(conn, 32)) if err != nil { return err } if !bytes.Equal(confirmationBytes, expect) { return fmt.Errorf("wrong confirmation: %x", confirmationBytes) } return nil } // LoadConfig loads the config from configFile and adapts it // using adapterName. If adapterName is specified, configFile // must be also. If no configFile is specified, it tries // loading a default config file. The lack of a config file is // not treated as an error, but false will be returned if // there is no config available. It prints any warnings to stderr, // and returns the resulting JSON config bytes along with // the name of the loaded config file (if any). func LoadConfig(configFile, adapterName string) ([]byte, string, error) { return loadConfigWithLogger(caddy.Log(), configFile, adapterName) } func loadConfigWithLogger(logger *zap.Logger, configFile, adapterName string) ([]byte, string, error) { // specifying an adapter without a config file is ambiguous if adapterName != "" && configFile == "" { return nil, "", fmt.Errorf("cannot adapt config without config file (use --config)") } // load initial config and adapter var config []byte var cfgAdapter caddyconfig.Adapter var err error if configFile != "" { if configFile == "-" { config, err = io.ReadAll(os.Stdin) } else { config, err = os.ReadFile(configFile) } if err != nil { return nil, "", fmt.Errorf("reading config file: %v", err) } if logger != nil { logger.Info("using provided configuration", zap.String("config_file", configFile), zap.String("config_adapter", adapterName)) } } else if adapterName == "" { // if the Caddyfile adapter is plugged in, we can try using an // adjacent Caddyfile by default cfgAdapter = caddyconfig.GetAdapter("caddyfile") if cfgAdapter != nil { config, err = os.ReadFile("Caddyfile") if os.IsNotExist(err) { // okay, no default Caddyfile; pretend like this never happened cfgAdapter = nil } else if err != nil { // default Caddyfile exists, but error reading it return nil, "", fmt.Errorf("reading default Caddyfile: %v", err) } else { // success reading default Caddyfile configFile = "Caddyfile" if logger != nil { logger.Info("using adjacent Caddyfile") } } } } // as a special case, if a config file called "Caddyfile" was // specified, and no adapter is specified, assume caddyfile adapter // for convenience if strings.HasPrefix(filepath.Base(configFile), "Caddyfile") && filepath.Ext(configFile) != ".json" && adapterName == "" { adapterName = "caddyfile" } // load config adapter if adapterName != "" { cfgAdapter = caddyconfig.GetAdapter(adapterName) if cfgAdapter == nil { return nil, "", fmt.Errorf("unrecognized config adapter: %s", adapterName) } } // adapt config if cfgAdapter != nil { adaptedConfig, warnings, err := cfgAdapter.Adapt(config, map[string]any{ "filename": configFile, }) if err != nil { return nil, "", fmt.Errorf("adapting config using %s: %v", adapterName, err) } for _, warn := range warnings { msg := warn.Message if warn.Directive != "" { msg = fmt.Sprintf("%s: %s", warn.Directive, warn.Message) } if logger != nil { logger.Warn(msg, zap.String("adapter", adapterName), zap.String("file", warn.File), zap.Int("line", warn.Line)) } } config = adaptedConfig } return config, configFile, nil } // watchConfigFile watches the config file at filename for changes // and reloads the config if the file was updated. This function // blocks indefinitely; it only quits if the poller has errors for // long enough time. The filename passed in must be the actual // config file used, not one to be discovered. // Each second the config files is loaded and parsed into an object // and is compared to the last config object that was loaded func watchConfigFile(filename, adapterName string) { defer func() { if err := recover(); err != nil { log.Printf("[PANIC] watching config file: %v\n%s", err, debug.Stack()) } }() // make our logger; since config reloads can change the // default logger, we need to get it dynamically each time logger := func() *zap.Logger { return caddy.Log(). Named("watcher"). With(zap.String("config_file", filename)) } // get current config lastCfg, _, err := loadConfigWithLogger(nil, filename, adapterName) if err != nil { logger().Error("unable to load latest config", zap.Error(err)) return } logger().Info("watching config file for changes") // begin poller //nolint:staticcheck for range time.Tick(1 * time.Second) { // get current config newCfg, _, err := loadConfigWithLogger(nil, filename, adapterName) if err != nil { logger().Error("unable to load latest config", zap.Error(err)) return } // if it hasn't changed, nothing to do if bytes.Equal(lastCfg, newCfg) { continue } logger().Info("config file changed; reloading") // remember the current config lastCfg = newCfg // apply the updated config err = caddy.Load(lastCfg, false) if err != nil { logger().Error("applying latest config", zap.Error(err)) continue } } } // Flags wraps a FlagSet so that typed values // from flags can be easily retrieved. type Flags struct { *pflag.FlagSet } // String returns the string representation of the // flag given by name. It panics if the flag is not // in the flag set. func (f Flags) String(name string) string { return f.FlagSet.Lookup(name).Value.String() } // Bool returns the boolean representation of the // flag given by name. It returns false if the flag // is not a boolean type. It panics if the flag is // not in the flag set. func (f Flags) Bool(name string) bool { val, _ := strconv.ParseBool(f.String(name)) return val } // Int returns the integer representation of the // flag given by name. It returns 0 if the flag // is not an integer type. It panics if the flag is // not in the flag set. func (f Flags) Int(name string) int { val, _ := strconv.ParseInt(f.String(name), 0, strconv.IntSize) return int(val) } // Float64 returns the float64 representation of the // flag given by name. It returns false if the flag // is not a float64 type. It panics if the flag is // not in the flag set. func (f Flags) Float64(name string) float64 { val, _ := strconv.ParseFloat(f.String(name), 64) return val } // Duration returns the duration representation of the // flag given by name. It returns false if the flag // is not a duration type. It panics if the flag is // not in the flag set. func (f Flags) Duration(name string) time.Duration { val, _ := caddy.ParseDuration(f.String(name)) return val } func loadEnvFromFile(envFile string) error { file, err := os.Open(envFile) if err != nil { return fmt.Errorf("reading environment file: %v", err) } defer file.Close() envMap, err := parseEnvFile(file) if err != nil { return fmt.Errorf("parsing environment file: %v", err) } for k, v := range envMap { if err := os.Setenv(k, v); err != nil { return fmt.Errorf("setting environment variables: %v", err) } } // Update the storage paths to ensure they have the proper // value after loading a specified env file. caddy.ConfigAutosavePath = filepath.Join(caddy.AppConfigDir(), "autosave.json") caddy.DefaultStorage = &certmagic.FileStorage{Path: caddy.AppDataDir()} return nil } // parseEnvFile parses an env file from KEY=VALUE format. // It's pretty naive. Limited value quotation is supported, // but variable and command expansions are not supported. func parseEnvFile(envInput io.Reader) (map[string]string, error) { envMap := make(map[string]string) scanner := bufio.NewScanner(envInput) var lineNumber int for scanner.Scan() { line := strings.TrimSpace(scanner.Text()) lineNumber++ // skip empty lines and lines starting with comment if line == "" || strings.HasPrefix(line, "#") { continue } // split line into key and value before, after, isCut := strings.Cut(line, "=") if !isCut { return nil, fmt.Errorf("can't parse line %d; line should be in KEY=VALUE format", lineNumber) } key, val := before, after // sometimes keys are prefixed by "export " so file can be sourced in bash; ignore it here key = strings.TrimPrefix(key, "export ") // validate key and value if key == "" { return nil, fmt.Errorf("missing or empty key on line %d", lineNumber) } if strings.Contains(key, " ") { return nil, fmt.Errorf("invalid key on line %d: contains whitespace: %s", lineNumber, key) } if strings.HasPrefix(val, " ") || strings.HasPrefix(val, "\t") { return nil, fmt.Errorf("invalid value on line %d: whitespace before value: '%s'", lineNumber, val) } // remove any trailing comment after value if commentStart, _, found := strings.Cut(val, "#"); found { val = strings.TrimRight(commentStart, " \t") } // quoted value: support newlines if strings.HasPrefix(val, `"`) || strings.HasPrefix(val, "'") { quote := string(val[0]) for !(strings.HasSuffix(line, quote) && !strings.HasSuffix(line, `\`+quote)) { val = strings.ReplaceAll(val, `\`+quote, quote) if !scanner.Scan() { break } lineNumber++ line = strings.ReplaceAll(scanner.Text(), `\`+quote, quote) val += "\n" + line } val = strings.TrimPrefix(val, quote) val = strings.TrimSuffix(val, quote) } envMap[key] = val } if err := scanner.Err(); err != nil { return nil, err } return envMap, nil } func printEnvironment() { _, version := caddy.Version() fmt.Printf("caddy.HomeDir=%s\n", caddy.HomeDir()) fmt.Printf("caddy.AppDataDir=%s\n", caddy.AppDataDir()) fmt.Printf("caddy.AppConfigDir=%s\n", caddy.AppConfigDir()) fmt.Printf("caddy.ConfigAutosavePath=%s\n", caddy.ConfigAutosavePath) fmt.Printf("caddy.Version=%s\n", version) fmt.Printf("runtime.GOOS=%s\n", runtime.GOOS) fmt.Printf("runtime.GOARCH=%s\n", runtime.GOARCH) fmt.Printf("runtime.Compiler=%s\n", runtime.Compiler) fmt.Printf("runtime.NumCPU=%d\n", runtime.NumCPU()) fmt.Printf("runtime.GOMAXPROCS=%d\n", runtime.GOMAXPROCS(0)) fmt.Printf("runtime.Version=%s\n", runtime.Version()) cwd, err := os.Getwd() if err != nil { cwd = fmt.Sprintf("<error: %v>", err) } fmt.Printf("os.Getwd=%s\n\n", cwd) for _, v := range os.Environ() { fmt.Println(v) } } // StringSlice is a flag.Value that enables repeated use of a string flag. type StringSlice []string func (ss StringSlice) String() string { return "[" + strings.Join(ss, ", ") + "]" } func (ss *StringSlice) Set(value string) error { *ss = append(*ss, value) return nil } // Interface guard var _ flag.Value = (*StringSlice)(nil)
Go
caddy/cmd/main_test.go
package caddycmd import ( "reflect" "strings" "testing" ) func TestParseEnvFile(t *testing.T) { for i, tc := range []struct { input string expect map[string]string shouldErr bool }{ { input: `KEY=value`, expect: map[string]string{ "KEY": "value", }, }, { input: ` KEY=value OTHER_KEY=Some Value `, expect: map[string]string{ "KEY": "value", "OTHER_KEY": "Some Value", }, }, { input: ` KEY=value INVALID KEY=asdf OTHER_KEY=Some Value `, shouldErr: true, }, { input: ` KEY=value SIMPLE_QUOTED="quoted value" OTHER_KEY=Some Value `, expect: map[string]string{ "KEY": "value", "SIMPLE_QUOTED": "quoted value", "OTHER_KEY": "Some Value", }, }, { input: ` KEY=value NEWLINES="foo bar" OTHER_KEY=Some Value `, expect: map[string]string{ "KEY": "value", "NEWLINES": "foo\n\tbar", "OTHER_KEY": "Some Value", }, }, { input: ` KEY=value ESCAPED="\"escaped quotes\" here" OTHER_KEY=Some Value `, expect: map[string]string{ "KEY": "value", "ESCAPED": "\"escaped quotes\"\nhere", "OTHER_KEY": "Some Value", }, }, { input: ` export KEY=value OTHER_KEY=Some Value `, expect: map[string]string{ "KEY": "value", "OTHER_KEY": "Some Value", }, }, { input: ` =value OTHER_KEY=Some Value `, shouldErr: true, }, { input: ` EMPTY= OTHER_KEY=Some Value `, expect: map[string]string{ "EMPTY": "", "OTHER_KEY": "Some Value", }, }, { input: ` EMPTY="" OTHER_KEY=Some Value `, expect: map[string]string{ "EMPTY": "", "OTHER_KEY": "Some Value", }, }, { input: ` KEY=value #OTHER_KEY=Some Value `, expect: map[string]string{ "KEY": "value", }, }, { input: ` KEY=value COMMENT=foo bar # some comment here OTHER_KEY=Some Value `, expect: map[string]string{ "KEY": "value", "COMMENT": "foo bar", "OTHER_KEY": "Some Value", }, }, { input: ` KEY=value WHITESPACE= foo OTHER_KEY=Some Value `, shouldErr: true, }, { input: ` KEY=value WHITESPACE=" foo bar " OTHER_KEY=Some Value `, expect: map[string]string{ "KEY": "value", "WHITESPACE": " foo bar ", "OTHER_KEY": "Some Value", }, }, } { actual, err := parseEnvFile(strings.NewReader(tc.input)) if err != nil && !tc.shouldErr { t.Errorf("Test %d: Got error but shouldn't have: %v", i, err) } if err == nil && tc.shouldErr { t.Errorf("Test %d: Did not get error but should have", i) } if tc.shouldErr { continue } if !reflect.DeepEqual(tc.expect, actual) { t.Errorf("Test %d: Expected %v but got %v", i, tc.expect, actual) } } }
Go
caddy/cmd/packagesfuncs.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 caddycmd import ( "encoding/json" "fmt" "io" "net/http" "net/url" "os" "os/exec" "reflect" "runtime" "runtime/debug" "strings" "go.uber.org/zap" "github.com/caddyserver/caddy/v2" ) func cmdUpgrade(fl Flags) (int, error) { _, nonstandard, _, err := getModules() if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("unable to enumerate installed plugins: %v", err) } pluginPkgs, err := getPluginPackages(nonstandard) if err != nil { return caddy.ExitCodeFailedStartup, err } return upgradeBuild(pluginPkgs, fl) } func cmdAddPackage(fl Flags) (int, error) { if len(fl.Args()) == 0 { return caddy.ExitCodeFailedStartup, fmt.Errorf("at least one package name must be specified") } _, nonstandard, _, err := getModules() if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("unable to enumerate installed plugins: %v", err) } pluginPkgs, err := getPluginPackages(nonstandard) if err != nil { return caddy.ExitCodeFailedStartup, err } for _, arg := range fl.Args() { if _, ok := pluginPkgs[arg]; ok { return caddy.ExitCodeFailedStartup, fmt.Errorf("package is already added") } pluginPkgs[arg] = struct{}{} } return upgradeBuild(pluginPkgs, fl) } func cmdRemovePackage(fl Flags) (int, error) { if len(fl.Args()) == 0 { return caddy.ExitCodeFailedStartup, fmt.Errorf("at least one package name must be specified") } _, nonstandard, _, err := getModules() if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("unable to enumerate installed plugins: %v", err) } pluginPkgs, err := getPluginPackages(nonstandard) if err != nil { return caddy.ExitCodeFailedStartup, err } for _, arg := range fl.Args() { if _, ok := pluginPkgs[arg]; !ok { // package does not exist return caddy.ExitCodeFailedStartup, fmt.Errorf("package is not added") } delete(pluginPkgs, arg) } return upgradeBuild(pluginPkgs, fl) } func upgradeBuild(pluginPkgs map[string]struct{}, fl Flags) (int, error) { l := caddy.Log() thisExecPath, err := os.Executable() if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("determining current executable path: %v", err) } thisExecStat, err := os.Stat(thisExecPath) if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("retrieving current executable permission bits: %v", err) } l.Info("this executable will be replaced", zap.String("path", thisExecPath)) // build the request URL to download this custom build qs := url.Values{ "os": {runtime.GOOS}, "arch": {runtime.GOARCH}, } for pkg := range pluginPkgs { qs.Add("p", pkg) } // initiate the build resp, err := downloadBuild(qs) if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("download failed: %v", err) } defer resp.Body.Close() // back up the current binary, in case something goes wrong we can replace it backupExecPath := thisExecPath + ".tmp" l.Info("build acquired; backing up current executable", zap.String("current_path", thisExecPath), zap.String("backup_path", backupExecPath)) err = os.Rename(thisExecPath, backupExecPath) if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("backing up current binary: %v", err) } defer func() { if err != nil { err2 := os.Rename(backupExecPath, thisExecPath) if err2 != nil { l.Error("restoring original executable failed; will need to be restored manually", zap.String("backup_path", backupExecPath), zap.String("original_path", thisExecPath), zap.Error(err2)) } } }() // download the file; do this in a closure to close reliably before we execute it err = writeCaddyBinary(thisExecPath, &resp.Body, thisExecStat) if err != nil { return caddy.ExitCodeFailedStartup, err } l.Info("download successful; displaying new binary details", zap.String("location", thisExecPath)) // use the new binary to print out version and module info fmt.Print("\nModule versions:\n\n") if err = listModules(thisExecPath); err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("download succeeded, but unable to execute 'caddy list-modules': %v", err) } fmt.Println("\nVersion:") if err = showVersion(thisExecPath); err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("download succeeded, but unable to execute 'caddy version': %v", err) } fmt.Println() // clean up the backup file if !fl.Bool("keep-backup") { if err = removeCaddyBinary(backupExecPath); err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("download succeeded, but unable to clean up backup binary: %v", err) } } else { l.Info("skipped cleaning up the backup file", zap.String("backup_path", backupExecPath)) } l.Info("upgrade successful; please restart any running Caddy instances", zap.String("executable", thisExecPath)) return caddy.ExitCodeSuccess, nil } func getModules() (standard, nonstandard, unknown []moduleInfo, err error) { bi, ok := debug.ReadBuildInfo() if !ok { err = fmt.Errorf("no build info") return } for _, modID := range caddy.Modules() { modInfo, err := caddy.GetModule(modID) if err != nil { // that's weird, shouldn't happen unknown = append(unknown, moduleInfo{caddyModuleID: modID, err: err}) continue } // to get the Caddy plugin's version info, we need to know // the package that the Caddy module's value comes from; we // can use reflection but we need a non-pointer value (I'm // not sure why), and since New() should return a pointer // value, we need to dereference it first iface := any(modInfo.New()) if rv := reflect.ValueOf(iface); rv.Kind() == reflect.Ptr { iface = reflect.New(reflect.TypeOf(iface).Elem()).Elem().Interface() } modPkgPath := reflect.TypeOf(iface).PkgPath() // now we find the Go module that the Caddy module's package // belongs to; we assume the Caddy module package path will // be prefixed by its Go module path, and we will choose the // longest matching prefix in case there are nested modules var matched *debug.Module for _, dep := range bi.Deps { if strings.HasPrefix(modPkgPath, dep.Path) { if matched == nil || len(dep.Path) > len(matched.Path) { matched = dep } } } caddyModGoMod := moduleInfo{caddyModuleID: modID, goModule: matched} if strings.HasPrefix(modPkgPath, caddy.ImportPath) { standard = append(standard, caddyModGoMod) } else { nonstandard = append(nonstandard, caddyModGoMod) } } return } func listModules(path string) error { cmd := exec.Command(path, "list-modules", "--versions", "--skip-standard") cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr return cmd.Run() } func showVersion(path string) error { cmd := exec.Command(path, "version") cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr return cmd.Run() } func downloadBuild(qs url.Values) (*http.Response, error) { l := caddy.Log() l.Info("requesting build", zap.String("os", qs.Get("os")), zap.String("arch", qs.Get("arch")), zap.Strings("packages", qs["p"])) resp, err := http.Get(fmt.Sprintf("%s?%s", downloadPath, qs.Encode())) if err != nil { return nil, fmt.Errorf("secure request failed: %v", err) } if resp.StatusCode >= 400 { var details struct { StatusCode int `json:"status_code"` Error struct { Message string `json:"message"` ID string `json:"id"` } `json:"error"` } err2 := json.NewDecoder(resp.Body).Decode(&details) if err2 != nil { return nil, fmt.Errorf("download and error decoding failed: HTTP %d: %v", resp.StatusCode, err2) } return nil, fmt.Errorf("download failed: HTTP %d: %s (id=%s)", resp.StatusCode, details.Error.Message, details.Error.ID) } return resp, nil } func getPluginPackages(modules []moduleInfo) (map[string]struct{}, error) { pluginPkgs := make(map[string]struct{}) for _, mod := range modules { if mod.goModule.Replace != nil { return nil, fmt.Errorf("cannot auto-upgrade when Go module has been replaced: %s => %s", mod.goModule.Path, mod.goModule.Replace.Path) } pluginPkgs[mod.goModule.Path] = struct{}{} } return pluginPkgs, nil } func writeCaddyBinary(path string, body *io.ReadCloser, fileInfo os.FileInfo) error { l := caddy.Log() destFile, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, fileInfo.Mode()) if err != nil { return fmt.Errorf("unable to open destination file: %v", err) } defer destFile.Close() l.Info("downloading binary", zap.String("destination", path)) _, err = io.Copy(destFile, *body) if err != nil { return fmt.Errorf("unable to download file: %v", err) } err = destFile.Sync() if err != nil { return fmt.Errorf("syncing downloaded file to device: %v", err) } return nil } const downloadPath = "https://caddyserver.com/api/download"
Go
caddy/cmd/removebinary.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. //go:build !windows package caddycmd import ( "os" ) // removeCaddyBinary removes the Caddy binary at the given path. // // On any non-Windows OS, this simply calls os.Remove, since they should // probably not exhibit any issue with processes deleting themselves. func removeCaddyBinary(path string) error { return os.Remove(path) }
Go
caddy/cmd/removebinary_windows.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 caddycmd import ( "os" "path/filepath" "syscall" ) // removeCaddyBinary removes the Caddy binary at the given path. // // On Windows, this uses a syscall to indirectly remove the file, // because otherwise we get an "Access is denied." error when trying // to delete the binary while Caddy is still running and performing // the upgrade. "cmd.exe /C" executes a command specified by the // following arguments, i.e. "del" which will run as a separate process, // which avoids the "Access is denied." error. func removeCaddyBinary(path string) error { var sI syscall.StartupInfo var pI syscall.ProcessInformation argv, err := syscall.UTF16PtrFromString(filepath.Join(os.Getenv("windir"), "system32", "cmd.exe") + " /C del " + path) if err != nil { return err } return syscall.CreateProcess(nil, argv, nil, nil, true, 0, nil, nil, &sI, &pI) }
Go
caddy/cmd/storagefuncs.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 caddycmd import ( "archive/tar" "context" "encoding/json" "errors" "fmt" "io" "os" "github.com/caddyserver/certmagic" "github.com/caddyserver/caddy/v2" ) type storVal struct { StorageRaw json.RawMessage `json:"storage,omitempty" caddy:"namespace=caddy.storage inline_key=module"` } // determineStorage returns the top-level storage module from the given config. // It may return nil even if no error. func determineStorage(configFile string, configAdapter string) (*storVal, error) { cfg, _, err := LoadConfig(configFile, configAdapter) if err != nil { return nil, err } // storage defaults to FileStorage if not explicitly // defined in the config, so the config can be valid // json but unmarshaling will fail. if !json.Valid(cfg) { return nil, &json.SyntaxError{} } var tmpStruct storVal err = json.Unmarshal(cfg, &tmpStruct) if err != nil { // default case, ignore the error var jsonError *json.SyntaxError if errors.As(err, &jsonError) { return nil, nil } return nil, err } return &tmpStruct, nil } func cmdImportStorage(fl Flags) (int, error) { importStorageCmdConfigFlag := fl.String("config") importStorageCmdImportFile := fl.String("input") if importStorageCmdConfigFlag == "" { return caddy.ExitCodeFailedStartup, errors.New("--config is required") } if importStorageCmdImportFile == "" { return caddy.ExitCodeFailedStartup, errors.New("--input is required") } // extract storage from config if possible storageCfg, err := determineStorage(importStorageCmdConfigFlag, "") if err != nil { return caddy.ExitCodeFailedStartup, err } // load specified storage or fallback to default var stor certmagic.Storage ctx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()}) defer cancel() if storageCfg != nil && storageCfg.StorageRaw != nil { val, err := ctx.LoadModule(storageCfg, "StorageRaw") if err != nil { return caddy.ExitCodeFailedStartup, err } stor, err = val.(caddy.StorageConverter).CertMagicStorage() if err != nil { return caddy.ExitCodeFailedStartup, err } } else { stor = caddy.DefaultStorage } // setup input var f *os.File if importStorageCmdImportFile == "-" { f = os.Stdin } else { f, err = os.Open(importStorageCmdImportFile) if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("opening input file: %v", err) } defer f.Close() } // store each archive element tr := tar.NewReader(f) for { hdr, err := tr.Next() if err == io.EOF { break } if err != nil { return caddy.ExitCodeFailedQuit, fmt.Errorf("reading archive: %v", err) } b, err := io.ReadAll(tr) if err != nil { return caddy.ExitCodeFailedQuit, fmt.Errorf("reading archive: %v", err) } err = stor.Store(ctx, hdr.Name, b) if err != nil { return caddy.ExitCodeFailedQuit, fmt.Errorf("reading archive: %v", err) } } fmt.Println("Successfully imported storage") return caddy.ExitCodeSuccess, nil } func cmdExportStorage(fl Flags) (int, error) { exportStorageCmdConfigFlag := fl.String("config") exportStorageCmdOutputFlag := fl.String("output") if exportStorageCmdConfigFlag == "" { return caddy.ExitCodeFailedStartup, errors.New("--config is required") } if exportStorageCmdOutputFlag == "" { return caddy.ExitCodeFailedStartup, errors.New("--output is required") } // extract storage from config if possible storageCfg, err := determineStorage(exportStorageCmdConfigFlag, "") if err != nil { return caddy.ExitCodeFailedStartup, err } // load specified storage or fallback to default var stor certmagic.Storage ctx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()}) defer cancel() if storageCfg != nil && storageCfg.StorageRaw != nil { val, err := ctx.LoadModule(storageCfg, "StorageRaw") if err != nil { return caddy.ExitCodeFailedStartup, err } stor, err = val.(caddy.StorageConverter).CertMagicStorage() if err != nil { return caddy.ExitCodeFailedStartup, err } } else { stor = caddy.DefaultStorage } // enumerate all keys keys, err := stor.List(ctx, "", true) if err != nil { return caddy.ExitCodeFailedStartup, err } // setup output var f *os.File if exportStorageCmdOutputFlag == "-" { f = os.Stdout } else { f, err = os.Create(exportStorageCmdOutputFlag) if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("opening output file: %v", err) } defer f.Close() } // `IsTerminal: true` keys hold the values we // care about, write them out tw := tar.NewWriter(f) for _, k := range keys { info, err := stor.Stat(ctx, k) if err != nil { return caddy.ExitCodeFailedQuit, err } if info.IsTerminal { v, err := stor.Load(ctx, k) if err != nil { return caddy.ExitCodeFailedQuit, err } hdr := &tar.Header{ Name: k, Mode: 0o600, Size: int64(len(v)), } if err = tw.WriteHeader(hdr); err != nil { return caddy.ExitCodeFailedQuit, fmt.Errorf("writing archive: %v", err) } if _, err = tw.Write(v); err != nil { return caddy.ExitCodeFailedQuit, fmt.Errorf("writing archive: %v", err) } } } if err = tw.Close(); err != nil { return caddy.ExitCodeFailedQuit, fmt.Errorf("writing archive: %v", err) } return caddy.ExitCodeSuccess, nil }
Go
caddy/cmd/caddy/main.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 main is the entry point of the Caddy application. // Most of Caddy's functionality is provided through modules, // which can be plugged in by adding their import below. // // There is no need to modify the Caddy source code to customize your // builds. You can easily build a custom Caddy with these simple steps: // // 1. Copy this file (main.go) into a new folder // 2. Edit the imports below to include the modules you want plugged in // 3. Run `go mod init caddy` // 4. Run `go install` or `go build` - you now have a custom binary! // // Or you can use xcaddy which does it all for you as a command: // https://github.com/caddyserver/xcaddy package main import ( caddycmd "github.com/caddyserver/caddy/v2/cmd" // plug in Caddy modules here _ "github.com/caddyserver/caddy/v2/modules/standard" ) func main() { caddycmd.Main() }
Shell Script
caddy/cmd/caddy/setcap.sh
#!/bin/sh # USAGE: go run -exec ./setcap.sh <args...> sudo setcap cap_net_bind_service=+ep "$1" "$@"
Go
caddy/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
caddy/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
caddy/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
caddy/modules/caddyevents/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 caddyevents import ( "context" "encoding/json" "errors" "fmt" "strings" "time" "github.com/google/uuid" "go.uber.org/zap" "github.com/caddyserver/caddy/v2" ) func init() { caddy.RegisterModule(App{}) } // App implements a global eventing system within Caddy. // Modules can emit and subscribe to events, providing // hooks into deep parts of the code base that aren't // otherwise accessible. Events provide information about // what and when things are happening, and this facility // allows handlers to take action when events occur, // add information to the event's metadata, and even // control program flow in some cases. // // Events are propagated in a DOM-like fashion. An event // emitted from module `a.b.c` (the "origin") will first // invoke handlers listening to `a.b.c`, then `a.b`, // then `a`, then those listening regardless of origin. // If a handler returns the special error Aborted, then // propagation immediately stops and the event is marked // as aborted. Emitters may optionally choose to adjust // program flow based on an abort. // // Modules can subscribe to events by origin and/or name. // A handler is invoked only if it is subscribed to the // event by name and origin. Subscriptions should be // registered during the provisioning phase, before apps // are started. // // Event handlers are fired synchronously as part of the // regular flow of the program. This allows event handlers // to control the flow of the program if the origin permits // it and also allows handlers to convey new information // back into the origin module before it continues. // In essence, event handlers are similar to HTTP // middleware handlers. // // Event bindings/subscribers are unordered; i.e. // event handlers are invoked in an arbitrary order. // Event handlers should not rely on the logic of other // handlers to succeed. // // The entirety of this app module is EXPERIMENTAL and // subject to change. Pay attention to release notes. type App struct { // Subscriptions bind handlers to one or more events // either globally or scoped to specific modules or module // namespaces. Subscriptions []*Subscription `json:"subscriptions,omitempty"` // Map of event name to map of module ID/namespace to handlers subscriptions map[string]map[caddy.ModuleID][]Handler logger *zap.Logger started bool } // Subscription represents binding of one or more handlers to // one or more events. type Subscription struct { // The name(s) of the event(s) to bind to. Default: all events. Events []string `json:"events,omitempty"` // The ID or namespace of the module(s) from which events // originate to listen to for events. Default: all modules. // // Events propagate up, so events emitted by module "a.b.c" // will also trigger the event for "a.b" and "a". Thus, to // receive all events from "a.b.c" and "a.b.d", for example, // one can subscribe to either "a.b" or all of "a" entirely. Modules []caddy.ModuleID `json:"modules,omitempty"` // The event handler modules. These implement the actual // behavior to invoke when an event occurs. At least one // handler is required. HandlersRaw []json.RawMessage `json:"handlers,omitempty" caddy:"namespace=events.handlers inline_key=handler"` // The decoded handlers; Go code that is subscribing to // an event should set this field directly; HandlersRaw // is meant for JSON configuration to fill out this field. Handlers []Handler `json:"-"` } // CaddyModule returns the Caddy module information. func (App) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "events", New: func() caddy.Module { return new(App) }, } } // Provision sets up the app. func (app *App) Provision(ctx caddy.Context) error { app.logger = ctx.Logger() app.subscriptions = make(map[string]map[caddy.ModuleID][]Handler) for _, sub := range app.Subscriptions { if sub.HandlersRaw != nil { handlersIface, err := ctx.LoadModule(sub, "HandlersRaw") if err != nil { return fmt.Errorf("loading event subscriber modules: %v", err) } for _, h := range handlersIface.([]any) { sub.Handlers = append(sub.Handlers, h.(Handler)) } if len(sub.Handlers) == 0 { // pointless to bind without any handlers return fmt.Errorf("no handlers defined") } } } return nil } // Start runs the app. func (app *App) Start() error { for _, sub := range app.Subscriptions { if err := app.Subscribe(sub); err != nil { return err } } app.started = true return nil } // Stop gracefully shuts down the app. func (app *App) Stop() error { return nil } // Subscribe binds one or more event handlers to one or more events // according to the subscription s. For now, subscriptions can only // be created during the provision phase; new bindings cannot be // created after the events app has started. func (app *App) Subscribe(s *Subscription) error { if app.started { return fmt.Errorf("events already started; new subscriptions closed") } // handle special case of catch-alls (omission of event name or module space implies all) if len(s.Events) == 0 { s.Events = []string{""} } if len(s.Modules) == 0 { s.Modules = []caddy.ModuleID{""} } for _, eventName := range s.Events { if app.subscriptions[eventName] == nil { app.subscriptions[eventName] = make(map[caddy.ModuleID][]Handler) } for _, originModule := range s.Modules { app.subscriptions[eventName][originModule] = append(app.subscriptions[eventName][originModule], s.Handlers...) } } return nil } // On is syntactic sugar for Subscribe() that binds a single handler // to a single event from any module. If the eventName is empty string, // it counts for all events. func (app *App) On(eventName string, handler Handler) error { return app.Subscribe(&Subscription{ Events: []string{eventName}, Handlers: []Handler{handler}, }) } // Emit creates and dispatches an event named eventName to all relevant handlers with // the metadata data. Events are emitted and propagated synchronously. The returned Event // value will have any additional information from the invoked handlers. // // Note that the data map is not copied, for efficiency. After Emit() is called, the // data passed in should not be changed in other goroutines. func (app *App) Emit(ctx caddy.Context, eventName string, data map[string]any) Event { logger := app.logger.With(zap.String("name", eventName)) id, err := uuid.NewRandom() if err != nil { logger.Error("failed generating new event ID", zap.Error(err)) } eventName = strings.ToLower(eventName) e := Event{ Data: data, id: id, ts: time.Now(), name: eventName, origin: ctx.Module(), } logger = logger.With( zap.String("id", e.id.String()), zap.String("origin", e.origin.CaddyModule().String())) // add event info to replacer, make sure it's in the context repl, ok := ctx.Context.Value(caddy.ReplacerCtxKey).(*caddy.Replacer) if !ok { repl = caddy.NewReplacer() ctx.Context = context.WithValue(ctx.Context, caddy.ReplacerCtxKey, repl) } repl.Map(func(key string) (any, bool) { switch key { case "event": return e, true case "event.id": return e.id, true case "event.name": return e.name, true case "event.time": return e.ts, true case "event.time_unix": return e.ts.UnixMilli(), true case "event.module": return e.origin.CaddyModule().ID, true case "event.data": return e.Data, true } if strings.HasPrefix(key, "event.data.") { key = strings.TrimPrefix(key, "event.data.") if val, ok := e.Data[key]; ok { return val, true } } return nil, false }) logger.Debug("event", zap.Any("data", e.Data)) // invoke handlers bound to the event by name and also all events; this for loop // iterates twice at most: once for the event name, once for "" (all events) for { moduleID := e.origin.CaddyModule().ID // implement propagation up the module tree (i.e. start with "a.b.c" then "a.b" then "a" then "") for { if app.subscriptions[eventName] == nil { break // shortcut if event not bound at all } for _, handler := range app.subscriptions[eventName][moduleID] { select { case <-ctx.Done(): logger.Error("context canceled; event handling stopped") return e default: } if err := handler.Handle(ctx, e); err != nil { aborted := errors.Is(err, ErrAborted) logger.Error("handler error", zap.Error(err), zap.Bool("aborted", aborted)) if aborted { e.Aborted = err return e } } } if moduleID == "" { break } lastDot := strings.LastIndex(string(moduleID), ".") if lastDot < 0 { moduleID = "" // include handlers bound to events regardless of module } else { moduleID = moduleID[:lastDot] } } // include handlers listening to all events if eventName == "" { break } eventName = "" } return e } // Event represents something that has happened or is happening. // An Event value is not synchronized, so it should be copied if // being used in goroutines. // // EXPERIMENTAL: As with the rest of this package, events are // subject to change. type Event struct { // If non-nil, the event has been aborted, meaning // propagation has stopped to other handlers and // the code should stop what it was doing. Emitters // may choose to use this as a signal to adjust their // code path appropriately. Aborted error // The data associated with the event. Usually the // original emitter will be the only one to set or // change these values, but the field is exported // so handlers can have full access if needed. // However, this map is not synchronized, so // handlers must not use this map directly in new // goroutines; instead, copy the map to use it in a // goroutine. Data map[string]any id uuid.UUID ts time.Time name string origin caddy.Module } // CloudEvent exports event e as a structure that, when // serialized as JSON, is compatible with the // CloudEvents spec. func (e Event) CloudEvent() CloudEvent { dataJSON, _ := json.Marshal(e.Data) return CloudEvent{ ID: e.id.String(), Source: e.origin.CaddyModule().String(), SpecVersion: "1.0", Type: e.name, Time: e.ts, DataContentType: "application/json", Data: dataJSON, } } // CloudEvent is a JSON-serializable structure that // is compatible with the CloudEvents specification. // See https://cloudevents.io. type CloudEvent struct { ID string `json:"id"` Source string `json:"source"` SpecVersion string `json:"specversion"` Type string `json:"type"` Time time.Time `json:"time"` DataContentType string `json:"datacontenttype,omitempty"` Data json.RawMessage `json:"data,omitempty"` } // ErrAborted cancels an event. var ErrAborted = errors.New("event aborted") // Handler is a type that can handle events. type Handler interface { Handle(context.Context, Event) error } // Interface guards var ( _ caddy.App = (*App)(nil) _ caddy.Provisioner = (*App)(nil) )
Go
caddy/modules/caddyevents/eventsconfig/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 eventsconfig is for configuring caddyevents.App with the // Caddyfile. This code can't be in the caddyevents package because // the httpcaddyfile package imports caddyhttp, which imports // caddyevents: hence, it creates an import cycle. package eventsconfig import ( "encoding/json" "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/modules/caddyevents" ) func init() { httpcaddyfile.RegisterGlobalOption("events", parseApp) } // parseApp configures the "events" global option from Caddyfile to set up the events app. // Syntax: // // events { // on <event> <handler_module...> // } // // If <event> is *, then it will bind to all events. func parseApp(d *caddyfile.Dispenser, _ any) (any, error) { app := new(caddyevents.App) // consume the option name if !d.Next() { return nil, d.ArgErr() } // handle the block for d.NextBlock(0) { switch d.Val() { case "on": if !d.NextArg() { return nil, d.ArgErr() } eventName := d.Val() if eventName == "*" { eventName = "" } if !d.NextArg() { return nil, d.ArgErr() } handlerName := d.Val() modID := "events.handlers." + handlerName unm, err := caddyfile.UnmarshalModule(d, modID) if err != nil { return nil, err } app.Subscriptions = append(app.Subscriptions, &caddyevents.Subscription{ Events: []string{eventName}, HandlersRaw: []json.RawMessage{ caddyconfig.JSONModuleObject(unm, "handler", handlerName, nil), }, }) default: return nil, d.ArgErr() } } return httpcaddyfile.App{ Name: "events", Value: caddyconfig.JSON(app, nil), }, nil }
Go
caddy/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 ( "context" "crypto/tls" "fmt" "net" "net/http" "runtime" "strconv" "strings" "sync" "time" "go.uber.org/zap" "golang.org/x/net/http2" "golang.org/x/net/http2/h2c" "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.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.remote.host}` | The host (IP) part of the remote client's address // `{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 // `{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.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"` ctx caddy.Context logger *zap.Logger tlsApp *caddytls.TLS // used temporarily between phases 1 and 2 of auto HTTPS allCertDomains []string } // 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 tlsAppIface, err := ctx.App("tls") if err != nil { return fmt.Errorf("getting tls app: %v", err) } app.tlsApp = tlsAppIface.(*caddytls.TLS) app.ctx = ctx app.logger = ctx.Logger() 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 } // 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) // only enable access logs if configured if srv.Logs != nil { srv.accessLogger = app.logger.Named("log.access") } // the Go standard library does not let us serve only HTTP/2 using // http.Server; we would probably need to write our own server if !srv.protocol("h1") && (srv.protocol("h2") || srv.protocol("h2c")) { return fmt.Errorf("server %s: cannot enable HTTP/2 or H2C without enabling HTTP/1.1; add h1 to protocols or remove h2/h2c", srvName) } // if no protocols configured explicitly, enable all except h2c if len(srv.Protocols) == 0 { srv.Protocols = []string{"h1", "h2", "h3"} } // 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...) } } // 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, srv.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, srv.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 } } ctx.Context = oldContext return nil } // Validate ensures the app's configuration is valid. func (app *App) Validate() error { isGo120 := strings.Contains(runtime.Version(), "go1.20") // each server must use distinct listener addresses lnAddrs := make(map[string]string) for srvName, srv := range app.Servers { if isGo120 && srv.EnableFullDuplex { app.logger.Warn("enable_full_duplex is not supported in Go 1.20, use a build made with Go 1.21 or later", zap.String("server", srvName)) } 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.Itoa(int(listenAddr.StartPort+i))) 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 } } } return nil } // 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, ConnContext: func(ctx context.Context, c net.Conn) context.Context { return context.WithValue(ctx, ConnCtxKey, c) }, } h2server := &http2.Server{ NewWriteScheduler: func() http2.WriteScheduler { return http2.NewPriorityWriteScheduler(nil) }, } // 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)) for _, cp := range srv.TLSConnPolicies { // the TLSConfig was already provisioned, so... manually remove it for i, np := range cp.TLSConfig.NextProtos { if np == "h2" { 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 == "h2" { cp.ALPN = append(cp.ALPN[:i], cp.ALPN[i+1:]...) break } } } } else { //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) // enable H2C if configured if srv.protocol("h2c") { srv.server.Handler = h2c.NewHandler(srv, h2server) } for _, 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) for portOffset := uint(0); portOffset < listenAddr.PortRangeSize(); portOffset++ { // create the listener for this socket hostport := listenAddr.JoinHostPort(portOffset) lnAny, err := listenAddr.Listen(app.ctx, portOffset, net.ListenConfig{KeepAlive: time.Duration(srv.KeepAliveInterval)}) if err != nil { return fmt.Errorf("listening on %s: %v", listenAddr.At(portOffset), err) } ln := lnAny.(net.Listener) // 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) } // 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 useTLS { // create TLS listener - this enables and terminates TLS ln = tls.NewListener(ln, tlsCfg) // enable HTTP/3 if configured if srv.protocol("h3") { // 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 len(srv.Protocols) > 1 && listenAddr.IsUnixNetwork() { app.logger.Warn("HTTP/3 disabled because Unix can't multiplex STREAM and DGRAM on same socket", zap.String("file", hostport)) for i := range srv.Protocols { if srv.Protocols[i] == "h3" { srv.Protocols = append(srv.Protocols[:i], srv.Protocols[i+1:]...) break } } } else { app.logger.Info("enabling HTTP/3 listener", zap.String("addr", hostport)) if err := srv.serveHTTP3(listenAddr.At(portOffset), tlsCfg); err != nil { return err } } } } // finish wrapping listener where we left off before TLS for i := lnWrapperIdx; i < len(srv.listenerWrappers); i++ { ln = srv.listenerWrappers[i].WrapListener(ln) } // handle http2 if use tls listener wrapper if useTLS { http2lnWrapper := &http2Listener{ Listener: ln, server: srv.server, h2server: h2server, } srv.h2listeners = append(srv.h2listeners, http2lnWrapper) ln = http2lnWrapper } // 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.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) // enable HTTP/1 if configured if srv.protocol("h1") { //nolint:errcheck go srv.server.Serve(ln) } } } 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 // hrough 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() 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 } // First close h3server then close listeners unlike stdlib for several reasons: // 1, udp has only a single socket, once closed, no more data can be read and // written. In contrast, closing tcp listeners won't affect established connections. // This have something to do with graceful shutdown when upstream implements it. // 2, h3server will only close listeners it's registered (quic listeners). Closing // listener first and these listeners maybe unregistered thus won't be closed. caddy // distinguishes quic-listener and underlying datagram sockets. // TODO: CloseGracefully, once implemented upstream (see https://github.com/quic-go/quic-go/issues/2103) if err := server.h3server.Close(); err != nil { app.logger.Error("HTTP/3 server shutdown", zap.Error(err), zap.Strings("addresses", server.Listen)) } // TODO: we have to manually close our listeners because quic-go won't // close listeners it didn't create along with the server itself... // see https://github.com/quic-go/quic-go/issues/3560 for _, el := range server.h3listeners { if err := el.Close(); err != nil { app.logger.Error("HTTP/3 listener close", zap.Error(err), zap.String("address", el.LocalAddr().String())) } } } stopH2Listener := func(server *Server) { defer finishedShutdown.Done() startedShutdown.Done() for i, s := range server.h2listeners { if err := s.Shutdown(ctx); err != nil { app.logger.Error("http2 listener shutdown", zap.Error(err), zap.Int("index", i)) } } } for _, server := range app.Servers { startedShutdown.Add(3) finishedShutdown.Add(3) go stopServer(server) go stopH3Server(server) go stopH2Listener(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() } return nil } 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 } // 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). const defaultIdleTimeout = caddy.Duration(5 * time.Minute) // Interface guards var ( _ caddy.App = (*App)(nil) _ caddy.Provisioner = (*App)(nil) _ caddy.Validator = (*App)(nil) )
Go
caddy/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" "strconv" "strings" "github.com/caddyserver/certmagic" "go.uber.org/zap" "github.com/caddyserver/caddy/v2" "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"` } // Skipped returns true if name is in skipSlice, which // should be either the Skip or SkipCerts field on ahc. func (ahc AutoHTTPSConfig) Skipped(name string, skipSlice []string) bool { for _, n := range skipSlice { if name == n { return true } } return false } // 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.Warn("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 !srv.AutoHTTPS.Skipped(d, srv.AutoHTTPS.Skip) { serverDomainSet[d] = struct{}{} } } } } } } // 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) && !srv.AutoHTTPS.Skipped(d, srv.AutoHTTPS.SkipCerts) { // 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.Warn("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] = []caddy.NetworkAddress{addr} } } } } // we now have a list of all the unique names for which we need certs; // turn the set into a slice so that phase 2 can use it app.allCertDomains = make([]string, 0, len(uniqueDomainsForCerts)) var internal, tailscale []string uniqueDomainsLoop: for d := range uniqueDomainsForCerts { if !isTailscaleDomain(d) { // whether or not there is already an automation policy for this // name, we should add it to the list to manage a cert for it, // unless it's a Tailscale domain, because we don't manage those app.allCertDomains = append(app.allCertDomains, d) } // 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 { continue uniqueDomainsLoop } } } } // if no automation policy exists for the name yet, we // will associate it with an implicit one if isTailscaleDomain(d) { tailscale = append(tailscale, d) } else if !certmagic.SubjectQualifiesForPublicCert(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, } } 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", app.allCertDomains), ) err := app.tlsApp.Manage(app.allCertDomains) if err != nil { return fmt.Errorf("managing certificates for %v: %s", 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
caddy/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. type RequestMatcher interface { Match(*http.Request) bool } // 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, *http.Request) error { 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 routse 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. func SanitizedPathJoin(root, reqPath string) string { if root == "" { root = "." } path := filepath.Join(root, path.Clean("/"+reqPath)) // 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
caddy/modules/caddyhttp/caddyhttp_test.go
package caddyhttp import ( "net/url" "path/filepath" "testing" ) func TestSanitizedPathJoin(t *testing.T) { // For reference: // %2e = . // %2f = / // %5c = \ for i, tc := range []struct { inputRoot string inputPath string expect string }{ { inputPath: "", expect: ".", }, { inputPath: "/", expect: ".", }, { inputPath: "/foo", expect: "foo", }, { inputPath: "/foo/", expect: "foo" + separator, }, { inputPath: "/foo/bar", expect: filepath.Join("foo", "bar"), }, { inputRoot: "/a", inputPath: "/foo/bar", expect: filepath.Join("/", "a", "foo", "bar"), }, { inputPath: "/foo/../bar", expect: "bar", }, { inputRoot: "/a/b", inputPath: "/foo/../bar", expect: filepath.Join("/", "a", "b", "bar"), }, { inputRoot: "/a/b", inputPath: "/..%2fbar", expect: filepath.Join("/", "a", "b", "bar"), }, { inputRoot: "/a/b", inputPath: "/%2e%2e%2fbar", expect: filepath.Join("/", "a", "b", "bar"), }, { inputRoot: "/a/b", inputPath: "/%2e%2e%2f%2e%2e%2f", expect: filepath.Join("/", "a", "b") + separator, }, { 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"), }, } { // 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 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
caddy/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/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" exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1" "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 expandedExpr string prg cel.Program ta ref.TypeAdapter 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) { return json.Marshal(m.Expr) } // UnmarshalJSON unmarshals m's expression. func (m *MatchExpression) UnmarshalJSON(data []byte) error { return json.Unmarshal(data, &m.Expr) } // 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) // 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) } } // 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(placeholderFuncName, cel.SingletonBinaryBinding(m.caddyPlaceholderFunc), cel.Overload( placeholderFuncName+"_httpRequest_string", []*cel.Type{httpRequestObjectType, cel.StringType}, cel.AnyType, )), cel.Variable("request", httpRequestObjectType), cel.CustomTypeAdapter(m.ta), ext.Strings(), 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 { celReq := celHTTPRequest{r} out, _, err := m.prg.Eval(celReq) if err != nil { m.log.Error("evaluating expression", zap.Error(err)) SetVar(r.Context(), MatcherErrorVarKey, err) return false } if outBool, ok := out.Value().(bool); ok { return outBool } return false } // UnmarshalCaddyfile implements caddyfile.Unmarshaler. func (m *MatchExpression) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { if d.CountRemainingArgs() > 1 { m.Expr = strings.Join(d.RemainingArgsRaw(), " ") } else { m.Expr = d.Val() } } 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(), placeholderFuncName, ) } phStr, ok := rhs.(types.String) if !ok { return types.NewErr( "invalid placeholder variable name of type '%v' to %s(request, placeholderVarName)", rhs.Type(), placeholderFuncName, ) } 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 = types.NewTypeValue("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 == "request" { 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 = types.NewTypeValue("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: types.NewErr(v.Error()) } 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 CELMatcherFactory) (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. type CELMatcherFactory func(data ref.Val) (RequestMatcher, error) // matcherCELLibrary is a simplistic configurable cel.Library implementation. type matcherCELLibary 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 &matcherCELLibary{ envOptions: envOptions, programOptions: programOptions, } } func (lib *matcherCELLibary) CompileOptions() []cel.EnvOption { return lib.envOptions } func (lib *matcherCELLibary) 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 CELMatcherFactory) 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 'request' argument") } nsAttr, ok := reqAttr.Attr().(interpreter.NamespacedAttribute) if !ok { return nil, errors.New("missing 'request' argument") } varNames := nsAttr.CandidateVariableNames() if len(varNames) != 1 || len(varNames) == 1 && varNames[0] != "request" { return nil, errors.New("missing 'request' 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 } matcher, err := fac(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) return types.Bool(matcher.Match(httpReq.Request)) }, ), nil } } // 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 CELMatcherFactory) functions.BinaryOp { return func(celReq, matcherData ref.Val) ref.Val { matcher, err := fac(matcherData) if err != nil { return types.NewErr(err.Error()) } httpReq := celReq.Value().(celHTTPRequest) return types.Bool(matcher.Match(httpReq.Request)) } } // 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) parser.MacroExpander { return func(eh parser.ExprHelper, target *exprpb.Expr, args []*exprpb.Expr) (*exprpb.Expr, *common.Error) { matchArgs := []*exprpb.Expr{} if len(args) == 0 { return nil, &common.Error{ Message: "matcher requires at least one argument", } } for _, arg := range args { if isCELStringExpr(arg) { matchArgs = append(matchArgs, arg) } else { return nil, &common.Error{ Location: eh.OffsetLocation(arg.GetId()), Message: "matcher arguments must be string constants", } } } return eh.GlobalCall(funcName, eh.Ident("request"), 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 parser.ExprHelper, target *exprpb.Expr, args []*exprpb.Expr) (*exprpb.Expr, *common.Error) { if len(args) != 1 { return nil, &common.Error{ Message: "matcher requires one argument", } } if isCELStringExpr(args[0]) { return eh.GlobalCall(funcName, eh.Ident("request"), args[0]), nil } return nil, &common.Error{ Location: eh.OffsetLocation(args[0].GetId()), Message: "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 parser.ExprHelper, target *exprpb.Expr, args []*exprpb.Expr) (*exprpb.Expr, *common.Error) { if len(args) != 1 { return nil, &common.Error{ Message: "matcher requires a map literal argument", } } arg := args[0] switch arg.GetExprKind().(type) { case *exprpb.Expr_StructExpr: structExpr := arg.GetStructExpr() if structExpr.GetMessageName() != "" { return nil, &common.Error{ Location: eh.OffsetLocation(arg.GetId()), Message: fmt.Sprintf( "matcher input must be a map literal, not a %s", structExpr.GetMessageName(), ), } } for _, entry := range structExpr.GetEntries() { isStringPlaceholder := isCELStringExpr(entry.GetMapKey()) if !isStringPlaceholder { return nil, &common.Error{ Location: eh.OffsetLocation(entry.GetId()), Message: "matcher map keys must be string literals", } } isStringListPlaceholder := isCELStringExpr(entry.GetValue()) || isCELStringListLiteral(entry.GetValue()) if !isStringListPlaceholder { return nil, &common.Error{ Location: eh.OffsetLocation(entry.GetValue().GetId()), Message: "matcher map values must be string or list literals", } } } return eh.GlobalCall(funcName, eh.Ident("request"), arg), nil } return nil, &common.Error{ Location: eh.OffsetLocation(arg.GetId()), Message: "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.TypeOf(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 *exprpb.Expr) bool { return isCELStringLiteral(e) || isCELCaddyPlaceholderCall(e) || isCELConcatCall(e) } // isCELStringLiteral returns whether the expression is a CEL string literal. func isCELStringLiteral(e *exprpb.Expr) bool { switch e.GetExprKind().(type) { case *exprpb.Expr_ConstExpr: constant := e.GetConstExpr() switch constant.GetConstantKind().(type) { case *exprpb.Constant_StringValue: return true } } return false } // isCELCaddyPlaceholderCall returns whether the expression is a caddy placeholder call. func isCELCaddyPlaceholderCall(e *exprpb.Expr) bool { switch e.GetExprKind().(type) { case *exprpb.Expr_CallExpr: call := e.GetCallExpr() if call.GetFunction() == "caddyPlaceholder" { return true } } return false } // isCELConcatCall tests whether the expression is a concat function (+) with string, placeholder, or // other concat call arguments. func isCELConcatCall(e *exprpb.Expr) bool { switch e.GetExprKind().(type) { case *exprpb.Expr_CallExpr: call := e.GetCallExpr() if call.GetTarget() != nil { return false } if call.GetFunction() != operators.Add { return false } for _, arg := range call.GetArgs() { if !isCELStringExpr(arg) { return false } } return true } return false } // isCELStringListLiteral returns whether the expression resolves to a list literal // containing only string constants or a placeholder call. func isCELStringListLiteral(e *exprpb.Expr) bool { switch e.GetExprKind().(type) { case *exprpb.Expr_ListExpr: list := e.GetListExpr() for _, elem := range list.GetElements() { if !isCELStringExpr(elem) { return false } } return true } return false } // Variables used for replacing Caddy placeholders in CEL // expressions with a proper CEL function call; this is // just for syntactic sugar. var ( placeholderRegexp = regexp.MustCompile(`{([a-zA-Z][\w.-]+)}`) placeholderExpansion = `caddyPlaceholder(request, "${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 placeholderFuncName = "caddyPlaceholder" // Interface guards var ( _ caddy.Provisioner = (*MatchExpression)(nil) _ RequestMatcher = (*MatchExpression)(nil) _ caddyfile.Unmarshaler = (*MatchExpression)(nil) _ json.Marshaler = (*MatchExpression)(nil) _ json.Unmarshaler = (*MatchExpression)(nil) )
Go
caddy/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 error (MatchHeader)", expression: &MatchExpression{ Expr: `header('foo')`, }, urlTarget: "https://example.com/foo", httpHeader: &http.Header{"Field": []string{"foo", "bar"}}, 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')`, }, urlTarget: "https://example.com/foo", httpHeader: &http.Header{"Field": []string{"foo", "bar"}}, 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)`, }, urlTarget: "http://localhost: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()`, }, urlTarget: "https://foo.example.com", httpMethod: "PUT", 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()`, }, urlTarget: "https://example.com", wantErr: true, }, { name: "protocol invocation error too many args (MatchProtocol)", expression: &MatchExpression{ Expr: `protocol('grpc', 'https')`, }, urlTarget: "https://example.com", wantErr: true, }, { name: "protocol invocation error wrong arg type (MatchProtocol)", expression: &MatchExpression{ Expr: `protocol(true)`, }, urlTarget: "https://example.com", 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"})`, }, urlTarget: "https://example.com/foo", wantErr: true, }, { name: "query error typed struct instead of map (MatchQuery)", expression: &MatchExpression{ Expr: `query(Message{field: "1"})`, }, urlTarget: "https://example.com/foo", wantErr: true, }, { name: "query error bad map value type (MatchQuery)", expression: &MatchExpression{ Expr: `query({"debug": 1})`, }, urlTarget: "https://example.com/foo/?debug=1", wantErr: true, }, { name: "query error no args (MatchQuery)", expression: &MatchExpression{ Expr: `query()`, }, urlTarget: "https://example.com/foo/?debug=1", wantErr: true, }, { name: "remote_ip error no args (MatchRemoteIP)", expression: &MatchExpression{ Expr: `remote_ip()`, }, urlTarget: "https://example.com/foo", 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: "remote_ip forwarded (MatchRemoteIP)", expression: &MatchExpression{ Expr: `remote_ip('forwarded', '192.0.2.1')`, }, urlTarget: "https://example.com/foo", wantResult: true, }, { name: "remote_ip forwarded not first (MatchRemoteIP)", expression: &MatchExpression{ Expr: `remote_ip('192.0.2.1', 'forwarded')`, }, urlTarget: "https://example.com/foo", wantErr: true, }, } ) func TestMatchExpressionMatch(t *testing.T) { for _, tst := range matcherTests { tc := tst t.Run(tc.name, func(t *testing.T) { err := tc.expression.Provision(caddy.Context{}) 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) 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}, } } if tc.expression.Match(req) != 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) 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 i := 0; i < b.N; i++ { tc.expression.Match(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) { if err := tt.expression.Provision(caddy.Context{}); (err != nil) != tt.wantErr { t.Errorf("MatchExpression.Provision() error = %v, wantErr %v", err, tt.wantErr) } }) } }
Go
caddy/modules/caddyhttp/duplex_go120.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. //go:build !go1.21 package caddyhttp import ( "net/http" ) func enableFullDuplex(w http.ResponseWriter) error { // Do nothing, Go 1.20 and earlier do not support full duplex return nil }
Go
caddy/modules/caddyhttp/duplex_go121.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. //go:build go1.21 package caddyhttp import ( "net/http" ) func enableFullDuplex(w http.ResponseWriter) error { //nolint:bodyclose return http.NewResponseController(w).EnableFullDuplex() }
Go
caddy/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
caddy/modules/caddyhttp/http2listener.go
package caddyhttp import ( "context" "crypto/tls" weakrand "math/rand" "net" "net/http" "sync/atomic" "time" "golang.org/x/net/http2" ) // http2Listener wraps the listener to solve the following problems: // 1. server h2 natively without using h2c hack when listener handles tls connection but // don't return *tls.Conn // 2. graceful shutdown. the shutdown logic is copied from stdlib http.Server, it's an extra maintenance burden but // whatever, the shutdown logic maybe extracted to be used with h2c graceful shutdown. http2.Server supports graceful shutdown // sending GO_AWAY frame to connected clients, but doesn't track connection status. It requires explicit call of http2.ConfigureServer type http2Listener struct { cnt uint64 net.Listener server *http.Server h2server *http2.Server } type connectionStateConn interface { net.Conn ConnectionState() tls.ConnectionState } func (h *http2Listener) Accept() (net.Conn, error) { for { conn, err := h.Listener.Accept() if err != nil { return nil, err } if csc, ok := conn.(connectionStateConn); ok { // *tls.Conn will return empty string because it's only populated after handshake is complete if csc.ConnectionState().NegotiatedProtocol == http2.NextProtoTLS { go h.serveHttp2(csc) continue } } return conn, nil } } func (h *http2Listener) serveHttp2(csc connectionStateConn) { atomic.AddUint64(&h.cnt, 1) h.runHook(csc, http.StateNew) defer func() { csc.Close() atomic.AddUint64(&h.cnt, ^uint64(0)) h.runHook(csc, http.StateClosed) }() h.h2server.ServeConn(csc, &http2.ServeConnOpts{ Context: h.server.ConnContext(context.Background(), csc), BaseConfig: h.server, Handler: h.server.Handler, }) } const shutdownPollIntervalMax = 500 * time.Millisecond func (h *http2Listener) Shutdown(ctx context.Context) error { pollIntervalBase := time.Millisecond nextPollInterval := func() time.Duration { // Add 10% jitter. //nolint:gosec interval := pollIntervalBase + time.Duration(weakrand.Intn(int(pollIntervalBase/10))) // Double and clamp for next time. pollIntervalBase *= 2 if pollIntervalBase > shutdownPollIntervalMax { pollIntervalBase = shutdownPollIntervalMax } return interval } timer := time.NewTimer(nextPollInterval()) defer timer.Stop() for { if atomic.LoadUint64(&h.cnt) == 0 { return nil } select { case <-ctx.Done(): return ctx.Err() case <-timer.C: timer.Reset(nextPollInterval()) } } } func (h *http2Listener) runHook(conn net.Conn, state http.ConnState) { if h.server.ConnState != nil { h.server.ConnState(conn, state) } }
Go
caddy/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" "fmt" "net" "net/http" "sync" "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{} 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} } // 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 } // 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 } return &httpRedirectConn{ Conn: c, r: bufio.NewReader(c), }, nil } type httpRedirectConn struct { net.Conn once sync.Once 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) { var errReturn error c.once.Do(func() { firstBytes, err := c.r.Peek(5) if err != nil { return } // 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 } // 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 } // 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 { errReturn = fmt.Errorf("couldn't write HTTP->HTTPS redirect") return } errReturn = fmt.Errorf("redirected HTTP request on HTTPS port") c.Conn.Close() }) if errReturn != nil { return 0, errReturn } return c.r.Read(p) } // 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
caddy/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
caddy/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" "reflect" "strings" "github.com/google/cel-go/cel" "github.com/google/cel-go/common/types/ref" "go.uber.org/zap" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) // 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"` // If true, prefer the first IP in the request's X-Forwarded-For // header, if present, rather than the immediate peer's IP, as // the reference IP against which to match. Note that it is easy // to spoof request headers. Default: false // DEPRECATED: This is insecure, MatchClientIP should be used instead. Forwarded bool `json:"forwarded,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 { for d.Next() { for d.NextArg() { if d.Val() == "forwarded" { if len(m.Ranges) > 0 { return d.Err("if used, 'forwarded' must be first argument") } m.Forwarded = true continue } if d.Val() == "private_ranges" { m.Ranges = append(m.Ranges, 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('forwarded', '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) (RequestMatcher, error) { refStringList := reflect.TypeOf([]string{}) strList, err := data.ConvertToNative(refStringList) if err != nil { return nil, err } m := MatchRemoteIP{} for _, input := range strList.([]string) { if input == "forwarded" { if len(m.Ranges) > 0 { return nil, errors.New("if used, 'forwarded' must be first argument") } m.Forwarded = true continue } 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 if m.Forwarded { m.logger.Warn("remote_ip's forwarded mode is deprecated; use the 'client_ip' matcher instead") } return nil } // Match returns true if r matches m. func (m MatchRemoteIP) Match(r *http.Request) bool { address := r.RemoteAddr if m.Forwarded { if fwdFor := r.Header.Get("X-Forwarded-For"); fwdFor != "" { address = strings.TrimSpace(strings.Split(fwdFor, ",")[0]) } } clientIP, zoneID, err := parseIPZoneFromString(address) if err != nil { m.logger.Error("getting remote IP", zap.Error(err)) return false } matches, zoneFilter := matchIPByCidrZones(clientIP, zoneID, m.cidrs, m.zones) if !matches && !zoneFilter { m.logger.Debug("zone ID from remote IP did not match", zap.String("zone", zoneID)) } return matches } // 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 { for d.Next() { for d.NextArg() { if d.Val() == "private_ranges" { m.Ranges = append(m.Ranges, 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) (RequestMatcher, error) { refStringList := reflect.TypeOf([]string{}) 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 { 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 } 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 } func provisionCidrsZonesFromRanges(ranges []string) ([]*netip.Prefix, []string, error) { cidrs := []*netip.Prefix{} zones := []string{} for _, str := range ranges { // 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-Adresses 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 ( _ RequestMatcher = (*MatchRemoteIP)(nil) _ caddy.Provisioner = (*MatchRemoteIP)(nil) _ caddyfile.Unmarshaler = (*MatchRemoteIP)(nil) _ CELLibraryProducer = (*MatchRemoteIP)(nil) _ RequestMatcher = (*MatchClientIP)(nil) _ caddy.Provisioner = (*MatchClientIP)(nil) _ caddyfile.Unmarshaler = (*MatchClientIP)(nil) _ CELLibraryProducer = (*MatchClientIP)(nil) )
Go
caddy/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" ) 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, 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 } // 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", } } // Interface guards var ( _ caddy.Provisioner = (*StaticIPRange)(nil) _ caddyfile.Unmarshaler = (*StaticIPRange)(nil) _ IPRangeSource = (*StaticIPRange)(nil) )
Go
caddy/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 ( "errors" "net" "net/http" "strings" "go.uber.org/zap" "go.uber.org/zap/zapcore" "github.com/caddyserver/caddy/v2" ) // 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 LoggerNames (logger_names) map. DefaultLoggerName string `json:"default_logger_name,omitempty"` // LoggerNames maps request hostnames to a custom logger name. // For example, a mapping of "example.com" to "example" would // cause access logs from requests with a Host of example.com // to be emitted by a logger named "http.log.access.example". LoggerNames map[string]string `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 // LoggerNames (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"` } // wrapLogger wraps logger in a logger named according to user preferences for the given host. func (slc ServerLogConfig) wrapLogger(logger *zap.Logger, host string) *zap.Logger { if loggerName := slc.getLoggerName(host); loggerName != "" { return logger.Named(loggerName) } return logger } func (slc ServerLogConfig) getLoggerName(host string) string { tryHost := func(key string) (string, bool) { // first try exact match if loggerName, ok := slc.LoggerNames[key]; ok { return loggerName, ok } // strip port and try again (i.e. Host header of "example.com:1234" should // match "example.com" if there is no "example.com:1234" in the map) hostOnly, _, err := net.SplitHostPort(key) if err != nil { return "", false } loggerName, ok := slc.LoggerNames[hostOnly] return loggerName, ok } // try the exact hostname first if loggerName, ok := tryHost(host); ok { return loggerName } // 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 loggerName, ok := tryHost(wildcardHost); ok { return loggerName } } return slc.DefaultLoggerName } func (slc *ServerLogConfig) clone() *ServerLogConfig { clone := &ServerLogConfig{ DefaultLoggerName: slc.DefaultLoggerName, LoggerNames: make(map[string]string), SkipHosts: append([]string{}, slc.SkipHosts...), SkipUnmappedHosts: slc.SkipUnmappedHosts, ShouldLogCredentials: slc.ShouldLogCredentials, } for k, v := range slc.LoggerNames { clone.LoggerNames[k] = v } return clone } // 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 []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 = []zapcore.Field{ zap.Int("status", handlerErr.StatusCode), zap.String("err_id", handlerErr.ID), zap.String("err_trace", handlerErr.Trace), } return } status = http.StatusInternalServerError msg = err.Error() return } // ExtraLogFields is a list of extra fields to log with every request. type ExtraLogFields struct { fields []zapcore.Field } // Add adds a field to the list of extra fields to log. func (e *ExtraLogFields) Add(field zap.Field) { e.fields = append(e.fields, field) } const ( // Variable name used to indicate that this request // should be omitted from the access logs SkipLogVar string = "skip_log" // For adding additional fields to the access logs ExtraLogFieldsCtxKey caddy.CtxKey = "extra_log_fields" )
Go
caddy/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) enc.AddString("client_ip", GetVar(r.Context(), ClientIPVarKey).(string)) 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.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{} } } 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) 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
caddy/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" "reflect" "regexp" "runtime" "sort" "strconv" "strings" "github.com/google/cel-go/cel" "github.com/google/cel-go/common/types" "github.com/google/cel-go/common/types/ref" "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 // 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(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 { 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) for i, h := range m { h = strings.ToLower(h) if firstI, ok := seen[h]; ok { return fmt.Errorf("host at index %d is repeated at index %d: %s", firstI, i, h) } seen[h] = 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 { 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 } } 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 } else if strings.EqualFold(reqHost, host) { return true } } return false } // 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) (RequestMatcher, error) { refStringList := reflect.TypeOf([]string{}) 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 { // 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 } // 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 } // 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, "*") && strings.Count(matchPattern, "*") == 2 { if strings.Contains(reqPathForPattern, matchPattern[1:len(matchPattern)-1]) { return true } 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 } 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 } 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 } } return false } 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) (RequestMatcher, error) { refStringList := reflect.TypeOf([]string{}) 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 { 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 { 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) } // 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) (RequestMatcher, error) { pattern := data.(types.String) matcher := MatchPathRE{MatchRegexp{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) (RequestMatcher, error) { refStringList := reflect.TypeOf([]string{}) params, err := data.ConvertToNative(refStringList) if err != nil { return nil, err } strParams := params.([]string) matcher := MatchPathRE{MatchRegexp{Name: strParams[0], 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 { 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 { for _, method := range m { if r.Method == method { return true } } return false } // 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) (RequestMatcher, error) { refStringList := reflect.TypeOf([]string{}) 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) } 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 { 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 } for param, vals := range m { param = repl.ReplaceAll(param, "") paramVal, found := parsed[param] if found { for _, v := range vals { v = repl.ReplaceAll(v, "") if paramVal[0] == v || v == "*" { return true } } } } return len(m) == 0 && len(r.URL.Query()) == 0 } // 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) (RequestMatcher, 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) } 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 } // Match returns true if r matches m. func (m MatchHeader) Match(r *http.Request) bool { repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) return matchHeaders(r.Header, http.Header(m), r.Host, repl) } // CELLibrary produces options that expose this matcher for use in CEL // expression matchers. // // Example: // // expression header({'content-type': 'image/png'}) // expression header({'foo': ['bar', 'baz']}) // match bar or baz func (MatchHeader) CELLibrary(_ caddy.Context) (cel.Library, error) { return CELMatcherImpl( "header", "header_matcher_request_map", []*cel.Type{CELTypeJSON}, func(data ref.Val) (RequestMatcher, error) { mapStrListStr, err := CELValueToMapStrList(data) if err != nil { return nil, err } return MatchHeader(http.Header(mapStrListStr)), nil }, ) } // getHeaderFieldVals returns the field values for the given fieldName from input. // The host parameter should be obtained from the http.Request.Host field since // net/http removes it from the header map. func getHeaderFieldVals(input http.Header, fieldName, host string) []string { fieldName = textproto.CanonicalMIMEHeaderKey(fieldName) if fieldName == "Host" && host != "" { return []string{host} } return input[fieldName] } // matchHeaders returns true if input matches the criteria in against without regex. // The host parameter should be obtained from the http.Request.Host field since // net/http removes it from the header map. func matchHeaders(input, against http.Header, host string, repl *caddy.Replacer) bool { for field, allowedFieldVals := range against { actualFieldVals := getHeaderFieldVals(input, field, host) if allowedFieldVals != nil && len(allowedFieldVals) == 0 && actualFieldVals != nil { // a non-nil but empty list of allowed values means // match if the header field exists at all continue } if allowedFieldVals == nil && actualFieldVals == nil { // a nil list means match if the header does not exist at all continue } var match bool fieldVals: for _, actualFieldVal := range actualFieldVals { for _, allowedFieldVal := range allowedFieldVals { if repl != nil { allowedFieldVal = repl.ReplaceAll(allowedFieldVal, "") } switch { case allowedFieldVal == "*": match = true case strings.HasPrefix(allowedFieldVal, "*") && strings.HasSuffix(allowedFieldVal, "*"): match = strings.Contains(actualFieldVal, allowedFieldVal[1:len(allowedFieldVal)-1]) case strings.HasPrefix(allowedFieldVal, "*"): match = strings.HasSuffix(actualFieldVal, allowedFieldVal[1:]) case strings.HasSuffix(allowedFieldVal, "*"): match = strings.HasPrefix(actualFieldVal, allowedFieldVal[:len(allowedFieldVal)-1]) default: match = actualFieldVal == allowedFieldVal } if match { break fieldVals } } } if !match { return false } } return true } // CaddyModule returns the Caddy module information. func (MatchHeaderRE) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.matchers.header_regexp", New: func() caddy.Module { return new(MatchHeaderRE) }, } } // UnmarshalCaddyfile implements caddyfile.Unmarshaler. func (m *MatchHeaderRE) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { if *m == nil { *m = make(map[string]*MatchRegexp) } 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 } // If there's already a pattern for this field // then we would end up overwriting the old one if (*m)[field] != nil { return d.Errf("header_regexp matcher can only be used once per named matcher, per header field: %s", field) } (*m)[field] = &MatchRegexp{Pattern: val, Name: name} if d.NextBlock(0) { return d.Err("malformed header_regexp matcher: blocks are not supported") } } return nil } // Match returns true if r matches m. func (m MatchHeaderRE) Match(r *http.Request) bool { for field, rm := range m { actualFieldVals := getHeaderFieldVals(r.Header, field, r.Host) match := false fieldVal: for _, actualFieldVal := range actualFieldVals { repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) if rm.Match(actualFieldVal, repl) { match = true break fieldVal } } if !match { return false } } return true } // Provision compiles m's regular expressions. func (m MatchHeaderRE) Provision(ctx caddy.Context) error { for _, rm := range m { err := rm.Provision(ctx) if err != nil { return err } } return nil } // Validate validates m's regular expressions. func (m MatchHeaderRE) Validate() error { for _, rm := range m { err := rm.Validate() if err != nil { return err } } return nil } // CELLibrary produces options that expose this matcher for use in CEL // expression matchers. // // Example: // // expression header_regexp('foo', 'Field', 'fo+') func (MatchHeaderRE) CELLibrary(ctx caddy.Context) (cel.Library, error) { unnamedPattern, err := CELMatcherImpl( "header_regexp", "header_regexp_request_string_string", []*cel.Type{cel.StringType, cel.StringType}, func(data ref.Val) (RequestMatcher, error) { refStringList := reflect.TypeOf([]string{}) params, err := data.ConvertToNative(refStringList) if err != nil { return nil, err } strParams := params.([]string) matcher := MatchHeaderRE{} matcher[strParams[0]] = &MatchRegexp{Pattern: strParams[1], Name: ""} err = matcher.Provision(ctx) return matcher, err }, ) if err != nil { return nil, err } namedPattern, err := CELMatcherImpl( "header_regexp", "header_regexp_request_string_string_string", []*cel.Type{cel.StringType, cel.StringType, cel.StringType}, func(data ref.Val) (RequestMatcher, error) { refStringList := reflect.TypeOf([]string{}) params, err := data.ConvertToNative(refStringList) if err != nil { return nil, err } strParams := params.([]string) matcher := MatchHeaderRE{} matcher[strParams[1]] = &MatchRegexp{Pattern: strParams[2], Name: strParams[0]} 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 (MatchProtocol) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.matchers.protocol", New: func() caddy.Module { return new(MatchProtocol) }, } } // Match returns true if r matches m. func (m MatchProtocol) Match(r *http.Request) bool { switch string(m) { case "grpc": return strings.HasPrefix(r.Header.Get("content-type"), "application/grpc") case "https": return r.TLS != nil case "http": return r.TLS == nil case "http/1.0": return r.ProtoMajor == 1 && r.ProtoMinor == 0 case "http/1.0+": return r.ProtoAtLeast(1, 0) case "http/1.1": return r.ProtoMajor == 1 && r.ProtoMinor == 1 case "http/1.1+": return r.ProtoAtLeast(1, 1) case "http/2": return r.ProtoMajor == 2 case "http/2+": return r.ProtoAtLeast(2, 0) case "http/3": return r.ProtoMajor == 3 case "http/3+": return r.ProtoAtLeast(3, 0) } return false } // UnmarshalCaddyfile implements caddyfile.Unmarshaler. func (m *MatchProtocol) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { var proto string if !d.Args(&proto) { return d.Err("expected exactly one protocol") } *m = MatchProtocol(proto) } return nil } // CELLibrary produces options that expose this matcher for use in CEL // expression matchers. // // Example: // // expression protocol('https') func (MatchProtocol) CELLibrary(_ caddy.Context) (cel.Library, error) { return CELMatcherImpl( "protocol", "protocol_request_string", []*cel.Type{cel.StringType}, func(data ref.Val) (RequestMatcher, error) { protocolStr, ok := data.(types.String) if !ok { return nil, errors.New("protocol argument was not a string") } return MatchProtocol(strings.ToLower(string(protocolStr))), nil }, ) } // CaddyModule returns the Caddy module information. func (MatchNot) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.matchers.not", New: func() caddy.Module { return new(MatchNot) }, } } // UnmarshalCaddyfile implements caddyfile.Unmarshaler. func (m *MatchNot) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { matcherSet, err := ParseCaddyfileNestedMatcherSet(d) if err != nil { return err } m.MatcherSetsRaw = append(m.MatcherSetsRaw, matcherSet) } return nil } // UnmarshalJSON satisfies json.Unmarshaler. It puts the JSON // bytes directly into m's MatcherSetsRaw field. func (m *MatchNot) UnmarshalJSON(data []byte) error { return json.Unmarshal(data, &m.MatcherSetsRaw) } // MarshalJSON satisfies json.Marshaler by marshaling // m's raw matcher sets. func (m MatchNot) MarshalJSON() ([]byte, error) { return json.Marshal(m.MatcherSetsRaw) } // Provision loads the matcher modules to be negated. func (m *MatchNot) Provision(ctx caddy.Context) error { matcherSets, err := ctx.LoadModule(m, "MatcherSetsRaw") if err != nil { return fmt.Errorf("loading matcher sets: %v", err) } for _, modMap := range matcherSets.([]map[string]any) { var ms MatcherSet for _, modIface := range modMap { ms = append(ms, modIface.(RequestMatcher)) } m.MatcherSets = append(m.MatcherSets, ms) } return nil } // Match returns true if r matches m. Since this matcher negates // the embedded matchers, false is returned if any of its matcher // sets return true. func (m MatchNot) Match(r *http.Request) bool { for _, ms := range m.MatcherSets { if ms.Match(r) { return false } } return true } // MatchRegexp is an embedable type for matching // using regular expressions. It adds placeholders // to the request's replacer. type MatchRegexp struct { // A unique name for this regular expression. Optional, // but useful to prevent overwriting captures from other // regexp matchers. Name string `json:"name,omitempty"` // The regular expression to evaluate, in RE2 syntax, // which is the same general syntax used by Go, Perl, // and Python. For details, see // [Go's regexp package](https://golang.org/pkg/regexp/). // Captures are accessible via placeholders. Unnamed // capture groups are exposed as their numeric, 1-based // index, while named capture groups are available by // the capture group name. Pattern string `json:"pattern"` compiled *regexp.Regexp phPrefix string } // Provision compiles the regular expression. func (mre *MatchRegexp) Provision(caddy.Context) error { re, err := regexp.Compile(mre.Pattern) if err != nil { return fmt.Errorf("compiling matcher regexp %s: %v", mre.Pattern, err) } mre.compiled = re mre.phPrefix = regexpPlaceholderPrefix if mre.Name != "" { mre.phPrefix += "." + mre.Name } return nil } // Validate ensures mre is set up correctly. func (mre *MatchRegexp) Validate() error { if mre.Name != "" && !wordRE.MatchString(mre.Name) { return fmt.Errorf("invalid regexp name (must contain only word characters): %s", mre.Name) } return nil } // Match returns true if input matches the compiled regular // expression in mre. It sets values on the replacer repl // associated with capture groups, using the given scope // (namespace). func (mre *MatchRegexp) Match(input string, repl *caddy.Replacer) bool { matches := mre.compiled.FindStringSubmatch(input) if matches == nil { return false } // save all capture groups, first by index for i, match := range matches { key := mre.phPrefix + "." + strconv.Itoa(i) repl.Set(key, match) } // then by name for i, name := range mre.compiled.SubexpNames() { if i != 0 && name != "" { key := mre.phPrefix + "." + name repl.Set(key, matches[i]) } } return true } // UnmarshalCaddyfile implements caddyfile.Unmarshaler. func (mre *MatchRegexp) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { // If this is the second iteration of the loop // then there's more than one path_regexp matcher // and we would end up overwriting the old one if mre.Pattern != "" { return d.Err("regular expression can only be used once per named matcher") } args := d.RemainingArgs() switch len(args) { case 1: mre.Pattern = args[0] case 2: mre.Name = args[0] mre.Pattern = args[1] default: return d.ArgErr() } if d.NextBlock(0) { return d.Err("malformed path_regexp matcher: blocks are not supported") } } return nil } // ParseCaddyfileNestedMatcher parses the Caddyfile tokens for a nested // matcher set, and returns its raw module map value. func ParseCaddyfileNestedMatcherSet(d *caddyfile.Dispenser) (caddy.ModuleMap, error) { matcherMap := make(map[string]RequestMatcher) // in case there are multiple instances of the same matcher, concatenate // their tokens (we expect that UnmarshalCaddyfile should be able to // handle more than one segment); otherwise, we'd overwrite other // instances of the matcher in this set tokensByMatcherName := make(map[string][]caddyfile.Token) for nesting := d.Nesting(); d.NextArg() || d.NextBlock(nesting); { matcherName := d.Val() tokensByMatcherName[matcherName] = append(tokensByMatcherName[matcherName], d.NextSegment()...) } for matcherName, tokens := range tokensByMatcherName { mod, err := caddy.GetModule("http.matchers." + matcherName) if err != nil { return nil, d.Errf("getting matcher module '%s': %v", matcherName, err) } unm, ok := mod.New().(caddyfile.Unmarshaler) if !ok { return nil, d.Errf("matcher module '%s' is not a Caddyfile unmarshaler", matcherName) } err = unm.UnmarshalCaddyfile(caddyfile.NewDispenser(tokens)) if err != nil { return nil, err } rm, ok := unm.(RequestMatcher) if !ok { return nil, fmt.Errorf("matcher module '%s' is not a request matcher", matcherName) } matcherMap[matcherName] = rm } // we should now have a functional matcher, but we also // need to be able to marshal as JSON, otherwise config // adaptation will be missing the matchers! matcherSet := make(caddy.ModuleMap) for name, matcher := range matcherMap { jsonBytes, err := json.Marshal(matcher) if err != nil { return nil, fmt.Errorf("marshaling %T matcher: %v", matcher, err) } matcherSet[name] = jsonBytes } return matcherSet, nil } var wordRE = regexp.MustCompile(`\w+`) const regexpPlaceholderPrefix = "http.regexp" // MatcherErrorVarKey is the key used for the variable that // holds an optional error emitted from a request matcher, // to short-circuit the handler chain, since matchers cannot // return errors via the RequestMatcher interface. const MatcherErrorVarKey = "matchers.error" // Interface guards var ( _ RequestMatcher = (*MatchHost)(nil) _ caddy.Provisioner = (*MatchHost)(nil) _ RequestMatcher = (*MatchPath)(nil) _ RequestMatcher = (*MatchPathRE)(nil) _ caddy.Provisioner = (*MatchPathRE)(nil) _ RequestMatcher = (*MatchMethod)(nil) _ RequestMatcher = (*MatchQuery)(nil) _ RequestMatcher = (*MatchHeader)(nil) _ RequestMatcher = (*MatchHeaderRE)(nil) _ caddy.Provisioner = (*MatchHeaderRE)(nil) _ RequestMatcher = (*MatchProtocol)(nil) _ RequestMatcher = (*MatchNot)(nil) _ caddy.Provisioner = (*MatchNot)(nil) _ caddy.Provisioner = (*MatchRegexp)(nil) _ caddyfile.Unmarshaler = (*MatchHost)(nil) _ caddyfile.Unmarshaler = (*MatchPath)(nil) _ caddyfile.Unmarshaler = (*MatchPathRE)(nil) _ caddyfile.Unmarshaler = (*MatchMethod)(nil) _ caddyfile.Unmarshaler = (*MatchQuery)(nil) _ caddyfile.Unmarshaler = (*MatchHeader)(nil) _ caddyfile.Unmarshaler = (*MatchHeaderRE)(nil) _ caddyfile.Unmarshaler = (*MatchProtocol)(nil) _ caddyfile.Unmarshaler = (*VarsMatcher)(nil) _ caddyfile.Unmarshaler = (*MatchVarsRE)(nil) _ CELLibraryProducer = (*MatchHost)(nil) _ CELLibraryProducer = (*MatchPath)(nil) _ CELLibraryProducer = (*MatchPathRE)(nil) _ CELLibraryProducer = (*MatchMethod)(nil) _ CELLibraryProducer = (*MatchQuery)(nil) _ CELLibraryProducer = (*MatchHeader)(nil) _ CELLibraryProducer = (*MatchHeaderRE)(nil) _ CELLibraryProducer = (*MatchProtocol)(nil) // _ CELLibraryProducer = (*VarsMatcher)(nil) // _ CELLibraryProducer = (*MatchVarsRE)(nil) _ json.Marshaler = (*MatchNot)(nil) _ json.Unmarshaler = (*MatchNot)(nil) )
Go
caddy/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{"*.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) actual := tc.match.Match(req) 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 := tc.match.Match(req) 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 := match.Match(req) 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 := tc.match.Match(req) 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 := tc.match.Match(req) 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, }, } { 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 := tc.match.Match(req) 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 := tc.match.Match(req) 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 run := 0; run < b.N; run++ { match.Match(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, }, } { i := i // capture range value tc := tc // capture range value 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 := tc.match.Match(req) 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 := tc.match.Match(req) 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) } b.ResetTimer() for i := 0; i < b.N; i++ { matcher.Match(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"} b.ResetTimer() for i := 0; i < b.N; i++ { match.Match(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}"} b.ResetTimer() for i := 0; i < b.N; i++ { match.Match(req) } }
Go
caddy/modules/caddyhttp/metrics.go
package caddyhttp import ( "context" "net/http" "sync" "time" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" "github.com/caddyserver/caddy/v2/internal/metrics" ) // Metrics configures metrics observations. // EXPERIMENTAL and subject to change or removal. type Metrics struct{} var httpMetrics = struct { init sync.Once requestInFlight *prometheus.GaugeVec requestCount *prometheus.CounterVec requestErrors *prometheus.CounterVec requestDuration *prometheus.HistogramVec requestSize *prometheus.HistogramVec responseSize *prometheus.HistogramVec responseDuration *prometheus.HistogramVec }{ init: sync.Once{}, } func initHTTPMetrics() { const ns, sub = "caddy", "http" basicLabels := []string{"server", "handler"} httpMetrics.requestInFlight = promauto.NewGaugeVec(prometheus.GaugeOpts{ Namespace: ns, Subsystem: sub, Name: "requests_in_flight", Help: "Number of requests currently handled by this server.", }, basicLabels) httpMetrics.requestErrors = promauto.NewCounterVec(prometheus.CounterOpts{ Namespace: ns, Subsystem: sub, Name: "request_errors_total", Help: "Number of requests resulting in middleware errors.", }, basicLabels) httpMetrics.requestCount = promauto.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"} httpMetrics.requestDuration = promauto.NewHistogramVec(prometheus.HistogramOpts{ Namespace: ns, Subsystem: sub, Name: "request_duration_seconds", Help: "Histogram of round-trip request durations.", Buckets: durationBuckets, }, httpLabels) httpMetrics.requestSize = promauto.NewHistogramVec(prometheus.HistogramOpts{ Namespace: ns, Subsystem: sub, Name: "request_size_bytes", Help: "Total size of the request. Includes body", Buckets: sizeBuckets, }, httpLabels) httpMetrics.responseSize = promauto.NewHistogramVec(prometheus.HistogramOpts{ Namespace: ns, Subsystem: sub, Name: "response_size_bytes", Help: "Size of the returned response.", Buckets: sizeBuckets, }, httpLabels) httpMetrics.responseDuration = promauto.NewHistogramVec(prometheus.HistogramOpts{ Namespace: ns, Subsystem: sub, Name: "response_duration_seconds", Help: "Histogram of times to first byte in response bodies.", Buckets: durationBuckets, }, httpLabels) } // 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 } func newMetricsInstrumentedHandler(handler string, mh MiddlewareHandler) *metricsInstrumentedHandler { httpMetrics.init.Do(func() { initHTTPMetrics() }) return &metricsInstrumentedHandler{handler, mh} } 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": ""} inFlight := 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() 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() httpMetrics.requestCount.With(labels).Inc() if err != nil { httpMetrics.requestErrors.With(labels).Inc() return err } // 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(wrec.Status()) } httpMetrics.requestDuration.With(statusLabels).Observe(dur) httpMetrics.requestSize.With(statusLabels).Observe(float64(computeApproximateRequestSize(r))) httpMetrics.responseSize.With(statusLabels).Observe(float64(wrec.Size())) 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
caddy/modules/caddyhttp/metrics_test.go
package caddyhttp import ( "context" "errors" "net/http" "net/http/httptest" "testing" "github.com/prometheus/client_golang/prometheus/testutil" ) 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) { handlerErr := errors.New("oh noes") response := []byte("hello world!") h := HandlerFunc(func(w http.ResponseWriter, r *http.Request) error { if actual := testutil.ToFloat64(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("bar", mh) 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(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("empty", mh) 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) } } 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
caddy/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/elliptic" "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" "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.remote": return req.RemoteAddr, true case "http.request.remote.host": host, _, err := net.SplitHostPort(req.RemoteAddr) if err != nil { 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.path": return 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.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": id := GetVar(req.Context(), "uuid").(*requestID) 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 // 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 } // 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 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 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 { case key == "http.shutting_down": server := req.Context().Value(ServerCtxKey).(*Server) server.shutdownAtMu.RLock() defer server.shutdownAtMu.RUnlock() return !server.shutdownAt.IsZero(), true case key == "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 } 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: return elliptic.Marshal(key.Curve, key.X, key.Y), 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
caddy/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/http" "net/http/httptest" "testing" "github.com/caddyserver/caddy/v2" ) func TestHTTPVarReplacement(t *testing.T) { req, _ := http.NewRequest(http.MethodGet, "/foo/bar.tar.gz", nil) repl := caddy.NewReplacer() ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl) 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.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.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.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
caddy/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, "", 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 { for d.Next() { 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
caddy/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
caddy/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 simply calls io.Copy, // which uses io.ReaderFrom if available. func (rww *ResponseWriterWrapper) ReadFrom(r io.Reader) (n int64, err error) { 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 } // 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 // 1xx responses aren't final; just informational if statusCode < 100 || statusCode > 199 { rr.wroteHeader = true // decide whether we should buffer the response if rr.shouldBuffer == nil { rr.stream = true } else { rr.stream = !rr.shouldBuffer(rr.statusCode, rr.ResponseWriterWrapper.Header()) } } // 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.stream { return nil } if rr.statusCode == 0 { // could happen if no handlers actually wrote anything, // and this prevents a panic; status must be > 0 rr.statusCode = http.StatusOK } rr.ResponseWriterWrapper.WriteHeader(rr.statusCode) _, err := io.Copy(rr.ResponseWriterWrapper, rr.buf) return err } 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) return conn, brw, nil } // used to track the size of hijacked response writers type hijackedConn struct { net.Conn rr *responseRecorder } 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) )
Go
caddy/modules/caddyhttp/responsewriter_test.go
package caddyhttp import ( "bytes" "fmt" "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)} fmt.Println(name) if _, err := io.Copy(wrapped, src); err != nil { t.Errorf("Copy() err = %v", err) } if got := tt.responseWriter.Written(); got != srcData { t.Errorf("data = %q, want %q", got, srcData) } 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") } } }) } } 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
caddy/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)) } // 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 if !route.MatcherSets.AnyMatch(req) { // allow matchers the opportunity to short circuit // the request and trigger the error handling chain err, ok := GetVar(req.Context(), MatcherErrorVarKey).(error) if ok { // clear out the error from context, otherwise // it will cascade to the error routes (#4916) SetVar(req.Context(), MatcherErrorVarKey, nil) // return the matcher's error return err } // 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. We can't do this inline // inside a loop, because it relies on a reference to mh // not changing until the execution of its handler (which // is deferred by multiple func closures). In other words, // we need to pull this particular MiddlewareHandler // pointer into its own stack frame to preserve it so it // won't be overwritten in future loop iterations. func wrapMiddleware(ctx caddy.Context, mh MiddlewareHandler, metrics *Metrics) Middleware { handlerToUse := mh if metrics != nil { // wrap the middleware with metrics instrumentation handlerToUse = newMetricsInstrumentedHandler(caddy.GetModuleName(mh), mh) } return func(next Handler) Handler { // copy the next handler (it's an interface, so it's // just a very lightweight copy of a pointer); this // is a safeguard against the handler changing the // value, which could affect future requests (yikes) nextCopy := next return HandlerFunc(func(w http.ResponseWriter, r *http.Request) error { // TODO: This is where request tracing could be implemented // TODO: see what the std lib gives us in terms of stack tracing too return handlerToUse.ServeHTTP(w, r, nextCopy) }) } } // MatcherSet is a set of matchers which // must all match in order for the request // to be matched successfully. type MatcherSet []RequestMatcher // 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 !m.Match(r) { return false } } return true } // 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. func (ms MatcherSets) AnyMatch(req *http.Request) bool { for _, m := range ms { if m.Match(req) { return true } } return len(ms) == 0 } // 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 { reqMatcher, ok := matcher.(RequestMatcher) if !ok { return fmt.Errorf("decoded module is not a RequestMatcher: %#v", matcher) } matcherSet = append(matcherSet, reqMatcher) } *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
caddy/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" "strings" "sync" "sync/atomic" "time" "github.com/caddyserver/certmagic" "github.com/quic-go/quic-go" "github.com/quic-go/quic-go/http3" "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 { activeRequests int64 // accessed atomically // 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"` // 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. 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. The default is 15s. KeepAliveInterval caddy.Duration `json:"keepalive_interval,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"` // 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"` // If set, metrics observations will be enabled. // This setting is EXPERIMENTAL and subject to change. Metrics *Metrics `json:"metrics,omitempty"` name string primaryHandlerChain Handler errorHandlerChain Handler listenerWrappers []caddy.ListenerWrapper listeners []net.Listener tlsApp *caddytls.TLS events *caddyevents.App logger *zap.Logger accessLogger *zap.Logger errorLogger *zap.Logger ctx caddy.Context server *http.Server h3server *http3.Server h3listeners []net.PacketConn // TODO: we have to hold these because quic-go won't close listeners it didn't create h2listeners []*http2Listener 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() } // 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. // TODO: Can be removed if https://github.com/golang/go/pull/56110 is ever merged. if r.TLS == nil { // not all requests have a conn (like virtual requests) - see #5698 if conn, ok := r.Context().Value(ConnCtxKey).(net.Conn); ok { if csc, ok := conn.(connectionStateConn); ok { r.TLS = new(tls.ConnectionState) *r.TLS = csc.ConnectionState() } } } w.Header().Set("Server", "Caddy") // advertise HTTP/3, if enabled if s.h3server != nil { // keep track of active requests for QUIC transport purposes atomic.AddInt64(&s.activeRequests, 1) defer atomic.AddInt64(&s.activeRequests, -1) if r.ProtoMajor < 3 { err := s.h3server.SetQuicHeaders(w.Header()) if err != nil { s.logger.Error("setting HTTP/3 Alt-Svc header", zap.Error(err)) } } } // reject very long methods; probably a mistake or an attack if len(r.Method) > 32 { if s.shouldLogRequest(r) { s.accessLogger.Debug("rejecting request with long method", 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 { // TODO: Remove duplex_go12*.go abstraction once our // minimum Go version is 1.21 or later err := enableFullDuplex(w) if err != nil { s.accessLogger.Warn("failed to enable full duplex", zap.Error(err)) } } // encode 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 shouldLogCredentials := s.Logs != nil && s.Logs.ShouldLogCredentials loggableReq := zap.Object("request", LoggableHTTPRequest{ Request: r, ShouldLogCredentials: shouldLogCredentials, }) errLog := s.errorLogger.With(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 } // 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 logger := errLog if s.Logs != nil { logger = s.Logs.wrapLogger(logger, r.Host) } logger = logger.With(zap.Duration("duration", duration)) // 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) if s.Errors != nil && len(s.Errors.Routes) > 0 { // execute user-defined error handling route err2 := s.errorHandlerChain.ServeHTTP(w, r) if err2 == nil { // user's error route handled the error response // successfully, so now just log the error logger.Debug(errMsg, errFields...) } else { // well... this is awkward errFields = append([]zapcore.Field{ zap.String("error", err2.Error()), zap.Namespace("first_error"), zap.String("msg", errMsg), }, errFields...) logger.Error("error handling handler error", errFields...) if handlerErr, ok := err.(HandlerError); ok { w.WriteHeader(handlerErr.StatusCode) } else { w.WriteHeader(http.StatusInternalServerError) } } } else { if errStatus >= 500 { logger.Error(errMsg, errFields...) } else { logger.Debug(errMsg, errFields...) } 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 { for _, cp := range s.TLSConnPolicies { if cp.ClientAuthentication != nil && cp.ClientAuthentication.Active() { return true } } return false } // 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 { addr.Network = getHTTP3Network(addr.Network) lnAny, err := addr.Listen(s.ctx, 0, net.ListenConfig{}) if err != nil { return err } ln := lnAny.(net.PacketConn) h3ln, err := caddy.ListenQUIC(ln, tlsCfg, &s.activeRequests) 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, // TODO: remove this config when draft versions are no longer supported (we have no need to support drafts) QuicConfig: &quic.Config{ Versions: []quic.VersionNumber{quic.Version1, quic.Version2}, }, } } s.h3listeners = append(s.h3listeners, ln) //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 on server shutdown. func (s *Server) RegisterOnShutdown(f func()) { s.onShutdownFuncs = append(s.onShutdownFuncs, 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 } if _, ok := s.Logs.LoggerNames[r.Host]; ok { // 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(r.Host, dh) { return false } } // if configured, this host is not mapped and thus must not be logged return !s.Logs.SkipUnmappedHosts } // 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, ) { // this request may be flagged as omitted from the logs if skipLog, ok := GetVar(r.Context(), SkipLogVar).(bool); ok && skipLog { return } repl.Set("http.response.status", wrec.Status()) // will be 0 if no response is written by us (Go will write 200 to client) repl.Set("http.response.size", wrec.Size()) repl.Set("http.response.duration", duration) repl.Set("http.response.duration_ms", duration.Seconds()*1e3) // multiply seconds to preserve decimal (see #4666) logger := accLog if s.Logs != nil { logger = s.Logs.wrapLogger(logger, r.Host) } log := logger.Info if wrec.Status() >= 400 { log = logger.Error } userID, _ := repl.GetString("http.auth.user.id") reqBodyLength := 0 if bodyReader != nil { reqBodyLength = bodyReader.Length } extra := r.Context().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", wrec.Size()), zap.Int("status", wrec.Status()), zap.Object("resp_headers", LoggableHTTPHeader{ Header: wrec.Header(), ShouldLogCredentials: shouldLogCredentials, })) fields = append(fields, extra.fields...) log("handled request", fields...) } // protocol returns true if the protocol proto is configured/enabled. func (s *Server) protocol(proto string) bool { for _, p := range s.Protocols { if p == 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) return http.Request{ Method: req.Method, RemoteAddr: req.RemoteAddr, RequestURI: req.RequestURI, URL: urlCopy, } } // determineTrustedProxy parses the remote IP address of // the request, and determines (if the server configured it) // if the client is a trusted proxy. If trusted, also returns // the real client IP if possible. func determineTrustedProxy(r *http.Request, s *Server) (bool, string) { // If there's no server, then we can't check anything if s == nil { return false, "" } // 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(r.RemoteAddr) if err != nil { return false, "" } // 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 false, "" } // Check if the client is a trusted proxy if s.trustedProxies == nil { return false, ipAddr.String() } for _, ipRange := range s.trustedProxies.GetIPRanges(r) { if ipRange.Contains(ipAddr) { // We trust the proxy, so let's try to // determine the real client IP return true, trustedRealClientIP(r, s.ClientIPHeaders, ipAddr.String()) } } return false, ipAddr.String() } // trustedRealClientIP finds the client IP from the request assuming it is // from a trusted client. If there is no client IP headers, then the // direct remote address is returned. If there are client IP headers, // then the first value from those headers is used. func trustedRealClientIP(r *http.Request, headers []string, clientIP string) string { // Read all the values of the configured client IP headers, in order var values []string for _, field := range headers { values = append(values, r.Header.Values(field)...) } // If we don't have any values, then give up if len(values) == 0 { return clientIP } // Since there can be many header values, we need to // join them together before splitting to get the full list allValues := strings.Split(strings.Join(values, ","), ",") // Get first valid left-most IP address for _, ip := range allValues { ip, _, _ = strings.Cut(strings.TrimSpace(ip), "%") ipAddr, err := netip.ParseAddr(ip) if err != nil { continue } return ipAddr.String() } // We didn't find a valid IP return clientIP } // cloneURL makes a copy of r.URL and returns a // new value that doesn't reference the original. func cloneURL(from, to *url.URL) { *to = *from if from.User != nil { userInfo := new(url.Userinfo) *userInfo = *from.User to.User = userInfo } } // lengthReader is an io.ReadCloser that keeps track of the // number of bytes read from the request body. type lengthReader struct { Source io.ReadCloser Length int } func (r *lengthReader) Read(b []byte) (int, error) { n, err := r.Source.Read(b) r.Length += n return n, err } func (r *lengthReader) Close() error { return r.Source.Close() } // Context keys for HTTP request context values. const ( // For referencing the server instance ServerCtxKey caddy.CtxKey = "server" // For the request's variable table VarsCtxKey caddy.CtxKey = "vars" // For a partial copy of the unmodified request that // originally came into the server's entry handler OriginalRequestCtxKey caddy.CtxKey = "original_request" // For referencing underlying net.Conn ConnCtxKey caddy.CtxKey = "conn" // For tracking whether the client is a trusted proxy TrustedProxyVarKey string = "trusted_proxy" // For tracking the real client IP (affected by trusted_proxy) ClientIPVarKey string = "client_ip" ) var networkTypesHTTP3 = map[string]string{ "unix": "unixgram", "tcp4": "udp4", "tcp6": "udp6", } // RegisterNetworkHTTP3 registers a mapping from non-HTTP/3 network to HTTP/3 // network. This should be called during init() and will panic if the network // type is standard, reserved, or already registered. // // EXPERIMENTAL: Subject to change. func RegisterNetworkHTTP3(originalNetwork, h3Network string) { if _, ok := networkTypesHTTP3[strings.ToLower(originalNetwork)]; ok { panic("network type " + originalNetwork + " is already registered") } networkTypesHTTP3[originalNetwork] = h3Network } func getHTTP3Network(originalNetwork string) string { h3Network, ok := networkTypesHTTP3[strings.ToLower(originalNetwork)] if !ok { // TODO: Maybe a better default is to not enable HTTP/3 if we do not know the network? return "udp" } return h3Network }
Go
caddy/modules/caddyhttp/server_test.go
package caddyhttp import ( "bytes" "context" "io" "net/http" "net/http/httptest" "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_WithTraceID(t *testing.T) { s := &Server{} extra := new(ExtraLogFields) ctx := context.WithValue(context.Background(), ExtraLogFieldsCtxKey, extra) extra.Add(zap.String("traceID", "1234567890abcdef")) 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" }`, 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) b.ResetTimer() for i := 0; i < b.N; i++ { s.logRequest(accLog, req, wrec, &duration, repl, bodyReader, false) } } func BenchmarkServer_LogRequest_WithTraceID(b *testing.B) { s := &Server{} extra := new(ExtraLogFields) ctx := context.WithValue(context.Background(), ExtraLogFieldsCtxKey, extra) extra.Add(zap.String("traceID", "1234567890abcdef")) 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) b.ResetTimer() for i := 0; i < b.N; i++ { s.logRequest(accLog, req, wrec, &duration, repl, bodyReader, false) } }
Go
caddy/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 { for d.Next() { 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", e.Error)) } // Interface guard var ( _ MiddlewareHandler = (*StaticError)(nil) _ caddyfile.Unmarshaler = (*StaticError)(nil) )
Go
caddy/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" "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().StringSliceP("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 { for d.Next() { 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(s.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 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 var statusCodeFlagSpecified bool for _, fl := range os.Args { if fl == "--status" { statusCodeFlagSpecified = true break } } // 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.GetStringSlice("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) } // expand listen address, if more than one port listenAddr, err := caddy.ParseNetworkAddress(listen) if err != nil { return caddy.ExitCodeFailedStartup, err } listenAddrs := make([]string, 0, listenAddr.PortRangeSize()) for offset := uint(0); offset < listenAddr.PortRangeSize(); offset++ { listenAddrs = append(listenAddrs, listenAddr.JoinHostPort(offset)) } // build each HTTP server httpApp := App{Servers: make(map[string]*Server)} for i, addr := range listenAddrs { 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: listenAddr.StartPort + uint(i), Address: addr, } tpl, err := template.New("body").Parse(body) if err != nil { return caddy.ExitCodeFailedStartup, err } buf := new(bytes.Buffer) err = tpl.Execute(buf, tplCtx) if err != nil { return caddy.ExitCodeFailedStartup, 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) } // save server httpApp.Servers[fmt.Sprintf("static%d", i)] = 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
caddy/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
caddy/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
caddy/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" "strings" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) 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 } return next.ServeHTTP(w, r) } // UnmarshalCaddyfile implements caddyfile.Unmarshaler. Syntax: // // vars [<name> <val>] { // <name> <val> // ... // } func (m *VarsMiddleware) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { 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 } for d.Next() { if err := nextVar(true); err != nil { return err } for nesting := d.Nesting(); d.NextBlock(nesting); { 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) } 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 { if len(m) == 0 { return true } 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() default: varStr = fmt.Sprintf("%v", vv) } if varStr == matcherValExpanded { return true } } } return false } // 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) } 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 } (*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 { 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() default: varStr = fmt.Sprintf("%v", vv) } valExpanded := repl.ReplaceAll(varStr, "") if match := val.Match(valExpanded, repl); match { return match } } return false } // 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) _ RequestMatcher = (*VarsMatcher)(nil) _ caddyfile.Unmarshaler = (*VarsMatcher)(nil) )
Go
caddy/modules/caddyhttp/caddyauth/basicauth.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 caddyauth import ( "encoding/base64" "encoding/hex" "encoding/json" "fmt" weakrand "math/rand" "net/http" "strings" "sync" "golang.org/x/sync/singleflight" "github.com/caddyserver/caddy/v2" ) func init() { caddy.RegisterModule(HTTPBasicAuth{}) } // HTTPBasicAuth facilitates HTTP basic authentication. type HTTPBasicAuth struct { // The algorithm with which the passwords are hashed. Default: bcrypt HashRaw json.RawMessage `json:"hash,omitempty" caddy:"namespace=http.authentication.hashes inline_key=algorithm"` // The list of accounts to authenticate. AccountList []Account `json:"accounts,omitempty"` // The name of the realm. Default: restricted Realm string `json:"realm,omitempty"` // If non-nil, a mapping of plaintext passwords to their // hashes will be cached in memory (with random eviction). // This can greatly improve the performance of traffic-heavy // servers that use secure password hashing algorithms, with // the downside that plaintext passwords will be stored in // memory for a longer time (this should not be a problem // as long as your machine is not compromised, at which point // all bets are off, since basicauth necessitates plaintext // passwords being received over the wire anyway). Note that // a cache hit does not mean it is a valid password. HashCache *Cache `json:"hash_cache,omitempty"` Accounts map[string]Account `json:"-"` Hash Comparer `json:"-"` // fakePassword is used when a given user is not found, // so that timing side-channels can be mitigated: it gives // us something to hash and compare even if the user does // not exist, which should have similar timing as a user // account that does exist. fakePassword []byte } // CaddyModule returns the Caddy module information. func (HTTPBasicAuth) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.authentication.providers.http_basic", New: func() caddy.Module { return new(HTTPBasicAuth) }, } } // Provision provisions the HTTP basic auth provider. func (hba *HTTPBasicAuth) Provision(ctx caddy.Context) error { if hba.HashRaw == nil { hba.HashRaw = json.RawMessage(`{"algorithm": "bcrypt"}`) } // load password hasher hasherIface, err := ctx.LoadModule(hba, "HashRaw") if err != nil { return fmt.Errorf("loading password hasher module: %v", err) } hba.Hash = hasherIface.(Comparer) if hba.Hash == nil { return fmt.Errorf("hash is required") } // if supported, generate a fake password we can compare against if needed if hasher, ok := hba.Hash.(Hasher); ok { hba.fakePassword = hasher.FakeHash() } repl := caddy.NewReplacer() // load account list hba.Accounts = make(map[string]Account) for i, acct := range hba.AccountList { if _, ok := hba.Accounts[acct.Username]; ok { return fmt.Errorf("account %d: username is not unique: %s", i, acct.Username) } acct.Username = repl.ReplaceAll(acct.Username, "") acct.Password = repl.ReplaceAll(acct.Password, "") acct.Salt = repl.ReplaceAll(acct.Salt, "") if acct.Username == "" || acct.Password == "" { return fmt.Errorf("account %d: username and password are required", i) } // TODO: Remove support for redundantly-encoded b64-encoded hashes // Passwords starting with '$' are likely in Modular Crypt Format, // so we don't need to base64 decode them. But historically, we // required redundant base64, so we try to decode it otherwise. if strings.HasPrefix(acct.Password, "$") { acct.password = []byte(acct.Password) } else { acct.password, err = base64.StdEncoding.DecodeString(acct.Password) if err != nil { return fmt.Errorf("base64-decoding password: %v", err) } } if acct.Salt != "" { acct.salt, err = base64.StdEncoding.DecodeString(acct.Salt) if err != nil { return fmt.Errorf("base64-decoding salt: %v", err) } } hba.Accounts[acct.Username] = acct } hba.AccountList = nil // allow GC to deallocate if hba.HashCache != nil { hba.HashCache.cache = make(map[string]bool) hba.HashCache.mu = new(sync.RWMutex) hba.HashCache.g = new(singleflight.Group) } return nil } // Authenticate validates the user credentials in req and returns the user, if valid. func (hba HTTPBasicAuth) Authenticate(w http.ResponseWriter, req *http.Request) (User, bool, error) { username, plaintextPasswordStr, ok := req.BasicAuth() if !ok { return hba.promptForCredentials(w, nil) } account, accountExists := hba.Accounts[username] if !accountExists { // don't return early if account does not exist; we want // to try to avoid side-channels that leak existence, so // we use a fake password to simulate realistic CPU cycles account.password = hba.fakePassword } same, err := hba.correctPassword(account, []byte(plaintextPasswordStr)) if err != nil || !same || !accountExists { return hba.promptForCredentials(w, err) } return User{ID: username}, true, nil } func (hba HTTPBasicAuth) correctPassword(account Account, plaintextPassword []byte) (bool, error) { compare := func() (bool, error) { return hba.Hash.Compare(account.password, plaintextPassword, account.salt) } // if no caching is enabled, simply return the result of hashing + comparing if hba.HashCache == nil { return compare() } // compute a cache key that is unique for these input parameters cacheKey := hex.EncodeToString(append(append(account.password, account.salt...), plaintextPassword...)) // fast track: if the result of the input is already cached, use it hba.HashCache.mu.RLock() same, ok := hba.HashCache.cache[cacheKey] hba.HashCache.mu.RUnlock() if ok { return same, nil } // slow track: do the expensive op, then add it to the cache // but perform it in a singleflight group so that multiple // parallel requests using the same password don't cause a // thundering herd problem by all performing the same hashing // operation before the first one finishes and caches it. v, err, _ := hba.HashCache.g.Do(cacheKey, func() (any, error) { return compare() }) if err != nil { return false, err } same = v.(bool) hba.HashCache.mu.Lock() if len(hba.HashCache.cache) >= 1000 { hba.HashCache.makeRoom() // keep cache size under control } hba.HashCache.cache[cacheKey] = same hba.HashCache.mu.Unlock() return same, nil } func (hba HTTPBasicAuth) promptForCredentials(w http.ResponseWriter, err error) (User, bool, error) { // browsers show a message that says something like: // "The website says: <realm>" // which is kinda dumb, but whatever. realm := hba.Realm if realm == "" { realm = "restricted" } w.Header().Set("WWW-Authenticate", fmt.Sprintf(`Basic realm="%s"`, realm)) return User{}, false, err } // Cache enables caching of basic auth results. This is especially // helpful for secure password hashes which can be expensive to // compute on every HTTP request. type Cache struct { mu *sync.RWMutex g *singleflight.Group // map of concatenated hashed password + plaintext password + salt, to result cache map[string]bool } // makeRoom deletes about 1/10 of the items in the cache // in order to keep its size under control. It must not be // called without a lock on c.mu. func (c *Cache) makeRoom() { // we delete more than just 1 entry so that we don't have // to do this on every request; assuming the capacity of // the cache is on a long tail, we can save a lot of CPU // time by doing a whole bunch of deletions now and then // we won't have to do them again for a while numToDelete := len(c.cache) / 10 if numToDelete < 1 { numToDelete = 1 } for deleted := 0; deleted <= numToDelete; deleted++ { // Go maps are "nondeterministic" not actually random, // so although we could just chop off the "front" of the // map with less code, this is a heavily skewed eviction // strategy; generating random numbers is cheap and // ensures a much better distribution. //nolint:gosec rnd := weakrand.Intn(len(c.cache)) i := 0 for key := range c.cache { if i == rnd { delete(c.cache, key) break } i++ } } } // Comparer is a type that can securely compare // a plaintext password with a hashed password // in constant-time. Comparers should hash the // plaintext password and then use constant-time // comparison. type Comparer interface { // Compare returns true if the result of hashing // plaintextPassword with salt is hashedPassword, // false otherwise. An error is returned only if // there is a technical/configuration error. Compare(hashedPassword, plaintextPassword, salt []byte) (bool, error) } // Hasher is a type that can generate a secure hash // given a plaintext and optional salt (for algorithms // that require a salt). Hashing modules which implement // this interface can be used with the hash-password // subcommand as well as benefitting from anti-timing // features. A hasher also returns a fake hash which // can be used for timing side-channel mitigation. type Hasher interface { Hash(plaintext, salt []byte) ([]byte, error) FakeHash() []byte } // Account contains a username, password, and salt (if applicable). type Account struct { // A user's username. Username string `json:"username"` // The user's hashed password, base64-encoded. Password string `json:"password"` // The user's password salt, base64-encoded; for // algorithms where external salt is needed. Salt string `json:"salt,omitempty"` password, salt []byte } // Interface guards var ( _ caddy.Provisioner = (*HTTPBasicAuth)(nil) _ Authenticator = (*HTTPBasicAuth)(nil) )
Go
caddy/modules/caddyhttp/caddyauth/caddyauth.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 caddyauth import ( "fmt" "net/http" "go.uber.org/zap" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func init() { caddy.RegisterModule(Authentication{}) } // Authentication is a middleware which provides user authentication. // Rejects requests with HTTP 401 if the request is not authenticated. // // After a successful authentication, the placeholder // `{http.auth.user.id}` will be set to the username, and also // `{http.auth.user.*}` placeholders may be set for any authentication // modules that provide user metadata. // // Its API is still experimental and may be subject to change. type Authentication struct { // A set of authentication providers. If none are specified, // all requests will always be unauthenticated. ProvidersRaw caddy.ModuleMap `json:"providers,omitempty" caddy:"namespace=http.authentication.providers"` Providers map[string]Authenticator `json:"-"` logger *zap.Logger } // CaddyModule returns the Caddy module information. func (Authentication) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.handlers.authentication", New: func() caddy.Module { return new(Authentication) }, } } // Provision sets up a. func (a *Authentication) Provision(ctx caddy.Context) error { a.logger = ctx.Logger() a.Providers = make(map[string]Authenticator) mods, err := ctx.LoadModule(a, "ProvidersRaw") if err != nil { return fmt.Errorf("loading authentication providers: %v", err) } for modName, modIface := range mods.(map[string]any) { a.Providers[modName] = modIface.(Authenticator) } return nil } func (a Authentication) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { var user User var authed bool var err error for provName, prov := range a.Providers { user, authed, err = prov.Authenticate(w, r) if err != nil { a.logger.Error("auth provider returned error", zap.String("provider", provName), zap.Error(err)) continue } if authed { break } } if !authed { return caddyhttp.Error(http.StatusUnauthorized, fmt.Errorf("not authenticated")) } repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) repl.Set("http.auth.user.id", user.ID) for k, v := range user.Metadata { repl.Set("http.auth.user."+k, v) } return next.ServeHTTP(w, r) } // Authenticator is a type which can authenticate a request. // If a request was not authenticated, it returns false. An // error is only returned if authenticating the request fails // for a technical reason (not for bad/missing credentials). type Authenticator interface { Authenticate(http.ResponseWriter, *http.Request) (User, bool, error) } // User represents an authenticated user. type User struct { // The ID of the authenticated user. ID string // Any other relevant data about this // user. Keys should be adhere to Caddy // conventions (snake_casing), as all // keys will be made available as // placeholders. Metadata map[string]string } // Interface guards var ( _ caddy.Provisioner = (*Authentication)(nil) _ caddyhttp.MiddlewareHandler = (*Authentication)(nil) )
Go
caddy/modules/caddyhttp/caddyauth/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 caddyauth import ( "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" ) func init() { httpcaddyfile.RegisterHandlerDirective("basicauth", parseCaddyfile) } // parseCaddyfile sets up the handler from Caddyfile tokens. Syntax: // // basicauth [<matcher>] [<hash_algorithm> [<realm>]] { // <username> <hashed_password_base64> [<salt_base64>] // ... // } // // If no hash algorithm is supplied, bcrypt will be assumed. func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) { var ba HTTPBasicAuth ba.HashCache = new(Cache) for h.Next() { var cmp Comparer args := h.RemainingArgs() var hashName string switch len(args) { case 0: hashName = "bcrypt" case 1: hashName = args[0] case 2: hashName = args[0] ba.Realm = args[1] default: return nil, h.ArgErr() } switch hashName { case "bcrypt": cmp = BcryptHash{} case "scrypt": cmp = ScryptHash{} default: return nil, h.Errf("unrecognized hash algorithm: %s", hashName) } ba.HashRaw = caddyconfig.JSONModuleObject(cmp, "algorithm", hashName, nil) for h.NextBlock(0) { username := h.Val() var b64Pwd, b64Salt string h.Args(&b64Pwd, &b64Salt) if h.NextArg() { return nil, h.ArgErr() } if username == "" || b64Pwd == "" { return nil, h.Err("username and password cannot be empty or missing") } ba.AccountList = append(ba.AccountList, Account{ Username: username, Password: b64Pwd, Salt: b64Salt, }) } } return Authentication{ ProvidersRaw: caddy.ModuleMap{ "http_basic": caddyconfig.JSON(ba, nil), }, }, nil }
Go
caddy/modules/caddyhttp/caddyauth/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 caddyauth import ( "bufio" "bytes" "encoding/base64" "fmt" "os" "os/signal" "github.com/spf13/cobra" "golang.org/x/term" caddycmd "github.com/caddyserver/caddy/v2/cmd" "github.com/caddyserver/caddy/v2" ) func init() { caddycmd.RegisterCommand(caddycmd.Command{ Name: "hash-password", Usage: "[--algorithm <name>] [--salt <string>] [--plaintext <password>]", Short: "Hashes a password and writes base64", Long: ` Convenient way to hash a plaintext password. The resulting hash is written to stdout as a base64 string. --plaintext, when omitted, will be read from stdin. If Caddy is attached to a controlling tty, the plaintext will not be echoed. --algorithm may be bcrypt or scrypt. If scrypt, the default parameters are used. Use the --salt flag for algorithms which require a salt to be provided (scrypt). Note that scrypt is deprecated. Please use 'bcrypt' instead. `, CobraFunc: func(cmd *cobra.Command) { cmd.Flags().StringP("plaintext", "p", "", "The plaintext password") cmd.Flags().StringP("salt", "s", "", "The password salt") cmd.Flags().StringP("algorithm", "a", "bcrypt", "Name of the hash algorithm") cmd.RunE = caddycmd.WrapCommandFuncForCobra(cmdHashPassword) }, }) } func cmdHashPassword(fs caddycmd.Flags) (int, error) { var err error algorithm := fs.String("algorithm") plaintext := []byte(fs.String("plaintext")) salt := []byte(fs.String("salt")) if len(plaintext) == 0 { fd := int(os.Stdin.Fd()) if term.IsTerminal(fd) { // ensure the terminal state is restored on SIGINT state, _ := term.GetState(fd) c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt) go func() { <-c _ = term.Restore(fd, state) os.Exit(caddy.ExitCodeFailedStartup) }() defer signal.Stop(c) fmt.Fprint(os.Stderr, "Enter password: ") plaintext, err = term.ReadPassword(fd) fmt.Fprintln(os.Stderr) if err != nil { return caddy.ExitCodeFailedStartup, err } fmt.Fprint(os.Stderr, "Confirm password: ") confirmation, err := term.ReadPassword(fd) fmt.Fprintln(os.Stderr) if err != nil { return caddy.ExitCodeFailedStartup, err } if !bytes.Equal(plaintext, confirmation) { return caddy.ExitCodeFailedStartup, fmt.Errorf("password does not match") } } else { rd := bufio.NewReader(os.Stdin) plaintext, err = rd.ReadBytes('\n') if err != nil { return caddy.ExitCodeFailedStartup, err } plaintext = plaintext[:len(plaintext)-1] // Trailing newline } if len(plaintext) == 0 { return caddy.ExitCodeFailedStartup, fmt.Errorf("plaintext is required") } } var hash []byte var hashString string switch algorithm { case "bcrypt": hash, err = BcryptHash{}.Hash(plaintext, nil) hashString = string(hash) case "scrypt": def := ScryptHash{} def.SetDefaults() hash, err = def.Hash(plaintext, salt) hashString = base64.StdEncoding.EncodeToString(hash) default: return caddy.ExitCodeFailedStartup, fmt.Errorf("unrecognized hash algorithm: %s", algorithm) } if err != nil { return caddy.ExitCodeFailedStartup, err } fmt.Println(hashString) return 0, nil }
Go
caddy/modules/caddyhttp/caddyauth/hashes.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 caddyauth import ( "crypto/subtle" "encoding/base64" "golang.org/x/crypto/bcrypt" "golang.org/x/crypto/scrypt" "github.com/caddyserver/caddy/v2" ) func init() { caddy.RegisterModule(BcryptHash{}) caddy.RegisterModule(ScryptHash{}) } // BcryptHash implements the bcrypt hash. type BcryptHash struct{} // CaddyModule returns the Caddy module information. func (BcryptHash) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.authentication.hashes.bcrypt", New: func() caddy.Module { return new(BcryptHash) }, } } // Compare compares passwords. func (BcryptHash) Compare(hashed, plaintext, _ []byte) (bool, error) { err := bcrypt.CompareHashAndPassword(hashed, plaintext) if err == bcrypt.ErrMismatchedHashAndPassword { return false, nil } if err != nil { return false, err } return true, nil } // Hash hashes plaintext using a random salt. func (BcryptHash) Hash(plaintext, _ []byte) ([]byte, error) { return bcrypt.GenerateFromPassword(plaintext, 14) } // FakeHash returns a fake hash. func (BcryptHash) FakeHash() []byte { // hashed with the following command: // caddy hash-password --plaintext "antitiming" --algorithm "bcrypt" return []byte("$2a$14$X3ulqf/iGxnf1k6oMZ.RZeJUoqI9PX2PM4rS5lkIKJXduLGXGPrt6") } // ScryptHash implements the scrypt KDF as a hash. // // DEPRECATED, please use 'bcrypt' instead. type ScryptHash struct { // scrypt's N parameter. If unset or 0, a safe default is used. N int `json:"N,omitempty"` // scrypt's r parameter. If unset or 0, a safe default is used. R int `json:"r,omitempty"` // scrypt's p parameter. If unset or 0, a safe default is used. P int `json:"p,omitempty"` // scrypt's key length parameter (in bytes). If unset or 0, a // safe default is used. KeyLength int `json:"key_length,omitempty"` } // CaddyModule returns the Caddy module information. func (ScryptHash) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.authentication.hashes.scrypt", New: func() caddy.Module { return new(ScryptHash) }, } } // Provision sets up s. func (s *ScryptHash) Provision(ctx caddy.Context) error { s.SetDefaults() ctx.Logger().Warn("use of 'scrypt' is deprecated, please use 'bcrypt' instead") return nil } // SetDefaults sets safe default parameters, but does // not overwrite existing values. Each default parameter // is set independently; it does not check to ensure // that r*p < 2^30. The defaults chosen are those as // recommended in 2019 by // https://godoc.org/golang.org/x/crypto/scrypt. func (s *ScryptHash) SetDefaults() { if s.N == 0 { s.N = 32768 } if s.R == 0 { s.R = 8 } if s.P == 0 { s.P = 1 } if s.KeyLength == 0 { s.KeyLength = 32 } } // Compare compares passwords. func (s ScryptHash) Compare(hashed, plaintext, salt []byte) (bool, error) { ourHash, err := scrypt.Key(plaintext, salt, s.N, s.R, s.P, s.KeyLength) if err != nil { return false, err } if hashesMatch(hashed, ourHash) { return true, nil } return false, nil } // Hash hashes plaintext using the given salt. func (s ScryptHash) Hash(plaintext, salt []byte) ([]byte, error) { return scrypt.Key(plaintext, salt, s.N, s.R, s.P, s.KeyLength) } // FakeHash returns a fake hash. func (ScryptHash) FakeHash() []byte { // hashed with the following command: // caddy hash-password --plaintext "antitiming" --salt "fakesalt" --algorithm "scrypt" bytes, _ := base64.StdEncoding.DecodeString("kFbjiVemlwK/ZS0tS6/UQqEDeaNMigyCs48KEsGUse8=") return bytes } func hashesMatch(pwdHash1, pwdHash2 []byte) bool { return subtle.ConstantTimeCompare(pwdHash1, pwdHash2) == 1 } // Interface guards var ( _ Comparer = (*BcryptHash)(nil) _ Comparer = (*ScryptHash)(nil) _ Hasher = (*BcryptHash)(nil) _ Hasher = (*ScryptHash)(nil) _ caddy.Provisioner = (*ScryptHash)(nil) )
Go
caddy/modules/caddyhttp/encode/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 encode import ( "strconv" "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/modules/caddyhttp" ) func init() { httpcaddyfile.RegisterHandlerDirective("encode", parseCaddyfile) } func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) { enc := new(Encode) err := enc.UnmarshalCaddyfile(h.Dispenser) if err != nil { return nil, err } return enc, nil } // UnmarshalCaddyfile sets up the handler from Caddyfile tokens. Syntax: // // encode [<matcher>] <formats...> { // gzip [<level>] // zstd // minimum_length <length> // # response matcher block // match { // status <code...> // header <field> [<value>] // } // # or response matcher single line syntax // match [header <field> [<value>]] | [status <code...>] // } // // Specifying the formats on the first line will use those formats' defaults. func (enc *Encode) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { var prefer []string responseMatchers := make(map[string]caddyhttp.ResponseMatcher) for d.Next() { for _, arg := range d.RemainingArgs() { mod, err := caddy.GetModule("http.encoders." + arg) if err != nil { return d.Errf("finding encoder module '%s': %v", mod, err) } encoding, ok := mod.New().(Encoding) if !ok { return d.Errf("module %s is not an HTTP encoding", mod) } if enc.EncodingsRaw == nil { enc.EncodingsRaw = make(caddy.ModuleMap) } enc.EncodingsRaw[arg] = caddyconfig.JSON(encoding, nil) prefer = append(prefer, arg) } for d.NextBlock(0) { switch d.Val() { case "minimum_length": if !d.NextArg() { return d.ArgErr() } minLength, err := strconv.Atoi(d.Val()) if err != nil { return err } enc.MinLength = minLength case "match": err := caddyhttp.ParseNamedResponseMatcher(d.NewFromNextSegment(), responseMatchers) if err != nil { return err } matcher := responseMatchers["match"] enc.Matcher = &matcher default: name := d.Val() modID := "http.encoders." + name unm, err := caddyfile.UnmarshalModule(d, modID) if err != nil { return err } encoding, ok := unm.(Encoding) if !ok { return d.Errf("module %s is not an HTTP encoding; is %T", modID, unm) } if enc.EncodingsRaw == nil { enc.EncodingsRaw = make(caddy.ModuleMap) } enc.EncodingsRaw[name] = caddyconfig.JSON(encoding, nil) prefer = append(prefer, name) } } } // use the order in which the encoders were defined. enc.Prefer = prefer return nil } // Interface guard var _ caddyfile.Unmarshaler = (*Encode)(nil)
Go
caddy/modules/caddyhttp/encode/encode.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 encode implements an encoder middleware for Caddy. The initial // enhancements related to Accept-Encoding, minimum content length, and // buffer/writer pools were adapted from https://github.com/xi2/httpgzip // then modified heavily to accommodate modular encoders and fix bugs. // Code borrowed from that repository is Copyright (c) 2015 The Httpgzip Authors. package encode import ( "bufio" "fmt" "io" "math" "net" "net/http" "sort" "strconv" "strings" "sync" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func init() { caddy.RegisterModule(Encode{}) } // Encode is a middleware which can encode responses. type Encode struct { // Selection of compression algorithms to choose from. The best one // will be chosen based on the client's Accept-Encoding header. EncodingsRaw caddy.ModuleMap `json:"encodings,omitempty" caddy:"namespace=http.encoders"` // If the client has no strong preference, choose these encodings in order. Prefer []string `json:"prefer,omitempty"` // Only encode responses that are at least this many bytes long. MinLength int `json:"minimum_length,omitempty"` // Only encode responses that match against this ResponseMmatcher. // The default is a collection of text-based Content-Type headers. Matcher *caddyhttp.ResponseMatcher `json:"match,omitempty"` writerPools map[string]*sync.Pool // TODO: these pools do not get reused through config reloads... } // CaddyModule returns the Caddy module information. func (Encode) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.handlers.encode", New: func() caddy.Module { return new(Encode) }, } } // Provision provisions enc. func (enc *Encode) Provision(ctx caddy.Context) error { mods, err := ctx.LoadModule(enc, "EncodingsRaw") if err != nil { return fmt.Errorf("loading encoder modules: %v", err) } for modName, modIface := range mods.(map[string]any) { err = enc.addEncoding(modIface.(Encoding)) if err != nil { return fmt.Errorf("adding encoding %s: %v", modName, err) } } if enc.MinLength == 0 { enc.MinLength = defaultMinLength } if enc.Matcher == nil { // common text-based content types enc.Matcher = &caddyhttp.ResponseMatcher{ Headers: http.Header{ "Content-Type": []string{ "text/*", "application/json*", "application/javascript*", "application/xhtml+xml*", "application/atom+xml*", "application/rss+xml*", "image/svg+xml*", }, }, } } return nil } // Validate ensures that enc's configuration is valid. func (enc *Encode) Validate() error { check := make(map[string]bool) for _, encName := range enc.Prefer { if _, ok := enc.writerPools[encName]; !ok { return fmt.Errorf("encoding %s not enabled", encName) } if _, ok := check[encName]; ok { return fmt.Errorf("encoding %s is duplicated in prefer", encName) } check[encName] = true } return nil } func isEncodeAllowed(h http.Header) bool { return !strings.Contains(h.Get("Cache-Control"), "no-transform") } func (enc *Encode) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { if isEncodeAllowed(r.Header) { for _, encName := range AcceptedEncodings(r, enc.Prefer) { if _, ok := enc.writerPools[encName]; !ok { continue // encoding not offered } w = enc.openResponseWriter(encName, w) defer w.(*responseWriter).Close() break } } return next.ServeHTTP(w, r) } func (enc *Encode) addEncoding(e Encoding) error { ae := e.AcceptEncoding() if ae == "" { return fmt.Errorf("encoder does not specify an Accept-Encoding value") } if _, ok := enc.writerPools[ae]; ok { return fmt.Errorf("encoder already added: %s", ae) } if enc.writerPools == nil { enc.writerPools = make(map[string]*sync.Pool) } enc.writerPools[ae] = &sync.Pool{ New: func() any { return e.NewEncoder() }, } return nil } // openResponseWriter creates a new response writer that may (or may not) // encode the response with encodingName. The returned response writer MUST // be closed after the handler completes. func (enc *Encode) openResponseWriter(encodingName string, w http.ResponseWriter) *responseWriter { var rw responseWriter return enc.initResponseWriter(&rw, encodingName, w) } // initResponseWriter initializes the responseWriter instance // allocated in openResponseWriter, enabling mid-stack inlining. func (enc *Encode) initResponseWriter(rw *responseWriter, encodingName string, wrappedRW http.ResponseWriter) *responseWriter { if rww, ok := wrappedRW.(*caddyhttp.ResponseWriterWrapper); ok { rw.ResponseWriter = rww } else { rw.ResponseWriter = &caddyhttp.ResponseWriterWrapper{ResponseWriter: wrappedRW} } rw.encodingName = encodingName rw.config = enc return rw } // responseWriter writes to an underlying response writer // using the encoding represented by encodingName and // configured by config. type responseWriter struct { http.ResponseWriter encodingName string w Encoder config *Encode statusCode int wroteHeader bool } // WriteHeader stores the status to write when the time comes // to actually write the header. func (rw *responseWriter) WriteHeader(status int) { rw.statusCode = status } // Match determines, if encoding should be done based on the ResponseMatcher. func (enc *Encode) Match(rw *responseWriter) bool { return enc.Matcher.Match(rw.statusCode, rw.Header()) } // Flush implements http.Flusher. It delays the actual Flush of the underlying ResponseWriterWrapper // until headers were written. func (rw *responseWriter) Flush() { if !rw.wroteHeader { // flushing the underlying ResponseWriter will write header and status code, // but we need to delay that until we can determine if we must encode and // therefore add the Content-Encoding header; this happens in the first call // to rw.Write (see bug in #4314) return } //nolint:bodyclose http.NewResponseController(rw.ResponseWriter).Flush() } // Hijack implements http.Hijacker. It will flush status code if set. We don't track actual hijacked // status assuming http middlewares will track its status. func (rw *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { if !rw.wroteHeader { if rw.statusCode != 0 { rw.ResponseWriter.WriteHeader(rw.statusCode) } rw.wroteHeader = true } //nolint:bodyclose return http.NewResponseController(rw.ResponseWriter).Hijack() } // Write writes to the response. If the response qualifies, // it is encoded using the encoder, which is initialized // if not done so already. func (rw *responseWriter) Write(p []byte) (int, error) { // ignore zero data writes, probably head request if len(p) == 0 { return 0, nil } // sniff content-type and determine content-length if !rw.wroteHeader && rw.config.MinLength > 0 { var gtMinLength bool if len(p) > rw.config.MinLength { gtMinLength = true } else if cl, err := strconv.Atoi(rw.Header().Get("Content-Length")); err == nil && cl > rw.config.MinLength { gtMinLength = true } if gtMinLength { if rw.Header().Get("Content-Type") == "" { rw.Header().Set("Content-Type", http.DetectContentType(p)) } rw.init() } } // before we write to the response, we need to make // sure the header is written exactly once; we do // that by checking if a status code has been set, // and if so, that means we haven't written the // header OR the default status code will be written // by the standard library if !rw.wroteHeader { if rw.statusCode != 0 { rw.ResponseWriter.WriteHeader(rw.statusCode) } rw.wroteHeader = true } if rw.w != nil { return rw.w.Write(p) } else { return rw.ResponseWriter.Write(p) } } // Close writes any remaining buffered response and // deallocates any active resources. func (rw *responseWriter) Close() error { // didn't write, probably head request if !rw.wroteHeader { cl, err := strconv.Atoi(rw.Header().Get("Content-Length")) if err == nil && cl > rw.config.MinLength { rw.init() } // issue #5059, don't write status code if not set explicitly. if rw.statusCode != 0 { rw.ResponseWriter.WriteHeader(rw.statusCode) } rw.wroteHeader = true } var err error if rw.w != nil { err = rw.w.Close() rw.w.Reset(nil) rw.config.writerPools[rw.encodingName].Put(rw.w) rw.w = nil } return err } // Unwrap returns the underlying ResponseWriter. func (rw *responseWriter) Unwrap() http.ResponseWriter { return rw.ResponseWriter } // init should be called before we write a response, if rw.buf has contents. func (rw *responseWriter) init() { if rw.Header().Get("Content-Encoding") == "" && isEncodeAllowed(rw.Header()) && rw.config.Match(rw) { rw.w = rw.config.writerPools[rw.encodingName].Get().(Encoder) rw.w.Reset(rw.ResponseWriter) rw.Header().Del("Content-Length") // https://github.com/golang/go/issues/14975 rw.Header().Set("Content-Encoding", rw.encodingName) rw.Header().Add("Vary", "Accept-Encoding") rw.Header().Del("Accept-Ranges") // we don't know ranges for dynamically-encoded content } } // AcceptedEncodings returns the list of encodings that the // client supports, in descending order of preference. // The client preference via q-factor and the server // preference via Prefer setting are taken into account. If // the Sec-WebSocket-Key header is present then non-identity // encodings are not considered. See // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html. func AcceptedEncodings(r *http.Request, preferredOrder []string) []string { acceptEncHeader := r.Header.Get("Accept-Encoding") websocketKey := r.Header.Get("Sec-WebSocket-Key") if acceptEncHeader == "" { return []string{} } prefs := []encodingPreference{} for _, accepted := range strings.Split(acceptEncHeader, ",") { parts := strings.Split(accepted, ";") encName := strings.ToLower(strings.TrimSpace(parts[0])) // determine q-factor qFactor := 1.0 if len(parts) > 1 { qFactorStr := strings.ToLower(strings.TrimSpace(parts[1])) if strings.HasPrefix(qFactorStr, "q=") { if qFactorFloat, err := strconv.ParseFloat(qFactorStr[2:], 32); err == nil { if qFactorFloat >= 0 && qFactorFloat <= 1 { qFactor = qFactorFloat } } } } // encodings with q-factor of 0 are not accepted; // use a small threshold to account for float precision if qFactor < 0.00001 { continue } // don't encode WebSocket handshakes if websocketKey != "" && encName != "identity" { continue } // set server preference prefOrder := -1 for i, p := range preferredOrder { if encName == p { prefOrder = len(preferredOrder) - i break } } prefs = append(prefs, encodingPreference{ encoding: encName, q: qFactor, preferOrder: prefOrder, }) } // sort preferences by descending q-factor first, then by preferOrder sort.Slice(prefs, func(i, j int) bool { if math.Abs(prefs[i].q-prefs[j].q) < 0.00001 { return prefs[i].preferOrder > prefs[j].preferOrder } return prefs[i].q > prefs[j].q }) prefEncNames := make([]string, len(prefs)) for i := range prefs { prefEncNames[i] = prefs[i].encoding } return prefEncNames } // encodingPreference pairs an encoding with its q-factor. type encodingPreference struct { encoding string q float64 preferOrder int } // Encoder is a type which can encode a stream of data. type Encoder interface { io.WriteCloser Reset(io.Writer) } // Encoding is a type which can create encoders of its kind // and return the name used in the Accept-Encoding header. type Encoding interface { AcceptEncoding() string NewEncoder() Encoder } // Precompressed is a type which returns filename suffix of precompressed // file and Accept-Encoding header to use when serving this file. type Precompressed interface { AcceptEncoding() string Suffix() string } // defaultMinLength is the minimum length at which to compress content. const defaultMinLength = 512 // Interface guards var ( _ caddy.Provisioner = (*Encode)(nil) _ caddy.Validator = (*Encode)(nil) _ caddyhttp.MiddlewareHandler = (*Encode)(nil) )
Go
caddy/modules/caddyhttp/encode/encode_test.go
package encode import ( "net/http" "sync" "testing" ) func BenchmarkOpenResponseWriter(b *testing.B) { enc := new(Encode) for n := 0; n < b.N; n++ { enc.openResponseWriter("test", nil) } } func TestPreferOrder(t *testing.T) { testCases := []struct { name string accept string prefer []string expected []string }{ { name: "PreferOrder(): 4 accept, 3 prefer", accept: "deflate, gzip, br, zstd", prefer: []string{"zstd", "br", "gzip"}, expected: []string{"zstd", "br", "gzip", "deflate"}, }, { name: "PreferOrder(): 2 accept, 3 prefer", accept: "deflate, zstd", prefer: []string{"zstd", "br", "gzip"}, expected: []string{"zstd", "deflate"}, }, { name: "PreferOrder(): 2 accept (1 empty), 3 prefer", accept: "gzip,,zstd", prefer: []string{"zstd", "br", "gzip"}, expected: []string{"zstd", "gzip", ""}, }, { name: "PreferOrder(): 1 accept, 2 prefer", accept: "gzip", prefer: []string{"zstd", "gzip"}, expected: []string{"gzip"}, }, { name: "PreferOrder(): 4 accept (1 duplicate), 1 prefer", accept: "deflate, gzip, br, br", prefer: []string{"br"}, expected: []string{"br", "br", "deflate", "gzip"}, }, { name: "PreferOrder(): empty accept, 0 prefer", accept: "", prefer: []string{}, expected: []string{}, }, { name: "PreferOrder(): empty accept, 1 prefer", accept: "", prefer: []string{"gzip"}, expected: []string{}, }, { name: "PreferOrder(): with q-factor", accept: "deflate;q=0.8, gzip;q=0.4, br;q=0.2, zstd", prefer: []string{"gzip"}, expected: []string{"zstd", "deflate", "gzip", "br"}, }, { name: "PreferOrder(): with q-factor, no prefer", accept: "deflate;q=0.8, gzip;q=0.4, br;q=0.2, zstd", prefer: []string{}, expected: []string{"zstd", "deflate", "gzip", "br"}, }, { name: "PreferOrder(): q-factor=0 filtered out", accept: "deflate;q=0.1, gzip;q=0.4, br;q=0.5, zstd;q=0", prefer: []string{"gzip"}, expected: []string{"br", "gzip", "deflate"}, }, { name: "PreferOrder(): q-factor=0 filtered out, no prefer", accept: "deflate;q=0.1, gzip;q=0.4, br;q=0.5, zstd;q=0", prefer: []string{}, expected: []string{"br", "gzip", "deflate"}, }, { name: "PreferOrder(): with invalid q-factor", accept: "br, deflate, gzip;q=2, zstd;q=0.1", prefer: []string{"zstd", "gzip"}, expected: []string{"gzip", "br", "deflate", "zstd"}, }, { name: "PreferOrder(): with invalid q-factor, no prefer", accept: "br, deflate, gzip;q=2, zstd;q=0.1", prefer: []string{}, expected: []string{"br", "deflate", "gzip", "zstd"}, }, } enc := new(Encode) r, _ := http.NewRequest("", "", nil) for _, test := range testCases { t.Run(test.name, func(t *testing.T) { if test.accept == "" { r.Header.Del("Accept-Encoding") } else { r.Header.Set("Accept-Encoding", test.accept) } enc.Prefer = test.prefer result := AcceptedEncodings(r, enc.Prefer) if !sliceEqual(result, test.expected) { t.Errorf("AcceptedEncodings() actual: %s expected: %s", result, test.expected) } }) } } func sliceEqual(a, b []string) bool { if len(a) != len(b) { return false } for i := range a { if a[i] != b[i] { return false } } return true } func TestValidate(t *testing.T) { type testCase struct { name string prefer []string wantErr bool } var err error var testCases []testCase enc := new(Encode) enc.writerPools = map[string]*sync.Pool{ "zstd": nil, "gzip": nil, "br": nil, } testCases = []testCase{ { name: "ValidatePrefer (zstd, gzip & br enabled): valid order with all encoder", prefer: []string{"zstd", "br", "gzip"}, wantErr: false, }, { name: "ValidatePrefer (zstd, gzip & br enabled): valid order with 2 out of 3 encoders", prefer: []string{"br", "gzip"}, wantErr: false, }, { name: "ValidatePrefer (zstd, gzip & br enabled): valid order with 1 out of 3 encoders", prefer: []string{"gzip"}, wantErr: false, }, { name: "ValidatePrefer (zstd, gzip & br enabled): 1 duplicated (once) encoder", prefer: []string{"gzip", "zstd", "gzip"}, wantErr: true, }, { name: "ValidatePrefer (zstd, gzip & br enabled): 1 not enabled encoder in prefer list", prefer: []string{"br", "zstd", "gzip", "deflate"}, wantErr: true, }, { name: "ValidatePrefer (zstd, gzip & br enabled): no prefer list", prefer: []string{}, wantErr: false, }, } for _, test := range testCases { t.Run(test.name, func(t *testing.T) { enc.Prefer = test.prefer err = enc.Validate() if (err != nil) != test.wantErr { t.Errorf("Validate() error = %v, wantErr = %v", err, test.wantErr) } }) } enc.writerPools = map[string]*sync.Pool{ "zstd": nil, "gzip": nil, } testCases = []testCase{ { name: "ValidatePrefer (zstd & gzip enabled): 1 not enabled encoder in prefer list", prefer: []string{"zstd", "br", "gzip"}, wantErr: true, }, { name: "ValidatePrefer (zstd & gzip enabled): 2 not enabled encoder in prefer list", prefer: []string{"br", "zstd", "gzip", "deflate"}, wantErr: true, }, { name: "ValidatePrefer (zstd & gzip enabled): only not enabled encoder in prefer list", prefer: []string{"deflate", "br", "gzip"}, wantErr: true, }, { name: "ValidatePrefer (zstd & gzip enabled): 1 duplicated (once) encoder in prefer list", prefer: []string{"gzip", "zstd", "gzip"}, wantErr: true, }, { name: "ValidatePrefer (zstd & gzip enabled): 1 duplicated (twice) encoder in prefer list", prefer: []string{"gzip", "zstd", "gzip", "gzip"}, wantErr: true, }, { name: "ValidatePrefer (zstd & gzip enabled): 1 duplicated encoder in prefer list", prefer: []string{"zstd", "zstd", "gzip", "gzip"}, wantErr: true, }, { name: "ValidatePrefer (zstd & gzip enabled): 1 duplicated not enabled encoder in prefer list", prefer: []string{"br", "br", "gzip"}, wantErr: true, }, { name: "ValidatePrefer (zstd & gzip enabled): 2 duplicated not enabled encoder in prefer list", prefer: []string{"br", "deflate", "br", "deflate"}, wantErr: true, }, { name: "ValidatePrefer (zstd & gzip enabled): valid order zstd first", prefer: []string{"zstd", "gzip"}, wantErr: false, }, { name: "ValidatePrefer (zstd & gzip enabled): valid order gzip first", prefer: []string{"gzip", "zstd"}, wantErr: false, }, } for _, test := range testCases { t.Run(test.name, func(t *testing.T) { enc.Prefer = test.prefer err = enc.Validate() if (err != nil) != test.wantErr { t.Errorf("Validate() error = %v, wantErr = %v", err, test.wantErr) } }) } } func TestIsEncodeAllowed(t *testing.T) { testCases := []struct { name string headers http.Header expected bool }{ { name: "Without any headers", headers: http.Header{}, expected: true, }, { name: "Without Cache-Control HTTP header", headers: http.Header{ "Accept-Encoding": {"gzip"}, }, expected: true, }, { name: "Cache-Control HTTP header ending with no-transform directive", headers: http.Header{ "Accept-Encoding": {"gzip"}, "Cache-Control": {"no-cache; no-transform"}, }, expected: false, }, { name: "With Cache-Control HTTP header no-transform as Cache-Extension value", headers: http.Header{ "Accept-Encoding": {"gzip"}, "Cache-Control": {`no-store; no-cache; community="no-transform"`}, }, expected: false, }, } for _, test := range testCases { t.Run(test.name, func(t *testing.T) { if result := isEncodeAllowed(test.headers); result != test.expected { t.Errorf("The headers given to the isEncodeAllowed should return %t, %t given.", result, test.expected) } }) } }
Go
caddy/modules/caddyhttp/encode/brotli/brotli_precompressed.go
package caddybrotli import ( "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp/encode" ) func init() { caddy.RegisterModule(BrotliPrecompressed{}) } // BrotliPrecompressed provides the file extension for files precompressed with brotli encoding. type BrotliPrecompressed struct{} // CaddyModule returns the Caddy module information. func (BrotliPrecompressed) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.precompressed.br", New: func() caddy.Module { return new(BrotliPrecompressed) }, } } // AcceptEncoding returns the name of the encoding as // used in the Accept-Encoding request headers. func (BrotliPrecompressed) AcceptEncoding() string { return "br" } // Suffix returns the filename suffix of precompressed files. func (BrotliPrecompressed) Suffix() string { return ".br" } // Interface guards var _ encode.Precompressed = (*BrotliPrecompressed)(nil)
Go
caddy/modules/caddyhttp/encode/gzip/gzip.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 caddygzip import ( "fmt" "strconv" "github.com/klauspost/compress/gzip" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp/encode" ) func init() { caddy.RegisterModule(Gzip{}) } // Gzip can create gzip encoders. type Gzip struct { Level int `json:"level,omitempty"` } // CaddyModule returns the Caddy module information. func (Gzip) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.encoders.gzip", New: func() caddy.Module { return new(Gzip) }, } } // UnmarshalCaddyfile sets up the handler from Caddyfile tokens. func (g *Gzip) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { if !d.NextArg() { continue } levelStr := d.Val() level, err := strconv.Atoi(levelStr) if err != nil { return err } g.Level = level } return nil } // Provision provisions g's configuration. func (g *Gzip) Provision(ctx caddy.Context) error { if g.Level == 0 { g.Level = defaultGzipLevel } return nil } // Validate validates g's configuration. func (g Gzip) Validate() error { if g.Level < gzip.StatelessCompression { return fmt.Errorf("quality too low; must be >= %d", gzip.StatelessCompression) } if g.Level > gzip.BestCompression { return fmt.Errorf("quality too high; must be <= %d", gzip.BestCompression) } return nil } // AcceptEncoding returns the name of the encoding as // used in the Accept-Encoding request headers. func (Gzip) AcceptEncoding() string { return "gzip" } // NewEncoder returns a new gzip writer. func (g Gzip) NewEncoder() encode.Encoder { writer, _ := gzip.NewWriterLevel(nil, g.Level) return writer } // Informed from http://blog.klauspost.com/gzip-performance-for-go-webservers/ var defaultGzipLevel = 5 // Interface guards var ( _ encode.Encoding = (*Gzip)(nil) _ caddy.Provisioner = (*Gzip)(nil) _ caddy.Validator = (*Gzip)(nil) _ caddyfile.Unmarshaler = (*Gzip)(nil) )
Go
caddy/modules/caddyhttp/encode/gzip/gzip_precompressed.go
package caddygzip import ( "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp/encode" ) func init() { caddy.RegisterModule(GzipPrecompressed{}) } // GzipPrecompressed provides the file extension for files precompressed with gzip encoding. type GzipPrecompressed struct { Gzip } // CaddyModule returns the Caddy module information. func (GzipPrecompressed) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.precompressed.gzip", New: func() caddy.Module { return new(GzipPrecompressed) }, } } // Suffix returns the filename suffix of precompressed files. func (GzipPrecompressed) Suffix() string { return ".gz" } var _ encode.Precompressed = (*GzipPrecompressed)(nil)
Go
caddy/modules/caddyhttp/encode/zstd/zstd.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 caddyzstd import ( "github.com/klauspost/compress/zstd" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp/encode" ) func init() { caddy.RegisterModule(Zstd{}) } // Zstd can create Zstandard encoders. type Zstd struct{} // CaddyModule returns the Caddy module information. func (Zstd) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.encoders.zstd", New: func() caddy.Module { return new(Zstd) }, } } // UnmarshalCaddyfile sets up the handler from Caddyfile tokens. func (z *Zstd) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { return nil } // AcceptEncoding returns the name of the encoding as // used in the Accept-Encoding request headers. func (Zstd) AcceptEncoding() string { return "zstd" } // NewEncoder returns a new Zstandard writer. func (z Zstd) NewEncoder() encode.Encoder { // The default of 8MB for the window is // too large for many clients, so we limit // it to 128K to lighten their load. writer, _ := zstd.NewWriter(nil, zstd.WithWindowSize(128<<10), zstd.WithEncoderConcurrency(1), zstd.WithZeroFrames(true)) return writer } // Interface guards var ( _ encode.Encoding = (*Zstd)(nil) _ caddyfile.Unmarshaler = (*Zstd)(nil) )
Go
caddy/modules/caddyhttp/encode/zstd/zstd_precompressed.go
package caddyzstd import ( "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp/encode" ) func init() { caddy.RegisterModule(ZstdPrecompressed{}) } // ZstdPrecompressed provides the file extension for files precompressed with zstandard encoding. type ZstdPrecompressed struct { Zstd } // CaddyModule returns the Caddy module information. func (ZstdPrecompressed) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.precompressed.zstd", New: func() caddy.Module { return new(ZstdPrecompressed) }, } } // Suffix returns the filename suffix of precompressed files. func (ZstdPrecompressed) Suffix() string { return ".zst" } var _ encode.Precompressed = (*ZstdPrecompressed)(nil)
Go
caddy/modules/caddyhttp/fileserver/browse.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 fileserver import ( "bytes" "context" _ "embed" "encoding/json" "fmt" "io" "io/fs" "net/http" "os" "path" "strings" "sync" "text/template" "go.uber.org/zap" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" "github.com/caddyserver/caddy/v2/modules/caddyhttp/templates" ) //go:embed browse.html var defaultBrowseTemplate string // Browse configures directory browsing. type Browse struct { // Use this template file instead of the default browse template. TemplateFile string `json:"template_file,omitempty"` } func (fsrv *FileServer) serveBrowse(root, dirPath string, w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { fsrv.logger.Debug("browse enabled; listing directory contents", zap.String("path", dirPath), zap.String("root", root)) // Navigation on the client-side gets messed up if the // URL doesn't end in a trailing slash because hrefs to // "b/c" at path "/a" end up going to "/b/c" instead // of "/a/b/c" - so we have to redirect in this case // so that the path is "/a/" and the client constructs // relative hrefs "b/c" to be "/a/b/c". // // Only redirect if the last element of the path (the filename) was not // rewritten; if the admin wanted to rewrite to the canonical path, they // would have, and we have to be very careful not to introduce unwanted // redirects and especially redirect loops! (Redirecting using the // original URI is necessary because that's the URI the browser knows, // we don't want to redirect from internally-rewritten URIs.) // See https://github.com/caddyserver/caddy/issues/4205. // We also redirect if the path is empty, because this implies the path // prefix was fully stripped away by a `handle_path` handler for example. // See https://github.com/caddyserver/caddy/issues/4466. origReq := r.Context().Value(caddyhttp.OriginalRequestCtxKey).(http.Request) if r.URL.Path == "" || path.Base(origReq.URL.Path) == path.Base(r.URL.Path) { if !strings.HasSuffix(origReq.URL.Path, "/") { fsrv.logger.Debug("redirecting to trailing slash to preserve hrefs", zap.String("request_path", r.URL.Path)) return redirect(w, r, origReq.URL.Path+"/") } } dir, err := fsrv.openFile(dirPath, w) if err != nil { return err } defer dir.Close() repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) // TODO: not entirely sure if path.Clean() is necessary here but seems like a safe plan (i.e. /%2e%2e%2f) - someone could verify this listing, err := fsrv.loadDirectoryContents(r.Context(), dir.(fs.ReadDirFile), root, path.Clean(r.URL.EscapedPath()), repl) switch { case os.IsPermission(err): return caddyhttp.Error(http.StatusForbidden, err) case os.IsNotExist(err): return fsrv.notFound(w, r, next) case err != nil: return caddyhttp.Error(http.StatusInternalServerError, err) } fsrv.browseApplyQueryParams(w, r, listing) buf := bufPool.Get().(*bytes.Buffer) buf.Reset() defer bufPool.Put(buf) acceptHeader := strings.ToLower(strings.Join(r.Header["Accept"], ",")) // write response as either JSON or HTML if strings.Contains(acceptHeader, "application/json") { if err := json.NewEncoder(buf).Encode(listing.Items); err != nil { return caddyhttp.Error(http.StatusInternalServerError, err) } w.Header().Set("Content-Type", "application/json; charset=utf-8") } else { var fs http.FileSystem if fsrv.Root != "" { fs = http.Dir(repl.ReplaceAll(fsrv.Root, ".")) } tplCtx := &templateContext{ TemplateContext: templates.TemplateContext{ Root: fs, Req: r, RespHeader: templates.WrappedHeader{Header: w.Header()}, }, browseTemplateContext: listing, } tpl, err := fsrv.makeBrowseTemplate(tplCtx) if err != nil { return fmt.Errorf("parsing browse template: %v", err) } if err := tpl.Execute(buf, tplCtx); err != nil { return caddyhttp.Error(http.StatusInternalServerError, err) } w.Header().Set("Content-Type", "text/html; charset=utf-8") } _, _ = buf.WriteTo(w) return nil } func (fsrv *FileServer) loadDirectoryContents(ctx context.Context, dir fs.ReadDirFile, root, urlPath string, repl *caddy.Replacer) (*browseTemplateContext, error) { files, err := dir.ReadDir(10000) // TODO: this limit should probably be configurable if err != nil && err != io.EOF { return nil, err } // user can presumably browse "up" to parent folder if path is longer than "/" canGoUp := len(urlPath) > 1 return fsrv.directoryListing(ctx, files, canGoUp, root, urlPath, repl), nil } // browseApplyQueryParams applies query parameters to the listing. // It mutates the listing and may set cookies. func (fsrv *FileServer) browseApplyQueryParams(w http.ResponseWriter, r *http.Request, listing *browseTemplateContext) { layoutParam := r.URL.Query().Get("layout") sortParam := r.URL.Query().Get("sort") orderParam := r.URL.Query().Get("order") limitParam := r.URL.Query().Get("limit") offsetParam := r.URL.Query().Get("offset") switch layoutParam { case "list", "grid", "": listing.Layout = layoutParam default: listing.Layout = "list" } // figure out what to sort by switch sortParam { case "": sortParam = sortByNameDirFirst if sortCookie, sortErr := r.Cookie("sort"); sortErr == nil { sortParam = sortCookie.Value } case sortByName, sortByNameDirFirst, sortBySize, sortByTime: http.SetCookie(w, &http.Cookie{Name: "sort", Value: sortParam, Secure: r.TLS != nil}) } // then figure out the order switch orderParam { case "": orderParam = "asc" if orderCookie, orderErr := r.Cookie("order"); orderErr == nil { orderParam = orderCookie.Value } case "asc", "desc": http.SetCookie(w, &http.Cookie{Name: "order", Value: orderParam, Secure: r.TLS != nil}) } // finally, apply the sorting and limiting listing.applySortAndLimit(sortParam, orderParam, limitParam, offsetParam) } // makeBrowseTemplate creates the template to be used for directory listings. func (fsrv *FileServer) makeBrowseTemplate(tplCtx *templateContext) (*template.Template, error) { var tpl *template.Template var err error if fsrv.Browse.TemplateFile != "" { tpl = tplCtx.NewTemplate(path.Base(fsrv.Browse.TemplateFile)) tpl, err = tpl.ParseFiles(fsrv.Browse.TemplateFile) if err != nil { return nil, fmt.Errorf("parsing browse template file: %v", err) } } else { tpl = tplCtx.NewTemplate("default_listing") tpl, err = tpl.Parse(defaultBrowseTemplate) if err != nil { return nil, fmt.Errorf("parsing default browse template: %v", err) } } return tpl, nil } // isSymlinkTargetDir returns true if f's symbolic link target // is a directory. func (fsrv *FileServer) isSymlinkTargetDir(f fs.FileInfo, root, urlPath string) bool { if !isSymlink(f) { return false } target := caddyhttp.SanitizedPathJoin(root, path.Join(urlPath, f.Name())) targetInfo, err := fs.Stat(fsrv.fileSystem, target) if err != nil { return false } return targetInfo.IsDir() } // isSymlink return true if f is a symbolic link. func isSymlink(f fs.FileInfo) bool { return f.Mode()&os.ModeSymlink != 0 } // templateContext powers the context used when evaluating the browse template. // It combines browse-specific features with the standard templates handler // features. type templateContext struct { templates.TemplateContext *browseTemplateContext } // bufPool is used to increase the efficiency of file listings. var bufPool = sync.Pool{ New: func() any { return new(bytes.Buffer) }, }
HTML
caddy/modules/caddyhttp/fileserver/browse.html
{{- define "icon"}} {{- if .IsDir}} <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-folder-filled" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M9 3a1 1 0 0 1 .608 .206l.1 .087l2.706 2.707h6.586a3 3 0 0 1 2.995 2.824l.005 .176v8a3 3 0 0 1 -2.824 2.995l-.176 .005h-14a3 3 0 0 1 -2.995 -2.824l-.005 -.176v-11a3 3 0 0 1 2.824 -2.995l.176 -.005h4z" stroke-width="0" fill="currentColor"></path> </svg> {{- else if or (eq .Name "LICENSE") (eq .Name "README")}} <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-license" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M15 21h-9a3 3 0 0 1 -3 -3v-1h10v2a2 2 0 0 0 4 0v-14a2 2 0 1 1 2 2h-2m2 -4h-11a3 3 0 0 0 -3 3v11"></path> <path d="M9 7l4 0"></path> <path d="M9 11l4 0"></path> </svg> {{- else if .HasExt ".jpg" ".jpeg" ".png" ".gif" ".webp" ".tiff" ".bmp" ".heif" ".heic" ".svg"}} {{- if eq .Tpl.Layout "grid"}} <img loading="lazy" src="{{html .Name}}"> {{- else}} <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-photo" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M15 8h.01"></path> <path d="M3 6a3 3 0 0 1 3 -3h12a3 3 0 0 1 3 3v12a3 3 0 0 1 -3 3h-12a3 3 0 0 1 -3 -3v-12z"></path> <path d="M3 16l5 -5c.928 -.893 2.072 -.893 3 0l5 5"></path> <path d="M14 14l1 -1c.928 -.893 2.072 -.893 3 0l3 3"></path> </svg> {{- end}} {{- else if .HasExt ".mp4" ".mov" ".mpeg" ".mpg" ".avi" ".ogg" ".webm" ".mkv" ".vob" ".gifv" ".3gp"}} <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-movie" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M4 4m0 2a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v12a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2z"></path> <path d="M8 4l0 16"></path> <path d="M16 4l0 16"></path> <path d="M4 8l4 0"></path> <path d="M4 16l4 0"></path> <path d="M4 12l16 0"></path> <path d="M16 8l4 0"></path> <path d="M16 16l4 0"></path> </svg> {{- else if .HasExt ".mp3" ".m4a" ".aac" ".ogg" ".flac" ".wav" ".wma" ".midi" ".cda"}} <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-music" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M6 17m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0"></path> <path d="M16 17m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0"></path> <path d="M9 17l0 -13l10 0l0 13"></path> <path d="M9 8l10 0"></path> </svg> {{- else if .HasExt ".pdf"}} <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-file-type-pdf" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M14 3v4a1 1 0 0 0 1 1h4"></path> <path d="M5 12v-7a2 2 0 0 1 2 -2h7l5 5v4"></path> <path d="M5 18h1.5a1.5 1.5 0 0 0 0 -3h-1.5v6"></path> <path d="M17 18h2"></path> <path d="M20 15h-3v6"></path> <path d="M11 15v6h1a2 2 0 0 0 2 -2v-2a2 2 0 0 0 -2 -2h-1z"></path> </svg> {{- else if .HasExt ".csv" ".tsv"}} <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-file-type-csv" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M14 3v4a1 1 0 0 0 1 1h4"></path> <path d="M5 12v-7a2 2 0 0 1 2 -2h7l5 5v4"></path> <path d="M7 16.5a1.5 1.5 0 0 0 -3 0v3a1.5 1.5 0 0 0 3 0"></path> <path d="M10 20.25c0 .414 .336 .75 .75 .75h1.25a1 1 0 0 0 1 -1v-1a1 1 0 0 0 -1 -1h-1a1 1 0 0 1 -1 -1v-1a1 1 0 0 1 1 -1h1.25a.75 .75 0 0 1 .75 .75"></path> <path d="M16 15l2 6l2 -6"></path> </svg> {{- else if .HasExt ".txt" ".doc" ".docx" ".odt" ".fodt" ".rtf"}} <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-file-text" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M14 3v4a1 1 0 0 0 1 1h4"></path> <path d="M17 21h-10a2 2 0 0 1 -2 -2v-14a2 2 0 0 1 2 -2h7l5 5v11a2 2 0 0 1 -2 2z"></path> <path d="M9 9l1 0"></path> <path d="M9 13l6 0"></path> <path d="M9 17l6 0"></path> </svg> {{- else if .HasExt ".xls" ".xlsx" ".ods" ".fods"}} <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-file-spreadsheet" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M14 3v4a1 1 0 0 0 1 1h4"></path> <path d="M17 21h-10a2 2 0 0 1 -2 -2v-14a2 2 0 0 1 2 -2h7l5 5v11a2 2 0 0 1 -2 2z"></path> <path d="M8 11h8v7h-8z"></path> <path d="M8 15h8"></path> <path d="M11 11v7"></path> </svg> {{- else if .HasExt ".ppt" ".pptx" ".odp" ".fodp"}} <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-presentation-analytics" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M9 12v-4"></path> <path d="M15 12v-2"></path> <path d="M12 12v-1"></path> <path d="M3 4h18"></path> <path d="M4 4v10a2 2 0 0 0 2 2h12a2 2 0 0 0 2 -2v-10"></path> <path d="M12 16v4"></path> <path d="M9 20h6"></path> </svg> {{- else if .HasExt ".zip" ".gz" ".xz" ".tar" ".7z" ".rar" ".xz" ".zst"}} <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-file-zip" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M6 20.735a2 2 0 0 1 -1 -1.735v-14a2 2 0 0 1 2 -2h7l5 5v11a2 2 0 0 1 -2 2h-1"></path> <path d="M11 17a2 2 0 0 1 2 2v2a1 1 0 0 1 -1 1h-2a1 1 0 0 1 -1 -1v-2a2 2 0 0 1 2 -2z"></path> <path d="M11 5l-1 0"></path> <path d="M13 7l-1 0"></path> <path d="M11 9l-1 0"></path> <path d="M13 11l-1 0"></path> <path d="M11 13l-1 0"></path> <path d="M13 15l-1 0"></path> </svg> {{- else if .HasExt ".deb" ".dpkg"}} <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-brand-debian" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M12 17c-2.397 -.943 -4 -3.153 -4 -5.635c0 -2.19 1.039 -3.14 1.604 -3.595c2.646 -2.133 6.396 -.27 6.396 3.23c0 2.5 -2.905 2.121 -3.5 1.5c-.595 -.621 -1 -1.5 -.5 -2.5"></path> <path d="M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0"></path> </svg> {{- else if .HasExt ".rpm" ".exe" ".flatpak" ".appimage" ".jar" ".msi" ".apk"}} <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-package" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M12 3l8 4.5l0 9l-8 4.5l-8 -4.5l0 -9l8 -4.5"></path> <path d="M12 12l8 -4.5"></path> <path d="M12 12l0 9"></path> <path d="M12 12l-8 -4.5"></path> <path d="M16 5.25l-8 4.5"></path> </svg> {{- else if .HasExt ".ps1"}} <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-brand-powershell" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M4.887 20h11.868c.893 0 1.664 -.665 1.847 -1.592l2.358 -12c.212 -1.081 -.442 -2.14 -1.462 -2.366a1.784 1.784 0 0 0 -.385 -.042h-11.868c-.893 0 -1.664 .665 -1.847 1.592l-2.358 12c-.212 1.081 .442 2.14 1.462 2.366c.127 .028 .256 .042 .385 .042z"></path> <path d="M9 8l4 4l-6 4"></path> <path d="M12 16h3"></path> </svg> {{- else if .HasExt ".py" ".pyc" ".pyo"}} <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-brand-python" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M12 9h-7a2 2 0 0 0 -2 2v4a2 2 0 0 0 2 2h3"></path> <path d="M12 15h7a2 2 0 0 0 2 -2v-4a2 2 0 0 0 -2 -2h-3"></path> <path d="M8 9v-4a2 2 0 0 1 2 -2h4a2 2 0 0 1 2 2v5a2 2 0 0 1 -2 2h-4a2 2 0 0 0 -2 2v5a2 2 0 0 0 2 2h4a2 2 0 0 0 2 -2v-4"></path> <path d="M11 6l0 .01"></path> <path d="M13 18l0 .01"></path> </svg> {{- else if .HasExt ".bash" ".sh" ".com" ".bat" ".dll" ".so"}} <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-script" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M17 20h-11a3 3 0 0 1 0 -6h11a3 3 0 0 0 0 6h1a3 3 0 0 0 3 -3v-11a2 2 0 0 0 -2 -2h-10a2 2 0 0 0 -2 2v8"></path> </svg> {{- else if .HasExt ".dmg"}} <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-brand-finder" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M3 4m0 1a1 1 0 0 1 1 -1h16a1 1 0 0 1 1 1v14a1 1 0 0 1 -1 1h-16a1 1 0 0 1 -1 -1z"></path> <path d="M7 8v1"></path> <path d="M17 8v1"></path> <path d="M12.5 4c-.654 1.486 -1.26 3.443 -1.5 9h2.5c-.19 2.867 .094 5.024 .5 7"></path> <path d="M7 15.5c3.667 2 6.333 2 10 0"></path> </svg> {{- else if .HasExt ".iso" ".img"}} <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-disc" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0"></path> <path d="M12 12m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"></path> <path d="M7 12a5 5 0 0 1 5 -5"></path> <path d="M12 17a5 5 0 0 0 5 -5"></path> </svg> {{- else if .HasExt ".md" ".mdown" ".markdown"}} <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-markdown" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M3 5m0 2a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v10a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2z"></path> <path d="M7 15v-6l2 2l2 -2v6"></path> <path d="M14 13l2 2l2 -2m-2 2v-6"></path> </svg> {{- else if .HasExt ".ttf" ".otf" ".woff" ".woff2" ".eof"}} <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-file-typography" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M14 3v4a1 1 0 0 0 1 1h4"></path> <path d="M17 21h-10a2 2 0 0 1 -2 -2v-14a2 2 0 0 1 2 -2h7l5 5v11a2 2 0 0 1 -2 2z"></path> <path d="M11 18h2"></path> <path d="M12 18v-7"></path> <path d="M9 12v-1h6v1"></path> </svg> {{- else if .HasExt ".go"}} <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-brand-golang" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M15.695 14.305c1.061 1.06 2.953 .888 4.226 -.384c1.272 -1.273 1.444 -3.165 .384 -4.226c-1.061 -1.06 -2.953 -.888 -4.226 .384c-1.272 1.273 -1.444 3.165 -.384 4.226z"></path> <path d="M12.68 9.233c-1.084 -.497 -2.545 -.191 -3.591 .846c-1.284 1.273 -1.457 3.165 -.388 4.226c1.07 1.06 2.978 .888 4.261 -.384a3.669 3.669 0 0 0 1.038 -1.921h-2.427"></path> <path d="M5.5 15h-1.5"></path> <path d="M6 9h-2"></path> <path d="M5 12h-3"></path> </svg> {{- else if .HasExt ".html" ".htm"}} <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-file-type-html" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M14 3v4a1 1 0 0 0 1 1h4"></path> <path d="M5 12v-7a2 2 0 0 1 2 -2h7l5 5v4"></path> <path d="M2 21v-6"></path> <path d="M5 15v6"></path> <path d="M2 18h3"></path> <path d="M20 15v6h2"></path> <path d="M13 21v-6l2 3l2 -3v6"></path> <path d="M7.5 15h3"></path> <path d="M9 15v6"></path> </svg> {{- else if .HasExt ".js"}} <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-file-type-js" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M14 3v4a1 1 0 0 0 1 1h4"></path> <path d="M3 15h3v4.5a1.5 1.5 0 0 1 -3 0"></path> <path d="M9 20.25c0 .414 .336 .75 .75 .75h1.25a1 1 0 0 0 1 -1v-1a1 1 0 0 0 -1 -1h-1a1 1 0 0 1 -1 -1v-1a1 1 0 0 1 1 -1h1.25a.75 .75 0 0 1 .75 .75"></path> <path d="M5 12v-7a2 2 0 0 1 2 -2h7l5 5v11a2 2 0 0 1 -2 2h-1"></path> </svg> {{- else if .HasExt ".css"}} <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-file-type-css" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M14 3v4a1 1 0 0 0 1 1h4"></path> <path d="M5 12v-7a2 2 0 0 1 2 -2h7l5 5v4"></path> <path d="M8 16.5a1.5 1.5 0 0 0 -3 0v3a1.5 1.5 0 0 0 3 0"></path> <path d="M11 20.25c0 .414 .336 .75 .75 .75h1.25a1 1 0 0 0 1 -1v-1a1 1 0 0 0 -1 -1h-1a1 1 0 0 1 -1 -1v-1a1 1 0 0 1 1 -1h1.25a.75 .75 0 0 1 .75 .75"></path> <path d="M17 20.25c0 .414 .336 .75 .75 .75h1.25a1 1 0 0 0 1 -1v-1a1 1 0 0 0 -1 -1h-1a1 1 0 0 1 -1 -1v-1a1 1 0 0 1 1 -1h1.25a.75 .75 0 0 1 .75 .75"></path> </svg> {{- else if .HasExt ".json" ".json5" ".jsonc"}} <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-json" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M20 16v-8l3 8v-8"></path> <path d="M15 8a2 2 0 0 1 2 2v4a2 2 0 1 1 -4 0v-4a2 2 0 0 1 2 -2z"></path> <path d="M1 8h3v6.5a1.5 1.5 0 0 1 -3 0v-.5"></path> <path d="M7 15a1 1 0 0 0 1 1h1a1 1 0 0 0 1 -1v-2a1 1 0 0 0 -1 -1h-1a1 1 0 0 1 -1 -1v-2a1 1 0 0 1 1 -1h1a1 1 0 0 1 1 1"></path> </svg> {{- else if .HasExt ".ts"}} <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-file-type-ts" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M14 3v4a1 1 0 0 0 1 1h4"></path> <path d="M5 12v-7a2 2 0 0 1 2 -2h7l5 5v11a2 2 0 0 1 -2 2h-1"></path> <path d="M14 3v4a1 1 0 0 0 1 1h4"></path> <path d="M9 20.25c0 .414 .336 .75 .75 .75h1.25a1 1 0 0 0 1 -1v-1a1 1 0 0 0 -1 -1h-1a1 1 0 0 1 -1 -1v-1a1 1 0 0 1 1 -1h1.25a.75 .75 0 0 1 .75 .75"></path> <path d="M3.5 15h3"></path> <path d="M5 15v6"></path> </svg> {{- else if .HasExt ".sql"}} <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-file-type-sql" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M14 3v4a1 1 0 0 0 1 1h4"></path> <path d="M14 3v4a1 1 0 0 0 1 1h4"></path> <path d="M5 20.25c0 .414 .336 .75 .75 .75h1.25a1 1 0 0 0 1 -1v-1a1 1 0 0 0 -1 -1h-1a1 1 0 0 1 -1 -1v-1a1 1 0 0 1 1 -1h1.25a.75 .75 0 0 1 .75 .75"></path> <path d="M5 12v-7a2 2 0 0 1 2 -2h7l5 5v4"></path> <path d="M18 15v6h2"></path> <path d="M13 15a2 2 0 0 1 2 2v2a2 2 0 1 1 -4 0v-2a2 2 0 0 1 2 -2z"></path> <path d="M14 20l1.5 1.5"></path> </svg> {{- else if .HasExt ".db" ".sqlite" ".bak" ".mdb"}} <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-database" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M12 6m-8 0a8 3 0 1 0 16 0a8 3 0 1 0 -16 0"></path> <path d="M4 6v6a8 3 0 0 0 16 0v-6"></path> <path d="M4 12v6a8 3 0 0 0 16 0v-6"></path> </svg> {{- else if .HasExt ".eml" ".email" ".mailbox" ".mbox" ".msg"}} <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-mail" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M3 7a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v10a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2v-10z"></path> <path d="M3 7l9 6l9 -6"></path> </svg> {{- else if .HasExt ".crt" ".pem" ".x509" ".cer" ".ca-bundle"}} <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-certificate" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M15 15m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0"></path> <path d="M13 17.5v4.5l2 -1.5l2 1.5v-4.5"></path> <path d="M10 19h-5a2 2 0 0 1 -2 -2v-10c0 -1.1 .9 -2 2 -2h14a2 2 0 0 1 2 2v10a2 2 0 0 1 -1 1.73"></path> <path d="M6 9l12 0"></path> <path d="M6 12l3 0"></path> <path d="M6 15l2 0"></path> </svg> {{- else if .HasExt ".key" ".keystore" ".jks" ".p12" ".pfx" ".pub"}} <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-key" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M16.555 3.843l3.602 3.602a2.877 2.877 0 0 1 0 4.069l-2.643 2.643a2.877 2.877 0 0 1 -4.069 0l-.301 -.301l-6.558 6.558a2 2 0 0 1 -1.239 .578l-.175 .008h-1.172a1 1 0 0 1 -.993 -.883l-.007 -.117v-1.172a2 2 0 0 1 .467 -1.284l.119 -.13l.414 -.414h2v-2h2v-2l2.144 -2.144l-.301 -.301a2.877 2.877 0 0 1 0 -4.069l2.643 -2.643a2.877 2.877 0 0 1 4.069 0z"></path> <path d="M15 9h.01"></path> </svg> {{- else}} {{- if .IsSymlink}} <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-file-symlink" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M4 21v-4a3 3 0 0 1 3 -3h5"></path> <path d="M9 17l3 -3l-3 -3"></path> <path d="M14 3v4a1 1 0 0 0 1 1h4"></path> <path d="M5 11v-6a2 2 0 0 1 2 -2h7l5 5v11a2 2 0 0 1 -2 2h-9.5"></path> </svg> {{- else}} <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-file" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M14 3v4a1 1 0 0 0 1 1h4"></path> <path d="M17 21h-10a2 2 0 0 1 -2 -2v-14a2 2 0 0 1 2 -2h7l5 5v11a2 2 0 0 1 -2 2z"></path> </svg> {{- end}} {{- end}} {{- end}} <!DOCTYPE html> <html> <head> <title>{{html .Name}}</title> <meta charset="utf-8"> <meta name="color-scheme" content="light dark"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> * { padding: 0; margin: 0; box-sizing: border-box; } body { font-family: Inter, system-ui, sans-serif; font-size: 16px; text-rendering: optimizespeed; background-color: #f3f6f7; min-height: 100vh; } img, svg { vertical-align: middle; z-index: 1; } img { max-width: 100%; max-height: 100%; border-radius: 5px; } td img { max-width: 1.5em; max-height: 2em; object-fit: cover; } body, a, svg, .layout.current, .layout.current svg, .go-up { color: #333; text-decoration: none; } .wrapper { max-width: 1200px; margin-left: auto; margin-right: auto; } header, .meta { padding-left: 5%; padding-right: 5%; } td a { color: #006ed3; text-decoration: none; } td a:hover { color: #0095e4; } td a:visited { color: #800080; } td a:visited:hover { color: #b900b9; } th:first-child, td:first-child { width: 5%; } th:last-child, td:last-child { width: 5%; } .size, .timestamp { font-size: 14px; } .grid .size { font-size: 12px; margin-top: .5em; color: #496a84; } header { padding-top: 15px; padding-bottom: 15px; box-shadow: 0px 0px 20px 0px rgb(0 0 0 / 10%); } .breadcrumbs { text-transform: uppercase; font-size: 10px; letter-spacing: 1px; color: #939393; margin-bottom: 5px; padding-left: 3px; } h1 { font-size: 20px; font-family: Poppins, system-ui, sans-serif; font-weight: normal; white-space: nowrap; overflow-x: hidden; text-overflow: ellipsis; color: #c5c5c5; } h1 a, th a { color: #000; } h1 a { padding: 0 3px; margin: 0 1px; } h1 a:hover { background: #ffffc4; } h1 a:first-child { margin: 0; } header, main { background-color: white; } main { margin: 3em auto 0; border-radius: 5px; box-shadow: 0 2px 5px 1px rgb(0 0 0 / 5%); } .meta { display: flex; gap: 1em; font-size: 14px; border-bottom: 1px solid #e5e9ea; padding-top: 1em; padding-bottom: 1em; } #summary { display: flex; gap: 1em; align-items: center; margin-right: auto; } .filter-container { position: relative; display: inline-block; margin-left: 1em; } #search-icon { color: #777; position: absolute; height: 1em; top: .6em; left: .5em; } #filter { padding: .5em 1em .5em 2.5em; border: none; border: 1px solid #CCC; border-radius: 5px; font-family: inherit; position: relative; z-index: 2; background: none; } .layout, .layout svg { color: #9a9a9a; } table { width: 100%; border-collapse: collapse; } tbody tr, tbody tr a, .entry a { transition: all .15s; } tbody tr:hover, .grid .entry a:hover { background-color: #f4f9fd; } th, td { text-align: left; } th { position: sticky; top: 0; background: white; white-space: nowrap; z-index: 2; text-transform: uppercase; font-size: 14px; letter-spacing: 1px; padding: .75em 0; } td { white-space: nowrap; } td:nth-child(2) { width: 75%; } td:nth-child(2) a { padding: 1em 0; display: block; } td:nth-child(3), th:nth-child(3) { padding: 0 20px 0 20px; min-width: 150px; } td .go-up { text-transform: uppercase; font-size: 12px; font-weight: bold; } .name, .go-up { word-break: break-all; overflow-wrap: break-word; white-space: pre-wrap; } .listing .icon-tabler { color: #454545; } .listing .icon-tabler-folder-filled { color: #ffb900 !important; } .sizebar { position: relative; padding: 0.25rem 0.5rem; display: flex; } .sizebar-bar { background-color: #dbeeff; position: absolute; top: 0; right: 0; bottom: 0; left: 0; z-index: 0; height: 100%; pointer-events: none; } .sizebar-text { position: relative; z-index: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(16em, 1fr)); gap: 2px; } .grid .entry { position: relative; width: 100%; } .grid .entry a { display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 1.5em; height: 100%; } .grid .entry svg { width: 75px; height: 75px; } .grid .entry img { max-height: 200px; object-fit: cover; } .grid .entry .name { margin-top: 1em; } footer { padding: 40px 20px; font-size: 12px; text-align: center; } .caddy-logo { display: inline-block; height: 2.5em; margin: 0 auto; } @media (max-width: 600px) { .hideable { display: none; } td:nth-child(2) { width: auto; } th:nth-child(3), td:nth-child(3) { padding-right: 5%; text-align: right; } h1 { color: #000; } h1 a { margin: 0; } #filter { max-width: 100px; } .grid .entry { max-width: initial; } } @media (prefers-color-scheme: dark) { html { background: black; /* overscroll */ } body { background: linear-gradient(180deg, rgb(34 50 66) 0%, rgb(26 31 38) 100%); background-attachment: fixed; } body, a, svg, .layout.current, .layout.current svg, .go-up { color: #ccc; } h1 a, th a { color: white; } h1 { color: white; } h1 a:hover { background: hsl(213deg 100% 73% / 20%); } header, main, .grid .entry { background-color: #101720; } tbody tr:hover, .grid .entry a:hover { background-color: #162030; color: #fff; } th { background-color: #18212c; } td a, .listing .icon-tabler { color: #abc8e3; } td a:hover, td a:hover .icon-tabler { color: white; } td a:visited { color: #cd53cd; } td a:visited:hover { color: #f676f6; } #search-icon { color: #7798c4; } #filter { color: #ffffff; border: 1px solid #29435c; } .meta { border-bottom: 1px solid #222e3b; } .sizebar-bar { background-color: #1f3549; } .grid .entry a { background-color: #080b0f; } #Wordmark path, #R path { fill: #ccc !important; } #R circle { stroke: #ccc !important; } } </style> {{- if eq .Layout "grid"}} <style>.wrapper { max-width: none; } main { margin-top: 1px; }</style> {{- end}} </head> <body onload="initPage()"> <header> <div class="wrapper"> <div class="breadcrumbs">Folder Path</div> <h1> {{range $i, $crumb := .Breadcrumbs}}<a href="{{html $crumb.Link}}">{{html $crumb.Text}}</a>{{if ne $i 0}}/{{end}}{{end}} </h1> </div> </header> <div class="wrapper"> <main> <div class="meta"> <div id="summary"> <span class="meta-item"> <b>{{.NumDirs}}</b> director{{if eq 1 .NumDirs}}y{{else}}ies{{end}} </span> <span class="meta-item"> <b>{{.NumFiles}}</b> file{{if ne 1 .NumFiles}}s{{end}} </span> {{- if ne 0 .Limit}} <span class="meta-item"> (of which only <b>{{.Limit}}</b> are displayed) </span> {{- end}} </div> <a href="javascript:queryParam('layout', '')" id="layout-list" class='layout{{if eq $.Layout "list" ""}}current{{end}}'> <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-layout-list" width="16" height="16" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M4 4m0 2a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v2a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2z"></path> <path d="M4 14m0 2a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v2a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2z"></path> </svg> List </a> <a href="javascript:queryParam('layout', 'grid')" id="layout-grid" class='layout{{if eq $.Layout "grid"}}current{{end}}'> <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-layout-grid" width="16" height="16" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M4 4m0 1a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1z"></path> <path d="M14 4m0 1a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1z"></path> <path d="M4 14m0 1a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1z"></path> <path d="M14 14m0 1a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1z"></path> </svg> Grid </a> </div> <div class='listing{{if eq .Layout "grid"}} grid{{end}}'> {{- if eq .Layout "grid"}} {{- range .Items}} <div class="entry"> <a href="{{html .URL}}" title='{{html (.HumanModTime "January 2, 2006 at 15:04:05")}}'> {{template "icon" .}} <div class="name">{{html .Name}}</div> <div class="size">{{.HumanSize}}</div> </a> </div> {{- end}} {{- else}} <table aria-describedby="summary"> <thead> <tr> <th></th> <th> {{- if and (eq .Sort "namedirfirst") (ne .Order "desc")}} <a href="?sort=namedirfirst&order=desc{{if ne 0 .Limit}}&limit={{.Limit}}{{end}}{{if ne 0 .Offset}}&offset={{.Offset}}{{end}}" class="icon"> <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-caret-up" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M18 14l-6 -6l-6 6h12"></path> </svg> </a> {{- else if and (eq .Sort "namedirfirst") (ne .Order "asc")}} <a href="?sort=namedirfirst&order=asc{{if ne 0 .Limit}}&limit={{.Limit}}{{end}}{{if ne 0 .Offset}}&offset={{.Offset}}{{end}}" class="icon"> <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-caret-down" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M6 10l6 6l6 -6h-12"></path> </svg> </a> {{- else}} <a href="?sort=namedirfirst&order=asc{{if ne 0 .Limit}}&limit={{.Limit}}{{end}}{{if ne 0 .Offset}}&offset={{.Offset}}{{end}}" class="icon sort"> <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-caret-up" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M18 14l-6 -6l-6 6h12"></path> </svg> </a> {{- end}} {{- if and (eq .Sort "name") (ne .Order "desc")}} <a href="?sort=name&order=desc{{if ne 0 .Limit}}&limit={{.Limit}}{{end}}{{if ne 0 .Offset}}&offset={{.Offset}}{{end}}"> Name <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-caret-up" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M18 14l-6 -6l-6 6h12"></path> </svg> </a> {{- else if and (eq .Sort "name") (ne .Order "asc")}} <a href="?sort=name&order=asc{{if ne 0 .Limit}}&limit={{.Limit}}{{end}}{{if ne 0 .Offset}}&offset={{.Offset}}{{end}}"> Name <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-caret-down" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M6 10l6 6l6 -6h-12"></path> </svg> </a> {{- else}} <a href="?sort=name&order=asc{{if ne 0 .Limit}}&limit={{.Limit}}{{end}}{{if ne 0 .Offset}}&offset={{.Offset}}{{end}}"> Name </a> {{- end}} <div class="filter-container"> <svg id="search-icon" xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-search" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M10 10m-7 0a7 7 0 1 0 14 0a7 7 0 1 0 -14 0"></path> <path d="M21 21l-6 -6"></path> </svg> <input type="text" placeholder="Search" id="filter" onkeyup='filter()'> </div> </th> <th> {{- if and (eq .Sort "size") (ne .Order "desc")}} <a href="?sort=size&order=desc{{if ne 0 .Limit}}&limit={{.Limit}}{{end}}{{if ne 0 .Offset}}&offset={{.Offset}}{{end}}"> Size <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-caret-up" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M18 14l-6 -6l-6 6h12"></path> </svg> </a> {{- else if and (eq .Sort "size") (ne .Order "asc")}} <a href="?sort=size&order=asc{{if ne 0 .Limit}}&limit={{.Limit}}{{end}}{{if ne 0 .Offset}}&offset={{.Offset}}{{end}}"> Size <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-caret-down" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M6 10l6 6l6 -6h-12"></path> </svg> </a> {{- else}} <a href="?sort=size&order=asc{{if ne 0 .Limit}}&limit={{.Limit}}{{end}}{{if ne 0 .Offset}}&offset={{.Offset}}{{end}}"> Size </a> {{- end}} </th> <th class="hideable"> {{- if and (eq .Sort "time") (ne .Order "desc")}} <a href="?sort=time&order=desc{{if ne 0 .Limit}}&limit={{.Limit}}{{end}}{{if ne 0 .Offset}}&offset={{.Offset}}{{end}}"> Modified <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-caret-up" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M18 14l-6 -6l-6 6h12"></path> </svg> </a> {{- else if and (eq .Sort "time") (ne .Order "asc")}} <a href="?sort=time&order=asc{{if ne 0 .Limit}}&limit={{.Limit}}{{end}}{{if ne 0 .Offset}}&offset={{.Offset}}{{end}}"> Modified <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-caret-down" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M6 10l6 6l6 -6h-12"></path> </svg> </a> {{- else}} <a href="?sort=time&order=asc{{if ne 0 .Limit}}&limit={{.Limit}}{{end}}{{if ne 0 .Offset}}&offset={{.Offset}}{{end}}"> Modified </a> {{- end}} </th> <th class="hideable"></th> </tr> </thead> <tbody> {{- if .CanGoUp}} <tr> <td></td> <td> <a href=".."> <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-corner-left-up" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M18 18h-6a3 3 0 0 1 -3 -3v-10l-4 4m8 0l-4 -4"></path> </svg> <span class="go-up">Up</span> </a> </td> <td></td> <td class="hideable"></td> <td class="hideable"></td> </tr> {{- end}} {{- range .Items}} <tr class="file"> <td></td> <td> <a href="{{html .URL}}"> {{template "icon" .}} <span class="name">{{html .Name}}</span> </a> </td> {{- if .IsDir}} <td>&mdash;</td> {{- else}} <td class="size" data-size="{{.Size}}"> <div class="sizebar"> <div class="sizebar-bar"></div> <div class="sizebar-text"> {{.HumanSize}} </div> </div> </td> {{- end}} <td class="timestamp hideable"> <time datetime="{{.HumanModTime "2006-01-02T15:04:05Z"}}">{{.HumanModTime "01/02/2006 03:04:05 PM -07:00"}}</time> </td> <td class="hideable"></td> </tr> {{- end}} </tbody> </table> {{- end}} </div> </main> </div> <footer> Served with <a rel="noopener noreferrer" href="https://caddyserver.com"> <svg class="caddy-logo" viewBox="0 0 379 114" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linecap:round;stroke-linejoin:round;"> <g transform="matrix(1,0,0,1,-1982.99,-530.985)"> <g transform="matrix(1.16548,0,0,1.10195,1823.12,393.466)"> <g transform="matrix(1,0,0,1,0.233052,1.17986)"> <g id="Icon" transform="matrix(0.858013,0,0,0.907485,-3224.99,-1435.83)"> <g> <g transform="matrix(-0.191794,-0.715786,0.715786,-0.191794,4329.14,4673.64)"> <path d="M3901.56,610.734C3893.53,610.261 3886.06,608.1 3879.2,604.877C3872.24,601.608 3866.04,597.093 3860.8,591.633C3858.71,589.457 3856.76,587.149 3854.97,584.709C3853.2,582.281 3851.57,579.733 3850.13,577.066C3845.89,569.224 3843.21,560.381 3842.89,550.868C3842.57,543.321 3843.64,536.055 3845.94,529.307C3848.37,522.203 3852.08,515.696 3856.83,510.049L3855.79,509.095C3850.39,514.54 3846.02,520.981 3842.9,528.125C3839.84,535.125 3838.03,542.781 3837.68,550.868C3837.34,561.391 3839.51,571.425 3843.79,580.306C3845.27,583.38 3847.03,586.304 3849.01,589.049C3851.01,591.806 3853.24,594.39 3855.69,596.742C3861.75,602.568 3869,607.19 3877.03,610.1C3884.66,612.867 3892.96,614.059 3901.56,613.552L3901.56,610.734Z" style="fill:rgb(0,144,221);"/> </g> <g transform="matrix(-0.191794,-0.715786,0.715786,-0.191794,4329.14,4673.64)"> <path d="M3875.69,496.573C3879.62,494.538 3883.8,492.897 3888.2,491.786C3892.49,490.704 3896.96,490.124 3901.56,490.032C3903.82,490.13 3906.03,490.332 3908.21,490.688C3917.13,492.147 3925.19,495.814 3932.31,500.683C3936.13,503.294 3939.59,506.335 3942.81,509.619C3947.09,513.98 3950.89,518.816 3953.85,524.232C3958.2,532.197 3960.96,541.186 3961.32,550.868C3961.61,558.748 3960.46,566.345 3957.88,573.322C3956.09,578.169 3953.7,582.753 3950.66,586.838C3947.22,591.461 3942.96,595.427 3938.27,598.769C3933.66,602.055 3928.53,604.619 3923.09,606.478C3922.37,606.721 3921.6,606.805 3920.93,607.167C3920.42,607.448 3920.14,607.854 3919.69,608.224L3920.37,610.389C3920.98,610.432 3921.47,610.573 3922.07,610.474C3922.86,610.344 3923.55,609.883 3924.28,609.566C3931.99,606.216 3938.82,601.355 3944.57,595.428C3947.02,592.903 3949.25,590.174 3951.31,587.319C3953.59,584.168 3955.66,580.853 3957.43,577.348C3961.47,569.34 3964.01,560.422 3964.36,550.868C3964.74,540.511 3962.66,530.628 3958.48,521.868C3955.57,515.775 3951.72,510.163 3946.95,505.478C3943.37,501.962 3939.26,498.99 3934.84,496.562C3926.88,492.192 3917.87,489.76 3908.37,489.229C3906.12,489.104 3903.86,489.054 3901.56,489.154C3896.87,489.06 3892.3,489.519 3887.89,490.397C3883.3,491.309 3878.89,492.683 3874.71,494.525L3875.69,496.573Z" style="fill:rgb(0,144,221);"/> </g> </g> <g> <g transform="matrix(-3.37109,-0.514565,0.514565,-3.37109,4078.07,1806.88)"> <path d="M22,12C22,10.903 21.097,10 20,10C19.421,10 18.897,10.251 18.53,10.649C18.202,11.006 18,11.481 18,12C18,13.097 18.903,14 20,14C21.097,14 22,13.097 22,12Z" style="fill:none;fill-rule:nonzero;stroke:rgb(0,144,221);stroke-width:1.05px;"/> </g> <g transform="matrix(-5.33921,-5.26159,-3.12106,-6.96393,4073.87,1861.55)"> <path d="M10.315,5.333C10.315,5.333 9.748,5.921 9.03,6.673C7.768,7.995 6.054,9.805 6.054,9.805L6.237,9.86C6.237,9.86 8.045,8.077 9.36,6.771C10.107,6.028 10.689,5.444 10.689,5.444L10.315,5.333Z" style="fill:rgb(0,144,221);"/> </g> </g> <g id="Padlock" transform="matrix(3.11426,0,0,3.11426,3938.31,1737.25)"> <g> <path d="M9.876,21L18.162,21C18.625,21 19,20.625 19,20.162L19,11.838C19,11.375 18.625,11 18.162,11L5.838,11C5.375,11 5,11.375 5,11.838L5,16.758" style="fill:none;stroke:rgb(34,182,56);stroke-width:1.89px;stroke-linecap:butt;stroke-linejoin:miter;"/> <path d="M8,11L8,7C8,4.806 9.806,3 12,3C14.194,3 16,4.806 16,7L16,11" style="fill:none;fill-rule:nonzero;stroke:rgb(34,182,56);stroke-width:1.89px;"/> </g> </g> <g> <g transform="matrix(5.30977,0.697415,-0.697415,5.30977,3852.72,1727.97)"> <path d="M22,12C22,11.659 21.913,11.337 21.76,11.055C21.421,10.429 20.756,10 20,10C18.903,10 18,10.903 18,12C18,13.097 18.903,14 20,14C21.097,14 22,13.097 22,12Z" style="fill:none;fill-rule:nonzero;stroke:rgb(0,144,221);stroke-width:0.98px;"/> </g> <g transform="matrix(4.93114,2.49604,1.11018,5.44847,3921.41,1726.72)"> <path d="M8.902,6.77C8.902,6.77 7.235,8.253 6.027,9.366C5.343,9.996 4.819,10.502 4.819,10.502L5.52,11.164C5.52,11.164 6.021,10.637 6.646,9.951C7.749,8.739 9.219,7.068 9.219,7.068L8.902,6.77Z" style="fill:rgb(0,144,221);"/> </g> </g> </g> <g id="Text"> <g id="Wordmark" transform="matrix(1.32271,0,0,2.60848,-899.259,-791.691)"> <g id="y" transform="matrix(0.50291,0,0,0.281607,905.533,304.987)"> <path d="M192.152,286.875L202.629,268.64C187.804,270.106 183.397,265.779 180.143,263.391C176.888,261.004 174.362,257.99 172.563,254.347C170.765,250.705 169.866,246.691 169.866,242.305L169.866,208.107L183.21,208.107L183.21,242.213C183.21,245.188 183.896,247.822 185.268,250.116C186.64,252.41 188.465,254.197 190.743,255.475C193.022,256.754 195.501,257.393 198.182,257.393C200.894,257.393 203.393,256.75 205.68,255.463C207.966,254.177 209.799,252.391 211.178,250.105C212.558,247.818 213.248,245.188 213.248,242.213L213.248,208.107L226.545,208.107L226.545,242.305C226.545,246.707 225.378,258.46 218.079,268.64C215.735,271.909 207.835,286.875 207.835,286.875L192.152,286.875Z" style="fill:rgb(47,47,47);fill-rule:nonzero;"/> </g> <g id="add" transform="matrix(0.525075,0,0,0.281607,801.871,304.987)"> <g transform="matrix(116.242,0,0,116.242,161.846,267.39)"> <path d="M0.276,0.012C0.227,0.012 0.186,0 0.15,-0.024C0.115,-0.048 0.088,-0.08 0.069,-0.12C0.05,-0.161 0.04,-0.205 0.04,-0.254C0.04,-0.305 0.051,-0.35 0.072,-0.39C0.094,-0.431 0.125,-0.463 0.165,-0.487C0.205,-0.51 0.254,-0.522 0.31,-0.522C0.366,-0.522 0.413,-0.51 0.452,-0.486C0.491,-0.463 0.521,-0.431 0.542,-0.39C0.562,-0.35 0.573,-0.305 0.573,-0.256L0.573,-0L0.458,-0L0.458,-0.095L0.456,-0.095C0.446,-0.076 0.433,-0.058 0.417,-0.042C0.401,-0.026 0.381,-0.013 0.358,-0.003C0.335,0.007 0.307,0.012 0.276,0.012ZM0.307,-0.086C0.337,-0.086 0.363,-0.093 0.386,-0.108C0.408,-0.123 0.426,-0.144 0.438,-0.17C0.45,-0.195 0.456,-0.224 0.456,-0.256C0.456,-0.288 0.45,-0.317 0.438,-0.342C0.426,-0.367 0.409,-0.387 0.387,-0.402C0.365,-0.417 0.338,-0.424 0.308,-0.424C0.276,-0.424 0.249,-0.417 0.226,-0.402C0.204,-0.387 0.186,-0.366 0.174,-0.341C0.162,-0.315 0.156,-0.287 0.156,-0.255C0.156,-0.224 0.162,-0.195 0.174,-0.169C0.186,-0.144 0.203,-0.123 0.226,-0.108C0.248,-0.093 0.275,-0.086 0.307,-0.086Z" style="fill:rgb(47,47,47);fill-rule:nonzero;"/> </g> <g transform="matrix(116.242,0,0,116.242,226.592,267.39)"> <path d="M0.306,0.012C0.265,0.012 0.229,0.006 0.196,-0.008C0.163,-0.021 0.135,-0.039 0.112,-0.064C0.089,-0.088 0.071,-0.117 0.059,-0.151C0.046,-0.185 0.04,-0.222 0.04,-0.263C0.04,-0.315 0.051,-0.36 0.072,-0.399C0.093,-0.437 0.122,-0.468 0.159,-0.489C0.196,-0.511 0.239,-0.522 0.287,-0.522C0.311,-0.522 0.333,-0.518 0.355,-0.511C0.377,-0.504 0.396,-0.493 0.413,-0.48C0.431,-0.466 0.445,-0.451 0.455,-0.433L0.456,-0.433L0.456,-0.73L0.571,-0.73L0.571,-0.261C0.571,-0.205 0.56,-0.156 0.537,-0.115C0.515,-0.074 0.484,-0.043 0.444,-0.021C0.405,0.001 0.358,0.012 0.306,0.012ZM0.306,-0.086C0.335,-0.086 0.361,-0.093 0.384,-0.107C0.406,-0.122 0.423,-0.141 0.436,-0.167C0.448,-0.192 0.455,-0.221 0.455,-0.255C0.455,-0.288 0.448,-0.317 0.436,-0.343C0.423,-0.368 0.406,-0.388 0.383,-0.402C0.361,-0.417 0.335,-0.424 0.305,-0.424C0.276,-0.424 0.251,-0.417 0.228,-0.402C0.206,-0.387 0.188,-0.368 0.175,-0.342C0.163,-0.317 0.156,-0.288 0.156,-0.255C0.156,-0.222 0.163,-0.193 0.175,-0.167C0.188,-0.142 0.206,-0.122 0.229,-0.108C0.251,-0.093 0.277,-0.086 0.306,-0.086Z" style="fill:rgb(47,47,47);fill-rule:nonzero;"/> </g> <g transform="matrix(116.242,0,0,116.242,290.293,267.39)"> <path d="M0.306,0.012C0.265,0.012 0.229,0.006 0.196,-0.008C0.163,-0.021 0.135,-0.039 0.112,-0.064C0.089,-0.088 0.071,-0.117 0.059,-0.151C0.046,-0.185 0.04,-0.222 0.04,-0.263C0.04,-0.315 0.051,-0.36 0.072,-0.399C0.093,-0.437 0.122,-0.468 0.159,-0.489C0.196,-0.511 0.239,-0.522 0.287,-0.522C0.311,-0.522 0.333,-0.518 0.355,-0.511C0.377,-0.504 0.396,-0.493 0.413,-0.48C0.431,-0.466 0.445,-0.451 0.455,-0.433L0.456,-0.433L0.456,-0.73L0.571,-0.73L0.571,-0.261C0.571,-0.205 0.56,-0.156 0.537,-0.115C0.515,-0.074 0.484,-0.043 0.444,-0.021C0.405,0.001 0.358,0.012 0.306,0.012ZM0.306,-0.086C0.335,-0.086 0.361,-0.093 0.384,-0.107C0.406,-0.122 0.423,-0.141 0.436,-0.167C0.448,-0.192 0.455,-0.221 0.455,-0.255C0.455,-0.288 0.448,-0.317 0.436,-0.343C0.423,-0.368 0.406,-0.388 0.383,-0.402C0.361,-0.417 0.335,-0.424 0.305,-0.424C0.276,-0.424 0.251,-0.417 0.228,-0.402C0.206,-0.387 0.188,-0.368 0.175,-0.342C0.163,-0.317 0.156,-0.288 0.156,-0.255C0.156,-0.222 0.163,-0.193 0.175,-0.167C0.188,-0.142 0.206,-0.122 0.229,-0.108C0.251,-0.093 0.277,-0.086 0.306,-0.086Z" style="fill:rgb(47,47,47);fill-rule:nonzero;"/> </g> </g> <g id="c" transform="matrix(-0.0716462,0.31304,-0.583685,-0.0384251,1489.76,-444.051)"> <path d="M2668.11,700.4C2666.79,703.699 2666.12,707.216 2666.12,710.766C2666.12,726.268 2678.71,738.854 2694.21,738.854C2709.71,738.854 2722.3,726.268 2722.3,710.766C2722.3,704.111 2719.93,697.672 2715.63,692.597L2707.63,699.378C2710.33,702.559 2711.57,706.602 2711.81,710.766C2712.2,717.38 2706.61,724.52 2697.27,726.637C2683.9,728.581 2676.61,720.482 2676.61,710.766C2676.61,708.541 2677.03,706.336 2677.85,704.269L2668.11,700.4Z" style="fill:rgb(46,46,46);"/> </g> </g> <g id="R" transform="matrix(0.426446,0,0,0.451034,-1192.44,-722.167)"> <g transform="matrix(1,0,0,1,-0.10786,0.450801)"> <g transform="matrix(12.1247,0,0,12.1247,3862.61,1929.9)"> <path d="M0.073,-0L0.073,-0.7L0.383,-0.7C0.428,-0.7 0.469,-0.69 0.506,-0.67C0.543,-0.651 0.572,-0.623 0.594,-0.588C0.616,-0.553 0.627,-0.512 0.627,-0.465C0.627,-0.418 0.615,-0.377 0.592,-0.342C0.569,-0.306 0.539,-0.279 0.501,-0.259L0.57,-0.128C0.574,-0.12 0.579,-0.115 0.584,-0.111C0.59,-0.107 0.596,-0.106 0.605,-0.106L0.664,-0.106L0.664,-0L0.587,-0C0.56,-0 0.535,-0.007 0.514,-0.02C0.493,-0.034 0.476,-0.052 0.463,-0.075L0.381,-0.232C0.375,-0.231 0.368,-0.231 0.361,-0.231C0.354,-0.231 0.347,-0.231 0.34,-0.231L0.192,-0.231L0.192,-0L0.073,-0ZM0.192,-0.336L0.368,-0.336C0.394,-0.336 0.417,-0.341 0.438,-0.351C0.459,-0.361 0.476,-0.376 0.489,-0.396C0.501,-0.415 0.507,-0.438 0.507,-0.465C0.507,-0.492 0.501,-0.516 0.488,-0.535C0.475,-0.554 0.459,-0.569 0.438,-0.579C0.417,-0.59 0.394,-0.595 0.369,-0.595L0.192,-0.595L0.192,-0.336Z" style="fill:rgb(46,46,46);fill-rule:nonzero;"/> </g> </g> <g transform="matrix(1,0,0,1,0.278569,0.101881)"> <circle cx="3866.43" cy="1926.14" r="8.923" style="fill:none;stroke:rgb(46,46,46);stroke-width:2px;stroke-linecap:butt;stroke-linejoin:miter;"/> </g> </g> </g> </g> </g> </g> </svg> </a> </footer> <script> const filterEl = document.getElementById('filter'); filterEl?.focus({ preventScroll: true }); function initPage() { // populate and evaluate filter if (!filterEl?.value) { const filterParam = new URL(window.location.href).searchParams.get('filter'); if (filterParam) { filterEl.value = filterParam; } } filter(); // fill in size bars let largest = 0; document.querySelectorAll('.size').forEach(el => { largest = Math.max(largest, Number(el.dataset.size)); }); document.querySelectorAll('.size').forEach(el => { const size = Number(el.dataset.size); el.querySelector('.sizebar-bar').style.width = `${size/largest * 100}%`; }); } function filter() { if (!filterEl) return; const q = filterEl.value.trim().toLowerCase(); document.querySelectorAll('tr.file').forEach(function(el) { if (!q) { el.style.display = ''; return; } const nameEl = el.querySelector('.name'); const nameVal = nameEl.textContent.trim().toLowerCase(); if (nameVal.indexOf(q) !== -1) { el.style.display = ''; } else { el.style.display = 'none'; } }); } function queryParam(k, v) { const qs = new URLSearchParams(window.location.search); if (!v) { qs.delete(k); } else { qs.set(k, v); } const qsStr = qs.toString(); if (qsStr) { window.location.search = qsStr; } else { window.location = window.location.pathname; } } function localizeDatetime(e, index, ar) { if (e.textContent === undefined) { return; } var d = new Date(e.getAttribute('datetime')); if (isNaN(d)) { d = new Date(e.textContent); if (isNaN(d)) { return; } } e.textContent = d.toLocaleString(); } var timeList = Array.prototype.slice.call(document.getElementsByTagName("time")); timeList.forEach(localizeDatetime); </script> </body> </html>
Go
caddy/modules/caddyhttp/fileserver/browsetplcontext.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 fileserver import ( "context" "io/fs" "net/url" "os" "path" "sort" "strconv" "strings" "time" "github.com/dustin/go-humanize" "go.uber.org/zap" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func (fsrv *FileServer) directoryListing(ctx context.Context, entries []fs.DirEntry, canGoUp bool, root, urlPath string, repl *caddy.Replacer) *browseTemplateContext { filesToHide := fsrv.transformHidePaths(repl) name, _ := url.PathUnescape(urlPath) tplCtx := &browseTemplateContext{ Name: path.Base(name), Path: urlPath, CanGoUp: canGoUp, } for _, entry := range entries { if err := ctx.Err(); err != nil { break } name := entry.Name() if fileHidden(name, filesToHide) { continue } info, err := entry.Info() if err != nil { fsrv.logger.Error("could not get info about directory entry", zap.String("name", entry.Name()), zap.String("root", root)) continue } isDir := entry.IsDir() || fsrv.isSymlinkTargetDir(info, root, urlPath) // add the slash after the escape of path to avoid escaping the slash as well if isDir { name += "/" tplCtx.NumDirs++ } else { tplCtx.NumFiles++ } size := info.Size() fileIsSymlink := isSymlink(info) if fileIsSymlink { path := caddyhttp.SanitizedPathJoin(root, path.Join(urlPath, info.Name())) fileInfo, err := fs.Stat(fsrv.fileSystem, path) if err == nil { size = fileInfo.Size() } // An error most likely means the symlink target doesn't exist, // which isn't entirely unusual and shouldn't fail the listing. // In this case, just use the size of the symlink itself, which // was already set above. } u := url.URL{Path: "./" + name} // prepend with "./" to fix paths with ':' in the name tplCtx.Items = append(tplCtx.Items, fileInfo{ IsDir: isDir, IsSymlink: fileIsSymlink, Name: name, Size: size, URL: u.String(), ModTime: info.ModTime().UTC(), Mode: info.Mode(), Tpl: tplCtx, // a reference up to the template context is useful }) } return tplCtx } // browseTemplateContext provides the template context for directory listings. type browseTemplateContext struct { // The name of the directory (the last element of the path). Name string `json:"name"` // The full path of the request. Path string `json:"path"` // Whether the parent directory is browseable. CanGoUp bool `json:"can_go_up"` // The items (files and folders) in the path. Items []fileInfo `json:"items,omitempty"` // If โ‰ 0 then Items starting from that many elements. Offset int `json:"offset,omitempty"` // If โ‰ 0 then Items have been limited to that many elements. Limit int `json:"limit,omitempty"` // The number of directories in the listing. NumDirs int `json:"num_dirs"` // The number of files (items that aren't directories) in the listing. NumFiles int `json:"num_files"` // Sort column used Sort string `json:"sort,omitempty"` // Sorting order Order string `json:"order,omitempty"` // Display format (list or grid) Layout string `json:"layout,omitempty"` } // Breadcrumbs returns l.Path where every element maps // the link to the text to display. func (l browseTemplateContext) Breadcrumbs() []crumb { if len(l.Path) == 0 { return []crumb{} } // skip trailing slash lpath := l.Path if lpath[len(lpath)-1] == '/' { lpath = lpath[:len(lpath)-1] } parts := strings.Split(lpath, "/") result := make([]crumb, len(parts)) for i, p := range parts { if i == 0 && p == "" { p = "/" } // the directory name could include an encoded slash in its path, // so the item name should be unescaped in the loop rather than unescaping the // entire path outside the loop. p, _ = url.PathUnescape(p) lnk := strings.Repeat("../", len(parts)-i-1) result[i] = crumb{Link: lnk, Text: p} } return result } func (l *browseTemplateContext) applySortAndLimit(sortParam, orderParam, limitParam string, offsetParam string) { l.Sort = sortParam l.Order = orderParam if l.Order == "desc" { switch l.Sort { case sortByName: sort.Sort(sort.Reverse(byName(*l))) case sortByNameDirFirst: sort.Sort(sort.Reverse(byNameDirFirst(*l))) case sortBySize: sort.Sort(sort.Reverse(bySize(*l))) case sortByTime: sort.Sort(sort.Reverse(byTime(*l))) } } else { switch l.Sort { case sortByName: sort.Sort(byName(*l)) case sortByNameDirFirst: sort.Sort(byNameDirFirst(*l)) case sortBySize: sort.Sort(bySize(*l)) case sortByTime: sort.Sort(byTime(*l)) } } if offsetParam != "" { offset, _ := strconv.Atoi(offsetParam) if offset > 0 && offset <= len(l.Items) { l.Items = l.Items[offset:] l.Offset = offset } } if limitParam != "" { limit, _ := strconv.Atoi(limitParam) if limit > 0 && limit <= len(l.Items) { l.Items = l.Items[:limit] l.Limit = limit } } } // crumb represents part of a breadcrumb menu, // pairing a link with the text to display. type crumb struct { Link, Text string } // fileInfo contains serializable information // about a file or directory. type fileInfo struct { Name string `json:"name"` Size int64 `json:"size"` URL string `json:"url"` ModTime time.Time `json:"mod_time"` Mode os.FileMode `json:"mode"` IsDir bool `json:"is_dir"` IsSymlink bool `json:"is_symlink"` // a pointer to the template context is useful inside nested templates Tpl *browseTemplateContext `json:"-"` } // HasExt returns true if the filename has any of the given suffixes, case-insensitive. func (fi fileInfo) HasExt(exts ...string) bool { for _, ext := range exts { if strings.HasSuffix(strings.ToLower(fi.Name), strings.ToLower(ext)) { return true } } return false } // HumanSize returns the size of the file as a // human-readable string in IEC format (i.e. // power of 2 or base 1024). func (fi fileInfo) HumanSize() string { return humanize.IBytes(uint64(fi.Size)) } // HumanModTime returns the modified time of the file // as a human-readable string given by format. func (fi fileInfo) HumanModTime(format string) string { return fi.ModTime.Format(format) } type ( byName browseTemplateContext byNameDirFirst browseTemplateContext bySize browseTemplateContext byTime browseTemplateContext ) func (l byName) Len() int { return len(l.Items) } func (l byName) Swap(i, j int) { l.Items[i], l.Items[j] = l.Items[j], l.Items[i] } func (l byName) Less(i, j int) bool { return strings.ToLower(l.Items[i].Name) < strings.ToLower(l.Items[j].Name) } func (l byNameDirFirst) Len() int { return len(l.Items) } func (l byNameDirFirst) Swap(i, j int) { l.Items[i], l.Items[j] = l.Items[j], l.Items[i] } func (l byNameDirFirst) Less(i, j int) bool { // sort by name if both are dir or file if l.Items[i].IsDir == l.Items[j].IsDir { return strings.ToLower(l.Items[i].Name) < strings.ToLower(l.Items[j].Name) } // sort dir ahead of file return l.Items[i].IsDir } func (l bySize) Len() int { return len(l.Items) } func (l bySize) Swap(i, j int) { l.Items[i], l.Items[j] = l.Items[j], l.Items[i] } func (l bySize) Less(i, j int) bool { const directoryOffset = -1 << 31 // = -math.MinInt32 iSize, jSize := l.Items[i].Size, l.Items[j].Size // directory sizes depend on the file system; to // provide a consistent experience, put them up front // and sort them by name if l.Items[i].IsDir { iSize = directoryOffset } if l.Items[j].IsDir { jSize = directoryOffset } if l.Items[i].IsDir && l.Items[j].IsDir { return strings.ToLower(l.Items[i].Name) < strings.ToLower(l.Items[j].Name) } return iSize < jSize } func (l byTime) Len() int { return len(l.Items) } func (l byTime) Swap(i, j int) { l.Items[i], l.Items[j] = l.Items[j], l.Items[i] } func (l byTime) Less(i, j int) bool { return l.Items[i].ModTime.Before(l.Items[j].ModTime) } const ( sortByName = "name" sortByNameDirFirst = "namedirfirst" sortBySize = "size" sortByTime = "time" )
Go
caddy/modules/caddyhttp/fileserver/browsetplcontext_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 fileserver import ( "testing" ) func TestBreadcrumbs(t *testing.T) { testdata := []struct { path string expected []crumb }{ {"", []crumb{}}, {"/", []crumb{{Text: "/"}}}, {"/foo/", []crumb{ {Link: "../", Text: "/"}, {Link: "", Text: "foo"}, }}, {"/foo/bar/", []crumb{ {Link: "../../", Text: "/"}, {Link: "../", Text: "foo"}, {Link: "", Text: "bar"}, }}, {"/foo bar/", []crumb{ {Link: "../", Text: "/"}, {Link: "", Text: "foo bar"}, }}, {"/foo bar/baz/", []crumb{ {Link: "../../", Text: "/"}, {Link: "../", Text: "foo bar"}, {Link: "", Text: "baz"}, }}, {"/100%25 test coverage/is a lie/", []crumb{ {Link: "../../", Text: "/"}, {Link: "../", Text: "100% test coverage"}, {Link: "", Text: "is a lie"}, }}, {"/AC%2FDC/", []crumb{ {Link: "../", Text: "/"}, {Link: "", Text: "AC/DC"}, }}, {"/foo/%2e%2e%2f/bar", []crumb{ {Link: "../../../", Text: "/"}, {Link: "../../", Text: "foo"}, {Link: "../", Text: "../"}, {Link: "", Text: "bar"}, }}, {"/foo/../bar", []crumb{ {Link: "../../../", Text: "/"}, {Link: "../../", Text: "foo"}, {Link: "../", Text: ".."}, {Link: "", Text: "bar"}, }}, {"foo/bar/baz", []crumb{ {Link: "../../", Text: "foo"}, {Link: "../", Text: "bar"}, {Link: "", Text: "baz"}, }}, {"/qux/quux/corge/", []crumb{ {Link: "../../../", Text: "/"}, {Link: "../../", Text: "qux"}, {Link: "../", Text: "quux"}, {Link: "", Text: "corge"}, }}, {"/ู…ุฌู„ุฏ/", []crumb{ {Link: "../", Text: "/"}, {Link: "", Text: "ู…ุฌู„ุฏ"}, }}, {"/ู…ุฌู„ุฏ-1/ู…ุฌู„ุฏ-2", []crumb{ {Link: "../../", Text: "/"}, {Link: "../", Text: "ู…ุฌู„ุฏ-1"}, {Link: "", Text: "ู…ุฌู„ุฏ-2"}, }}, {"/ู…ุฌู„ุฏ%2F1", []crumb{ {Link: "../", Text: "/"}, {Link: "", Text: "ู…ุฌู„ุฏ/1"}, }}, } for testNum, d := range testdata { l := browseTemplateContext{Path: d.path} actual := l.Breadcrumbs() if len(actual) != len(d.expected) { t.Errorf("Test %d: Got %d components but expected %d; got: %+v", testNum, len(actual), len(d.expected), actual) continue } for i, c := range actual { if c != d.expected[i] { t.Errorf("Test %d crumb %d: got %#v but expected %#v at index %d", testNum, i, c, d.expected[i], i) } } } }
Go
caddy/modules/caddyhttp/fileserver/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 fileserver import ( "io/fs" "path/filepath" "strings" "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/modules/caddyhttp" "github.com/caddyserver/caddy/v2/modules/caddyhttp/encode" "github.com/caddyserver/caddy/v2/modules/caddyhttp/rewrite" ) func init() { httpcaddyfile.RegisterHandlerDirective("file_server", parseCaddyfile) httpcaddyfile.RegisterDirective("try_files", parseTryFiles) } // parseCaddyfile parses the file_server directive. It enables the static file // server and configures it with this syntax: // // file_server [<matcher>] [browse] { // fs <backend...> // root <path> // hide <files...> // index <files...> // browse [<template_file>] // precompressed <formats...> // status <status> // disable_canonical_uris // } func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) { var fsrv FileServer for h.Next() { args := h.RemainingArgs() switch len(args) { case 0: case 1: if args[0] != "browse" { return nil, h.ArgErr() } fsrv.Browse = new(Browse) default: return nil, h.ArgErr() } for h.NextBlock(0) { switch h.Val() { case "fs": if !h.NextArg() { return nil, h.ArgErr() } if fsrv.FileSystemRaw != nil { return nil, h.Err("file system module already specified") } name := h.Val() modID := "caddy.fs." + name unm, err := caddyfile.UnmarshalModule(h.Dispenser, modID) if err != nil { return nil, err } fsys, ok := unm.(fs.FS) if !ok { return nil, h.Errf("module %s (%T) is not a supported file system implementation (requires fs.FS)", modID, unm) } fsrv.FileSystemRaw = caddyconfig.JSONModuleObject(fsys, "backend", name, nil) case "hide": fsrv.Hide = h.RemainingArgs() if len(fsrv.Hide) == 0 { return nil, h.ArgErr() } case "index": fsrv.IndexNames = h.RemainingArgs() if len(fsrv.IndexNames) == 0 { return nil, h.ArgErr() } case "root": if !h.Args(&fsrv.Root) { return nil, h.ArgErr() } case "browse": if fsrv.Browse != nil { return nil, h.Err("browsing is already configured") } fsrv.Browse = new(Browse) h.Args(&fsrv.Browse.TemplateFile) case "precompressed": var order []string for h.NextArg() { modID := "http.precompressed." + h.Val() mod, err := caddy.GetModule(modID) if err != nil { return nil, h.Errf("getting module named '%s': %v", modID, err) } inst := mod.New() precompress, ok := inst.(encode.Precompressed) if !ok { return nil, h.Errf("module %s is not a precompressor; is %T", modID, inst) } if fsrv.PrecompressedRaw == nil { fsrv.PrecompressedRaw = make(caddy.ModuleMap) } fsrv.PrecompressedRaw[h.Val()] = caddyconfig.JSON(precompress, nil) order = append(order, h.Val()) } fsrv.PrecompressedOrder = order case "status": if !h.NextArg() { return nil, h.ArgErr() } fsrv.StatusCode = caddyhttp.WeakString(h.Val()) case "disable_canonical_uris": if h.NextArg() { return nil, h.ArgErr() } falseBool := false fsrv.CanonicalURIs = &falseBool case "pass_thru": if h.NextArg() { return nil, h.ArgErr() } fsrv.PassThru = true default: return nil, h.Errf("unknown subdirective '%s'", h.Val()) } } } // hide the Caddyfile (and any imported Caddyfiles) if configFiles := h.Caddyfiles(); len(configFiles) > 0 { for _, file := range configFiles { file = filepath.Clean(file) if !fileHidden(file, fsrv.Hide) { // if there's no path separator, the file server module will hide all // files by that name, rather than a specific one; but we want to hide // only this specific file, so ensure there's always a path separator if !strings.Contains(file, separator) { file = "." + separator + file } fsrv.Hide = append(fsrv.Hide, file) } } } return &fsrv, nil } // parseTryFiles parses the try_files directive. It combines a file matcher // with a rewrite directive, so this is not a standard handler directive. // A try_files directive has this syntax (notice no matcher tokens accepted): // // try_files <files...> { // policy first_exist|smallest_size|largest_size|most_recently_modified // } // // and is basically shorthand for: // // @try_files file { // try_files <files...> // policy first_exist|smallest_size|largest_size|most_recently_modified // } // rewrite @try_files {http.matchers.file.relative} // // This directive rewrites request paths only, preserving any other part // of the URI, unless the part is explicitly given in the file list. For // example, if any of the files in the list have a query string: // // try_files {path} index.php?{query}&p={path} // // then the query string will not be treated as part of the file name; and // if that file matches, the given query string will replace any query string // that already exists on the request URI. func parseTryFiles(h httpcaddyfile.Helper) ([]httpcaddyfile.ConfigValue, error) { if !h.Next() { return nil, h.ArgErr() } tryFiles := h.RemainingArgs() if len(tryFiles) == 0 { return nil, h.ArgErr() } // parse out the optional try policy var tryPolicy string for nesting := h.Nesting(); h.NextBlock(nesting); { switch h.Val() { case "policy": if tryPolicy != "" { return nil, h.Err("try policy already configured") } if !h.NextArg() { return nil, h.ArgErr() } tryPolicy = h.Val() switch tryPolicy { case tryPolicyFirstExist, tryPolicyLargestSize, tryPolicySmallestSize, tryPolicyMostRecentlyMod: default: return nil, h.Errf("unrecognized try policy: %s", tryPolicy) } } } // makeRoute returns a route that tries the files listed in try // and then rewrites to the matched file; userQueryString is // appended to the rewrite rule. makeRoute := func(try []string, userQueryString string) []httpcaddyfile.ConfigValue { handler := rewrite.Rewrite{ URI: "{http.matchers.file.relative}" + userQueryString, } matcherSet := caddy.ModuleMap{ "file": h.JSON(MatchFile{TryFiles: try, TryPolicy: tryPolicy}), } return h.NewRoute(matcherSet, handler) } var result []httpcaddyfile.ConfigValue // if there are query strings in the list, we have to split into // a separate route for each item with a query string, because // the rewrite is different for that item try := make([]string, 0, len(tryFiles)) for _, item := range tryFiles { if idx := strings.Index(item, "?"); idx >= 0 { if len(try) > 0 { result = append(result, makeRoute(try, "")...) try = []string{} } result = append(result, makeRoute([]string{item[:idx]}, item[idx:])...) continue } // accumulate consecutive non-query-string parameters try = append(try, item) } if len(try) > 0 { result = append(result, makeRoute(try, "")...) } // ensure that multiple routes (possible if rewrite targets // have query strings, for example) are grouped together // so only the first matching rewrite is performed (#2891) h.GroupRoutes(result) return result, nil }
Go
caddy/modules/caddyhttp/fileserver/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 fileserver import ( "encoding/json" "io" "log" "os" "strconv" "time" "github.com/caddyserver/certmagic" "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/modules/caddyhttp" caddytpl "github.com/caddyserver/caddy/v2/modules/caddyhttp/templates" ) func init() { caddycmd.RegisterCommand(caddycmd.Command{ Name: "file-server", Usage: "[--domain <example.com>] [--root <path>] [--listen <addr>] [--browse] [--access-log]", Short: "Spins up a production-ready file server", Long: ` A simple but production-ready file server. Useful for quick deployments, demos, and development. The listener's socket address can be customized with the --listen flag. If a domain name is specified with --domain, the default listener address will be changed to the HTTPS port and the server will use HTTPS. If using a public domain, ensure A/AAAA records are properly configured before using this option. If --browse is enabled, requests for folders without an index file will respond with a file listing.`, CobraFunc: func(cmd *cobra.Command) { cmd.Flags().StringP("domain", "d", "", "Domain name at which to serve the files") cmd.Flags().StringP("root", "r", "", "The path to the root of the site") cmd.Flags().StringP("listen", "", "", "The address to which to bind the listener") cmd.Flags().BoolP("browse", "b", false, "Enable directory browsing") cmd.Flags().BoolP("templates", "t", false, "Enable template rendering") cmd.Flags().BoolP("access-log", "", false, "Enable the access log") cmd.Flags().BoolP("debug", "v", false, "Enable verbose debug logs") cmd.RunE = caddycmd.WrapCommandFuncForCobra(cmdFileServer) cmd.AddCommand(&cobra.Command{ Use: "export-template", Short: "Exports the default file browser template", Example: "caddy file-server export-template > browse.html", RunE: func(cmd *cobra.Command, args []string) error { _, err := io.WriteString(os.Stdout, defaultBrowseTemplate) return err }, }) }, }) } func cmdFileServer(fs caddycmd.Flags) (int, error) { caddy.TrapSignals() domain := fs.String("domain") root := fs.String("root") listen := fs.String("listen") browse := fs.Bool("browse") templates := fs.Bool("templates") accessLog := fs.Bool("access-log") debug := fs.Bool("debug") var handlers []json.RawMessage if templates { handler := caddytpl.Templates{FileRoot: root} handlers = append(handlers, caddyconfig.JSONModuleObject(handler, "handler", "templates", nil)) } handler := FileServer{Root: root} if browse { handler.Browse = new(Browse) } handlers = append(handlers, caddyconfig.JSONModuleObject(handler, "handler", "file_server", nil)) route := caddyhttp.Route{HandlersRaw: handlers} if domain != "" { route.MatcherSetsRaw = []caddy.ModuleMap{ { "host": caddyconfig.JSON(caddyhttp.MatchHost{domain}, nil), }, } } server := &caddyhttp.Server{ ReadHeaderTimeout: caddy.Duration(10 * time.Second), IdleTimeout: caddy.Duration(30 * time.Second), MaxHeaderBytes: 1024 * 10, Routes: caddyhttp.RouteList{route}, } if listen == "" { if domain == "" { listen = ":80" } else { listen = ":" + strconv.Itoa(certmagic.HTTPSPort) } } server.Listen = []string{listen} if accessLog { server.Logs = &caddyhttp.ServerLogConfig{} } httpApp := caddyhttp.App{ Servers: map[string]*caddyhttp.Server{"static": server}, } 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()}, }, }, } } err := caddy.Run(cfg) if err != nil { return caddy.ExitCodeFailedStartup, err } log.Printf("Caddy serving static files on %s", listen) select {} }
Go
caddy/modules/caddyhttp/fileserver/matcher.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 fileserver import ( "encoding/json" "fmt" "io/fs" "net/http" "os" "path" "path/filepath" "runtime" "strconv" "strings" "github.com/google/cel-go/cel" "github.com/google/cel-go/common" "github.com/google/cel-go/common/operators" "github.com/google/cel-go/common/types/ref" "github.com/google/cel-go/parser" "go.uber.org/zap" exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func init() { caddy.RegisterModule(MatchFile{}) } // MatchFile is an HTTP request matcher that can match // requests based upon file existence. // // Upon matching, three new placeholders will be made // available: // // - `{http.matchers.file.relative}` The root-relative // path of the file. This is often useful when rewriting // requests. // - `{http.matchers.file.absolute}` The absolute path // of the matched file. // - `{http.matchers.file.type}` Set to "directory" if // the matched file is a directory, "file" otherwise. // - `{http.matchers.file.remainder}` Set to the remainder // of the path if the path was split by `split_path`. // // Even though file matching may depend on the OS path // separator, the placeholder values always use /. type MatchFile struct { // The file system implementation to use. By default, the // local disk file system will be used. FileSystemRaw json.RawMessage `json:"file_system,omitempty" caddy:"namespace=caddy.fs inline_key=backend"` fileSystem fs.FS // The root directory, used for creating absolute // file paths, and required when working with // relative paths; if not specified, `{http.vars.root}` // will be used, if set; otherwise, the current // directory is assumed. Accepts placeholders. Root string `json:"root,omitempty"` // The list of files to try. Each path here is // considered related to Root. If nil, the request // URL's path will be assumed. Files and // directories are treated distinctly, so to match // a directory, the filepath MUST end in a forward // slash `/`. To match a regular file, there must // be no trailing slash. Accepts placeholders. If // the policy is "first_exist", then an error may // be triggered as a fallback by configuring "=" // followed by a status code number, // for example "=404". TryFiles []string `json:"try_files,omitempty"` // How to choose a file in TryFiles. Can be: // // - first_exist // - smallest_size // - largest_size // - most_recently_modified // // Default is first_exist. TryPolicy string `json:"try_policy,omitempty"` // A list of delimiters to use to split the path in two // when trying files. If empty, no splitting will // occur, and the path will be tried as-is. For each // split value, the left-hand side of the split, // including the split value, will be the path tried. // For example, the path `/remote.php/dav/` using the // split value `.php` would try the file `/remote.php`. // Each delimiter must appear at the end of a URI path // component in order to be used as a split delimiter. SplitPath []string `json:"split_path,omitempty"` logger *zap.Logger } // CaddyModule returns the Caddy module information. func (MatchFile) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.matchers.file", New: func() caddy.Module { return new(MatchFile) }, } } // UnmarshalCaddyfile sets up the matcher from Caddyfile tokens. Syntax: // // file <files...> { // root <path> // try_files <files...> // try_policy first_exist|smallest_size|largest_size|most_recently_modified // } func (m *MatchFile) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { m.TryFiles = append(m.TryFiles, d.RemainingArgs()...) for d.NextBlock(0) { switch d.Val() { case "root": if !d.NextArg() { return d.ArgErr() } m.Root = d.Val() case "try_files": m.TryFiles = append(m.TryFiles, d.RemainingArgs()...) if len(m.TryFiles) == 0 { return d.ArgErr() } case "try_policy": if !d.NextArg() { return d.ArgErr() } m.TryPolicy = d.Val() case "split_path": m.SplitPath = d.RemainingArgs() if len(m.SplitPath) == 0 { return d.ArgErr() } default: return d.Errf("unrecognized subdirective: %s", d.Val()) } } } return nil } // CELLibrary produces options that expose this matcher for use in CEL // expression matchers. // // Example: // // expression file() // expression file({http.request.uri.path}, '/index.php') // expression file({'root': '/srv', 'try_files': [{http.request.uri.path}, '/index.php'], 'try_policy': 'first_exist', 'split_path': ['.php']}) func (MatchFile) CELLibrary(ctx caddy.Context) (cel.Library, error) { requestType := cel.ObjectType("http.Request") matcherFactory := func(data ref.Val) (caddyhttp.RequestMatcher, error) { values, err := caddyhttp.CELValueToMapStrList(data) if err != nil { return nil, err } var root string if len(values["root"]) > 0 { root = values["root"][0] } var try_policy string if len(values["try_policy"]) > 0 { root = values["try_policy"][0] } m := MatchFile{ Root: root, TryFiles: values["try_files"], TryPolicy: try_policy, SplitPath: values["split_path"], } err = m.Provision(ctx) return m, err } envOptions := []cel.EnvOption{ cel.Macros(parser.NewGlobalVarArgMacro("file", celFileMatcherMacroExpander())), cel.Function("file", cel.Overload("file_request_map", []*cel.Type{requestType, caddyhttp.CELTypeJSON}, cel.BoolType)), cel.Function("file_request_map", cel.Overload("file_request_map", []*cel.Type{requestType, caddyhttp.CELTypeJSON}, cel.BoolType), cel.SingletonBinaryBinding(caddyhttp.CELMatcherRuntimeFunction("file_request_map", matcherFactory))), } programOptions := []cel.ProgramOption{ cel.CustomDecorator(caddyhttp.CELMatcherDecorator("file_request_map", matcherFactory)), } return caddyhttp.NewMatcherCELLibrary(envOptions, programOptions), nil } func celFileMatcherMacroExpander() parser.MacroExpander { return func(eh parser.ExprHelper, target *exprpb.Expr, args []*exprpb.Expr) (*exprpb.Expr, *common.Error) { if len(args) == 0 { return eh.GlobalCall("file", eh.Ident("request"), eh.NewMap(), ), nil } if len(args) == 1 { arg := args[0] if isCELStringLiteral(arg) || isCELCaddyPlaceholderCall(arg) { return eh.GlobalCall("file", eh.Ident("request"), eh.NewMap(eh.NewMapEntry( eh.LiteralString("try_files"), eh.NewList(arg), false, )), ), nil } if isCELTryFilesLiteral(arg) { return eh.GlobalCall("file", eh.Ident("request"), arg), nil } return nil, &common.Error{ Location: eh.OffsetLocation(arg.GetId()), Message: "matcher requires either a map or string literal argument", } } for _, arg := range args { if !(isCELStringLiteral(arg) || isCELCaddyPlaceholderCall(arg)) { return nil, &common.Error{ Location: eh.OffsetLocation(arg.GetId()), Message: "matcher only supports repeated string literal arguments", } } } return eh.GlobalCall("file", eh.Ident("request"), eh.NewMap(eh.NewMapEntry( eh.LiteralString("try_files"), eh.NewList(args...), false, )), ), nil } } // Provision sets up m's defaults. func (m *MatchFile) Provision(ctx caddy.Context) error { m.logger = ctx.Logger() // establish the file system to use if len(m.FileSystemRaw) > 0 { mod, err := ctx.LoadModule(m, "FileSystemRaw") if err != nil { return fmt.Errorf("loading file system module: %v", err) } m.fileSystem = mod.(fs.FS) } if m.fileSystem == nil { m.fileSystem = osFS{} } if m.Root == "" { m.Root = "{http.vars.root}" } // if list of files to try was omitted entirely, assume URL path // (use placeholder instead of r.URL.Path; see issue #4146) if m.TryFiles == nil { m.TryFiles = []string{"{http.request.uri.path}"} } return nil } // Validate ensures m has a valid configuration. func (m MatchFile) Validate() error { switch m.TryPolicy { case "", tryPolicyFirstExist, tryPolicyLargestSize, tryPolicySmallestSize, tryPolicyMostRecentlyMod: default: return fmt.Errorf("unknown try policy %s", m.TryPolicy) } return nil } // Match returns true if r matches m. Returns true // if a file was matched. If so, four placeholders // will be available: // - http.matchers.file.relative: Path to file relative to site root // - http.matchers.file.absolute: Path to file including site root // - http.matchers.file.type: file or directory // - http.matchers.file.remainder: Portion remaining after splitting file path (if configured) func (m MatchFile) Match(r *http.Request) bool { return m.selectFile(r) } // selectFile chooses a file according to m.TryPolicy by appending // the paths in m.TryFiles to m.Root, with placeholder replacements. func (m MatchFile) selectFile(r *http.Request) (matched bool) { repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) root := filepath.Clean(repl.ReplaceAll(m.Root, ".")) type matchCandidate struct { fullpath, relative, splitRemainder string } // makeCandidates evaluates placeholders in file and expands any glob expressions // to build a list of file candidates. Special glob characters are escaped in // placeholder replacements so globs cannot be expanded from placeholders, and // globs are not evaluated on Windows because of its path separator character: // escaping is not supported so we can't safely glob on Windows, or we can't // support placeholders on Windows (pick one). (Actually, evaluating untrusted // globs is not the end of the world since the file server will still hide any // hidden files, it just might lead to unexpected behavior.) makeCandidates := func(file string) []matchCandidate { // first, evaluate placeholders in the file pattern expandedFile, err := repl.ReplaceFunc(file, func(variable string, val any) (any, error) { if runtime.GOOS == "windows" { return val, nil } switch v := val.(type) { case string: return globSafeRepl.Replace(v), nil case fmt.Stringer: return globSafeRepl.Replace(v.String()), nil } return val, nil }) if err != nil { m.logger.Error("evaluating placeholders", zap.Error(err)) expandedFile = file // "oh well," I guess? } // clean the path and split, if configured -- we must split before // globbing so that the file system doesn't include the remainder // ("afterSplit") in the filename; be sure to restore trailing slash beforeSplit, afterSplit := m.firstSplit(path.Clean(expandedFile)) if strings.HasSuffix(file, "/") { beforeSplit += "/" } // create the full path to the file by prepending the site root fullPattern := caddyhttp.SanitizedPathJoin(root, beforeSplit) // expand glob expressions, but not on Windows because Glob() doesn't // support escaping on Windows due to path separator) var globResults []string if runtime.GOOS == "windows" { globResults = []string{fullPattern} // precious Windows } else { globResults, err = fs.Glob(m.fileSystem, fullPattern) if err != nil { m.logger.Error("expanding glob", zap.Error(err)) } } // for each glob result, combine all the forms of the path var candidates []matchCandidate for _, result := range globResults { candidates = append(candidates, matchCandidate{ fullpath: result, relative: strings.TrimPrefix(result, root), splitRemainder: afterSplit, }) } return candidates } // setPlaceholders creates the placeholders for the matched file setPlaceholders := func(candidate matchCandidate, info fs.FileInfo) { repl.Set("http.matchers.file.relative", filepath.ToSlash(candidate.relative)) repl.Set("http.matchers.file.absolute", filepath.ToSlash(candidate.fullpath)) repl.Set("http.matchers.file.remainder", filepath.ToSlash(candidate.splitRemainder)) fileType := "file" if info.IsDir() { fileType = "directory" } repl.Set("http.matchers.file.type", fileType) } // match file according to the configured policy switch m.TryPolicy { case "", tryPolicyFirstExist: for _, pattern := range m.TryFiles { if err := parseErrorCode(pattern); err != nil { caddyhttp.SetVar(r.Context(), caddyhttp.MatcherErrorVarKey, err) return } candidates := makeCandidates(pattern) for _, c := range candidates { if info, exists := m.strictFileExists(c.fullpath); exists { setPlaceholders(c, info) return true } } } case tryPolicyLargestSize: var largestSize int64 var largest matchCandidate var largestInfo os.FileInfo for _, pattern := range m.TryFiles { candidates := makeCandidates(pattern) for _, c := range candidates { info, err := fs.Stat(m.fileSystem, c.fullpath) if err == nil && info.Size() > largestSize { largestSize = info.Size() largest = c largestInfo = info } } } if largestInfo == nil { return false } setPlaceholders(largest, largestInfo) return true case tryPolicySmallestSize: var smallestSize int64 var smallest matchCandidate var smallestInfo os.FileInfo for _, pattern := range m.TryFiles { candidates := makeCandidates(pattern) for _, c := range candidates { info, err := fs.Stat(m.fileSystem, c.fullpath) if err == nil && (smallestSize == 0 || info.Size() < smallestSize) { smallestSize = info.Size() smallest = c smallestInfo = info } } } if smallestInfo == nil { return false } setPlaceholders(smallest, smallestInfo) return true case tryPolicyMostRecentlyMod: var recent matchCandidate var recentInfo os.FileInfo for _, pattern := range m.TryFiles { candidates := makeCandidates(pattern) for _, c := range candidates { info, err := fs.Stat(m.fileSystem, c.fullpath) if err == nil && (recentInfo == nil || info.ModTime().After(recentInfo.ModTime())) { recent = c recentInfo = info } } } if recentInfo == nil { return false } setPlaceholders(recent, recentInfo) return true } return } // parseErrorCode checks if the input is a status // code number, prefixed by "=", and returns an // error if so. func parseErrorCode(input string) error { if len(input) > 1 && input[0] == '=' { code, err := strconv.Atoi(input[1:]) if err != nil || code < 100 || code > 999 { return nil } return caddyhttp.Error(code, fmt.Errorf("%s", input[1:])) } return nil } // strictFileExists returns true if file exists // and matches the convention of the given file // path. If the path ends in a forward slash, // the file must also be a directory; if it does // NOT end in a forward slash, the file must NOT // be a directory. func (m MatchFile) strictFileExists(file string) (os.FileInfo, bool) { info, err := fs.Stat(m.fileSystem, file) if err != nil { // in reality, this can be any error // such as permission or even obscure // ones like "is not a directory" (when // trying to stat a file within a file); // in those cases we can't be sure if // the file exists, so we just treat any // error as if it does not exist; see // https://stackoverflow.com/a/12518877/1048862 return nil, false } if strings.HasSuffix(file, separator) { // by convention, file paths ending // in a path separator must be a directory return info, info.IsDir() } // by convention, file paths NOT ending // in a path separator must NOT be a directory return info, !info.IsDir() } // firstSplit returns the first result where the path // can be split in two by a value in m.SplitPath. The // return values are the first piece of the path that // ends with the split substring and the remainder. // If the path cannot be split, the path is returned // as-is (with no remainder). func (m MatchFile) firstSplit(path string) (splitPart, remainder string) { for _, split := range m.SplitPath { if idx := indexFold(path, split); idx > -1 { pos := idx + len(split) // skip the split if it's not the final part of the filename if pos != len(path) && !strings.HasPrefix(path[pos:], "/") { continue } return path[:pos], path[pos:] } } return path, "" } // There is no strings.IndexFold() function like there is strings.EqualFold(), // but we can use strings.EqualFold() to build our own case-insensitive // substring search (as of Go 1.14). func indexFold(haystack, needle string) int { nlen := len(needle) for i := 0; i+nlen < len(haystack); i++ { if strings.EqualFold(haystack[i:i+nlen], needle) { return i } } return -1 } // isCELTryFilesLiteral returns whether the expression resolves to a map literal containing // only string keys with or a placeholder call. func isCELTryFilesLiteral(e *exprpb.Expr) bool { switch e.GetExprKind().(type) { case *exprpb.Expr_StructExpr: structExpr := e.GetStructExpr() if structExpr.GetMessageName() != "" { return false } for _, entry := range structExpr.GetEntries() { mapKey := entry.GetMapKey() mapVal := entry.GetValue() if !isCELStringLiteral(mapKey) { return false } mapKeyStr := mapKey.GetConstExpr().GetStringValue() if mapKeyStr == "try_files" || mapKeyStr == "split_path" { if !isCELStringListLiteral(mapVal) { return false } } else if mapKeyStr == "try_policy" || mapKeyStr == "root" { if !(isCELStringExpr(mapVal)) { return false } } else { return false } } return true } return false } // isCELStringExpr indicates whether the expression is a supported string expression func isCELStringExpr(e *exprpb.Expr) bool { return isCELStringLiteral(e) || isCELCaddyPlaceholderCall(e) || isCELConcatCall(e) } // isCELStringLiteral returns whether the expression is a CEL string literal. func isCELStringLiteral(e *exprpb.Expr) bool { switch e.GetExprKind().(type) { case *exprpb.Expr_ConstExpr: constant := e.GetConstExpr() switch constant.GetConstantKind().(type) { case *exprpb.Constant_StringValue: return true } } return false } // isCELCaddyPlaceholderCall returns whether the expression is a caddy placeholder call. func isCELCaddyPlaceholderCall(e *exprpb.Expr) bool { switch e.GetExprKind().(type) { case *exprpb.Expr_CallExpr: call := e.GetCallExpr() if call.GetFunction() == "caddyPlaceholder" { return true } } return false } // isCELConcatCall tests whether the expression is a concat function (+) with string, placeholder, or // other concat call arguments. func isCELConcatCall(e *exprpb.Expr) bool { switch e.GetExprKind().(type) { case *exprpb.Expr_CallExpr: call := e.GetCallExpr() if call.GetTarget() != nil { return false } if call.GetFunction() != operators.Add { return false } for _, arg := range call.GetArgs() { if !isCELStringExpr(arg) { return false } } return true } return false } // isCELStringListLiteral returns whether the expression resolves to a list literal // containing only string constants or a placeholder call. func isCELStringListLiteral(e *exprpb.Expr) bool { switch e.GetExprKind().(type) { case *exprpb.Expr_ListExpr: list := e.GetListExpr() for _, elem := range list.GetElements() { if !isCELStringExpr(elem) { return false } } return true } return false } // globSafeRepl replaces special glob characters with escaped // equivalents. Note that the filepath godoc states that // escaping is not done on Windows because of the separator. var globSafeRepl = strings.NewReplacer( "*", "\\*", "[", "\\[", "?", "\\?", ) const ( tryPolicyFirstExist = "first_exist" tryPolicyLargestSize = "largest_size" tryPolicySmallestSize = "smallest_size" tryPolicyMostRecentlyMod = "most_recently_modified" ) // Interface guards var ( _ caddy.Validator = (*MatchFile)(nil) _ caddyhttp.RequestMatcher = (*MatchFile)(nil) _ caddyhttp.CELLibraryProducer = (*MatchFile)(nil) )
Go
caddy/modules/caddyhttp/fileserver/matcher_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 fileserver import ( "context" "net/http" "net/http/httptest" "net/url" "os" "runtime" "testing" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func TestFileMatcher(t *testing.T) { // Windows doesn't like colons in files names isWindows := runtime.GOOS == "windows" if !isWindows { filename := "with:in-name.txt" f, err := os.Create("./testdata/" + filename) if err != nil { t.Fail() return } t.Cleanup(func() { os.Remove("./testdata/" + filename) }) f.WriteString(filename) f.Close() } for i, tc := range []struct { path string expectedPath string expectedType string matched bool }{ { path: "/foo.txt", expectedPath: "/foo.txt", expectedType: "file", matched: true, }, { path: "/foo.txt/", expectedPath: "/foo.txt", expectedType: "file", matched: true, }, { path: "/foo.txt?a=b", expectedPath: "/foo.txt", expectedType: "file", matched: true, }, { path: "/foodir", expectedPath: "/foodir/", expectedType: "directory", matched: true, }, { path: "/foodir/", expectedPath: "/foodir/", expectedType: "directory", matched: true, }, { path: "/foodir/foo.txt", expectedPath: "/foodir/foo.txt", expectedType: "file", matched: true, }, { path: "/missingfile.php", matched: false, }, { path: "ู…ู„ู.txt", // the path file name is not escaped expectedPath: "/ู…ู„ู.txt", expectedType: "file", matched: true, }, { path: url.PathEscape("ู…ู„ู.txt"), // singly-escaped path expectedPath: "/ู…ู„ู.txt", expectedType: "file", matched: true, }, { path: url.PathEscape(url.PathEscape("ู…ู„ู.txt")), // doubly-escaped path expectedPath: "/%D9%85%D9%84%D9%81.txt", expectedType: "file", matched: true, }, { path: "./with:in-name.txt", // browsers send the request with the path as such expectedPath: "/with:in-name.txt", expectedType: "file", matched: !isWindows, }, } { m := &MatchFile{ fileSystem: osFS{}, Root: "./testdata", TryFiles: []string{"{http.request.uri.path}", "{http.request.uri.path}/"}, } u, err := url.Parse(tc.path) if err != nil { t.Errorf("Test %d: parsing path: %v", i, err) } req := &http.Request{URL: u} repl := caddyhttp.NewTestReplacer(req) result := m.Match(req) if result != tc.matched { t.Errorf("Test %d: expected match=%t, got %t", i, tc.matched, result) } rel, ok := repl.Get("http.matchers.file.relative") if !ok && result { t.Errorf("Test %d: expected replacer value", i) } if !result { continue } if rel != tc.expectedPath { t.Errorf("Test %d: actual path: %v, expected: %v", i, rel, tc.expectedPath) } fileType, _ := repl.Get("http.matchers.file.type") if fileType != tc.expectedType { t.Errorf("Test %d: actual file type: %v, expected: %v", i, fileType, tc.expectedType) } } } func TestPHPFileMatcher(t *testing.T) { for i, tc := range []struct { path string expectedPath string expectedType string matched bool }{ { path: "/index.php", expectedPath: "/index.php", expectedType: "file", matched: true, }, { path: "/index.php/somewhere", expectedPath: "/index.php", expectedType: "file", matched: true, }, { path: "/remote.php", expectedPath: "/remote.php", expectedType: "file", matched: true, }, { path: "/remote.php/somewhere", expectedPath: "/remote.php", expectedType: "file", matched: true, }, { path: "/missingfile.php", matched: false, }, { path: "/notphp.php.txt", expectedPath: "/notphp.php.txt", expectedType: "file", matched: true, }, { path: "/notphp.php.txt/", expectedPath: "/notphp.php.txt", expectedType: "file", matched: true, }, { path: "/notphp.php.txt.suffixed", matched: false, }, { path: "/foo.php.php/index.php", expectedPath: "/foo.php.php/index.php", expectedType: "file", matched: true, }, { // See https://github.com/caddyserver/caddy/issues/3623 path: "/%E2%C3", expectedPath: "/%E2%C3", expectedType: "file", matched: false, }, { path: "/index.php?path={path}&{query}", expectedPath: "/index.php", expectedType: "file", matched: true, }, } { m := &MatchFile{ fileSystem: osFS{}, Root: "./testdata", TryFiles: []string{"{http.request.uri.path}", "{http.request.uri.path}/index.php"}, SplitPath: []string{".php"}, } u, err := url.Parse(tc.path) if err != nil { t.Errorf("Test %d: parsing path: %v", i, err) } req := &http.Request{URL: u} repl := caddyhttp.NewTestReplacer(req) result := m.Match(req) if result != tc.matched { t.Errorf("Test %d: expected match=%t, got %t", i, tc.matched, result) } rel, ok := repl.Get("http.matchers.file.relative") if !ok && result { t.Errorf("Test %d: expected replacer value", i) } if !result { continue } if rel != tc.expectedPath { t.Errorf("Test %d: actual path: %v, expected: %v", i, rel, tc.expectedPath) } fileType, _ := repl.Get("http.matchers.file.type") if fileType != tc.expectedType { t.Errorf("Test %d: actual file type: %v, expected: %v", i, fileType, tc.expectedType) } } } func TestFirstSplit(t *testing.T) { m := MatchFile{SplitPath: []string{".php"}} actual, remainder := m.firstSplit("index.PHP/somewhere") expected := "index.PHP" expectedRemainder := "/somewhere" if actual != expected { t.Errorf("Expected split %s but got %s", expected, actual) } if remainder != expectedRemainder { t.Errorf("Expected remainder %s but got %s", expectedRemainder, remainder) } } var ( expressionTests = []struct { name string expression *caddyhttp.MatchExpression urlTarget string httpMethod string httpHeader *http.Header wantErr bool wantResult bool clientCertificate []byte }{ { name: "file error no args (MatchFile)", expression: &caddyhttp.MatchExpression{ Expr: `file()`, }, urlTarget: "https://example.com/foo.txt", wantResult: true, }, { name: "file error bad try files (MatchFile)", expression: &caddyhttp.MatchExpression{ Expr: `file({"try_file": ["bad_arg"]})`, }, urlTarget: "https://example.com/foo", wantErr: true, }, { name: "file match short pattern index.php (MatchFile)", expression: &caddyhttp.MatchExpression{ Expr: `file("index.php")`, }, urlTarget: "https://example.com/foo", wantResult: true, }, { name: "file match short pattern foo.txt (MatchFile)", expression: &caddyhttp.MatchExpression{ Expr: `file({http.request.uri.path})`, }, urlTarget: "https://example.com/foo.txt", wantResult: true, }, { name: "file match index.php (MatchFile)", expression: &caddyhttp.MatchExpression{ Expr: `file({"root": "./testdata", "try_files": [{http.request.uri.path}, "/index.php"]})`, }, urlTarget: "https://example.com/foo", wantResult: true, }, { name: "file match long pattern foo.txt (MatchFile)", expression: &caddyhttp.MatchExpression{ Expr: `file({"root": "./testdata", "try_files": [{http.request.uri.path}]})`, }, urlTarget: "https://example.com/foo.txt", wantResult: true, }, { name: "file match long pattern foo.txt with concatenation (MatchFile)", expression: &caddyhttp.MatchExpression{ Expr: `file({"root": ".", "try_files": ["./testdata" + {http.request.uri.path}]})`, }, urlTarget: "https://example.com/foo.txt", wantResult: true, }, { name: "file not match long pattern (MatchFile)", expression: &caddyhttp.MatchExpression{ Expr: `file({"root": "./testdata", "try_files": [{http.request.uri.path}]})`, }, urlTarget: "https://example.com/nopenope.txt", wantResult: false, }, } ) func TestMatchExpressionMatch(t *testing.T) { for _, tst := range expressionTests { tc := tst t.Run(tc.name, func(t *testing.T) { err := tc.expression.Provision(caddy.Context{}) 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 := caddyhttp.NewTestReplacer(req) repl.Set("http.vars.root", "./testdata") ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl) req = req.WithContext(ctx) if tc.expression.Match(req) != tc.wantResult { t.Errorf("MatchExpression.Match() expected to return '%t', for expression : '%s'", tc.wantResult, tc.expression.Expr) } }) } }
Go
caddy/modules/caddyhttp/fileserver/staticfiles.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 fileserver import ( "encoding/json" "errors" "fmt" "io" "io/fs" weakrand "math/rand" "mime" "net/http" "os" "path" "path/filepath" "runtime" "strconv" "strings" "go.uber.org/zap" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" "github.com/caddyserver/caddy/v2/modules/caddyhttp/encode" ) func init() { caddy.RegisterModule(FileServer{}) } // FileServer implements a handler that serves static files. // // The path of the file to serve is constructed by joining the site root // and the sanitized request path. Any and all files within the root and // links with targets outside the site root may therefore be accessed. // For example, with a site root of `/www`, requests to `/foo/bar.txt` // will serve the file at `/www/foo/bar.txt`. // // The request path is sanitized using the Go standard library's // path.Clean() function (https://pkg.go.dev/path#Clean) before being // joined to the root. Request paths must be valid and well-formed. // // For requests that access directories instead of regular files, // Caddy will attempt to serve an index file if present. For example, // a request to `/dir/` will attempt to serve `/dir/index.html` if // it exists. The index file names to try are configurable. If a // requested directory does not have an index file, Caddy writes a // 404 response. Alternatively, file browsing can be enabled with // the "browse" parameter which shows a list of files when directories // are requested if no index file is present. If "browse" is enabled, // Caddy may serve a JSON array of the dirctory listing when the `Accept` // header mentions `application/json` with the following structure: // // [{ // "name": "", // "size": 0, // "url": "", // "mod_time": "", // "mode": 0, // "is_dir": false, // "is_symlink": false // }] // // with the `url` being relative to the request path and `mod_time` in the RFC 3339 format // with sub-second precision. For any other value for the `Accept` header, the // respective browse template is executed with `Content-Type: text/html`. // // By default, this handler will canonicalize URIs so that requests to // directories end with a slash, but requests to regular files do not. // This is enforced with HTTP redirects automatically and can be disabled. // Canonicalization redirects are not issued, however, if a URI rewrite // modified the last component of the path (the filename). // // This handler sets the Etag and Last-Modified headers for static files. // It does not perform MIME sniffing to determine Content-Type based on // contents, but does use the extension (if known); see the Go docs for // details: https://pkg.go.dev/mime#TypeByExtension // // The file server properly handles requests with If-Match, // If-Unmodified-Since, If-Modified-Since, If-None-Match, Range, and // If-Range headers. It includes the file's modification time in the // Last-Modified header of the response. type FileServer struct { // The file system implementation to use. By default, Caddy uses the local // disk file system. // // File system modules used here must adhere to the following requirements: // - Implement fs.FS interface. // - Support seeking on opened files; i.e.returned fs.File values must // implement the io.Seeker interface. This is required for determining // Content-Length and satisfying Range requests. // - fs.File values that represent directories must implement the // fs.ReadDirFile interface so that directory listings can be procured. FileSystemRaw json.RawMessage `json:"file_system,omitempty" caddy:"namespace=caddy.fs inline_key=backend"` fileSystem fs.FS // The path to the root of the site. Default is `{http.vars.root}` if set, // or current working directory otherwise. This should be a trusted value. // // Note that a site root is not a sandbox. Although the file server does // sanitize the request URI to prevent directory traversal, files (including // links) within the site root may be directly accessed based on the request // path. Files and folders within the root should be secure and trustworthy. Root string `json:"root,omitempty"` // A list of files or folders to hide; the file server will pretend as if // they don't exist. Accepts globular patterns like `*.ext` or `/foo/*/bar` // as well as placeholders. Because site roots can be dynamic, this list // uses file system paths, not request paths. To clarify, the base of // relative paths is the current working directory, NOT the site root. // // Entries without a path separator (`/` or `\` depending on OS) will match // any file or directory of that name regardless of its path. To hide only a // specific file with a name that may not be unique, always use a path // separator. For example, to hide all files or folder trees named "hidden", // put "hidden" in the list. To hide only ./hidden, put "./hidden" in the list. // // When possible, all paths are resolved to their absolute form before // comparisons are made. For maximum clarity and explictness, use complete, // absolute paths; or, for greater portability, use relative paths instead. Hide []string `json:"hide,omitempty"` // The names of files to try as index files if a folder is requested. // Default: index.html, index.txt. IndexNames []string `json:"index_names,omitempty"` // Enables file listings if a directory was requested and no index // file is present. Browse *Browse `json:"browse,omitempty"` // Use redirects to enforce trailing slashes for directories, or to // remove trailing slash from URIs for files. Default is true. // // Canonicalization will not happen if the last element of the request's // path (the filename) is changed in an internal rewrite, to avoid // clobbering the explicit rewrite with implicit behavior. CanonicalURIs *bool `json:"canonical_uris,omitempty"` // Override the status code written when successfully serving a file. // Particularly useful when explicitly serving a file as display for // an error, like a 404 page. A placeholder may be used. By default, // the status code will typically be 200, or 206 for partial content. StatusCode caddyhttp.WeakString `json:"status_code,omitempty"` // If pass-thru mode is enabled and a requested file is not found, // it will invoke the next handler in the chain instead of returning // a 404 error. By default, this is false (disabled). PassThru bool `json:"pass_thru,omitempty"` // Selection of encoders to use to check for precompressed files. PrecompressedRaw caddy.ModuleMap `json:"precompressed,omitempty" caddy:"namespace=http.precompressed"` // If the client has no strong preference (q-factor), choose these encodings in order. // If no order specified here, the first encoding from the Accept-Encoding header // that both client and server support is used PrecompressedOrder []string `json:"precompressed_order,omitempty"` precompressors map[string]encode.Precompressed logger *zap.Logger } // CaddyModule returns the Caddy module information. func (FileServer) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.handlers.file_server", New: func() caddy.Module { return new(FileServer) }, } } // Provision sets up the static files responder. func (fsrv *FileServer) Provision(ctx caddy.Context) error { fsrv.logger = ctx.Logger() // establish which file system (possibly a virtual one) we'll be using if len(fsrv.FileSystemRaw) > 0 { mod, err := ctx.LoadModule(fsrv, "FileSystemRaw") if err != nil { return fmt.Errorf("loading file system module: %v", err) } fsrv.fileSystem = mod.(fs.FS) } if fsrv.fileSystem == nil { fsrv.fileSystem = osFS{} } if fsrv.Root == "" { fsrv.Root = "{http.vars.root}" } if fsrv.IndexNames == nil { fsrv.IndexNames = defaultIndexNames } // for hide paths that are static (i.e. no placeholders), we can transform them into // absolute paths before the server starts for very slight performance improvement for i, h := range fsrv.Hide { if !strings.Contains(h, "{") && strings.Contains(h, separator) { if abs, err := filepath.Abs(h); err == nil { fsrv.Hide[i] = abs } } } // support precompressed sidecar files mods, err := ctx.LoadModule(fsrv, "PrecompressedRaw") if err != nil { return fmt.Errorf("loading encoder modules: %v", err) } for modName, modIface := range mods.(map[string]any) { p, ok := modIface.(encode.Precompressed) if !ok { return fmt.Errorf("module %s is not precompressor", modName) } ae := p.AcceptEncoding() if ae == "" { return fmt.Errorf("precompressor does not specify an Accept-Encoding value") } suffix := p.Suffix() if suffix == "" { return fmt.Errorf("precompressor does not specify a Suffix value") } if _, ok := fsrv.precompressors[ae]; ok { return fmt.Errorf("precompressor already added: %s", ae) } if fsrv.precompressors == nil { fsrv.precompressors = make(map[string]encode.Precompressed) } fsrv.precompressors[ae] = p } return nil } func (fsrv *FileServer) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) if runtime.GOOS == "windows" { // reject paths with Alternate Data Streams (ADS) if strings.Contains(r.URL.Path, ":") { return caddyhttp.Error(http.StatusBadRequest, fmt.Errorf("illegal ADS path")) } // reject paths with "8.3" short names trimmedPath := strings.TrimRight(r.URL.Path, ". ") // Windows ignores trailing dots and spaces, sigh if len(path.Base(trimmedPath)) <= 12 && strings.Contains(trimmedPath, "~") { return caddyhttp.Error(http.StatusBadRequest, fmt.Errorf("illegal short name")) } // both of those could bypass file hiding or possibly leak information even if the file is not hidden } filesToHide := fsrv.transformHidePaths(repl) root := repl.ReplaceAll(fsrv.Root, ".") // remove any trailing `/` as it breaks fs.ValidPath() in the stdlib filename := strings.TrimSuffix(caddyhttp.SanitizedPathJoin(root, r.URL.Path), "/") fsrv.logger.Debug("sanitized path join", zap.String("site_root", root), zap.String("request_path", r.URL.Path), zap.String("result", filename)) // get information about the file info, err := fs.Stat(fsrv.fileSystem, filename) if err != nil { err = fsrv.mapDirOpenError(err, filename) if errors.Is(err, fs.ErrNotExist) || errors.Is(err, fs.ErrInvalid) { return fsrv.notFound(w, r, next) } else if errors.Is(err, fs.ErrPermission) { return caddyhttp.Error(http.StatusForbidden, err) } return caddyhttp.Error(http.StatusInternalServerError, err) } // if the request mapped to a directory, see if // there is an index file we can serve var implicitIndexFile bool if info.IsDir() && len(fsrv.IndexNames) > 0 { for _, indexPage := range fsrv.IndexNames { indexPage := repl.ReplaceAll(indexPage, "") indexPath := caddyhttp.SanitizedPathJoin(filename, indexPage) if fileHidden(indexPath, filesToHide) { // pretend this file doesn't exist fsrv.logger.Debug("hiding index file", zap.String("filename", indexPath), zap.Strings("files_to_hide", filesToHide)) continue } indexInfo, err := fs.Stat(fsrv.fileSystem, indexPath) if err != nil { continue } // don't rewrite the request path to append // the index file, because we might need to // do a canonical-URL redirect below based // on the URL as-is // we've chosen to use this index file, // so replace the last file info and path // with that of the index file info = indexInfo filename = indexPath implicitIndexFile = true fsrv.logger.Debug("located index file", zap.String("filename", filename)) break } } // if still referencing a directory, delegate // to browse or return an error if info.IsDir() { fsrv.logger.Debug("no index file in directory", zap.String("path", filename), zap.Strings("index_filenames", fsrv.IndexNames)) if fsrv.Browse != nil && !fileHidden(filename, filesToHide) { return fsrv.serveBrowse(root, filename, w, r, next) } return fsrv.notFound(w, r, next) } // one last check to ensure the file isn't hidden (we might // have changed the filename from when we last checked) if fileHidden(filename, filesToHide) { fsrv.logger.Debug("hiding file", zap.String("filename", filename), zap.Strings("files_to_hide", filesToHide)) return fsrv.notFound(w, r, next) } // if URL canonicalization is enabled, we need to enforce trailing // slash convention: if a directory, trailing slash; if a file, no // trailing slash - not enforcing this can break relative hrefs // in HTML (see https://github.com/caddyserver/caddy/issues/2741) if fsrv.CanonicalURIs == nil || *fsrv.CanonicalURIs { // Only redirect if the last element of the path (the filename) was not // rewritten; if the admin wanted to rewrite to the canonical path, they // would have, and we have to be very careful not to introduce unwanted // redirects and especially redirect loops! // See https://github.com/caddyserver/caddy/issues/4205. origReq := r.Context().Value(caddyhttp.OriginalRequestCtxKey).(http.Request) if path.Base(origReq.URL.Path) == path.Base(r.URL.Path) { if implicitIndexFile && !strings.HasSuffix(origReq.URL.Path, "/") { to := origReq.URL.Path + "/" fsrv.logger.Debug("redirecting to canonical URI (adding trailing slash for directory)", zap.String("from_path", origReq.URL.Path), zap.String("to_path", to)) return redirect(w, r, to) } else if !implicitIndexFile && strings.HasSuffix(origReq.URL.Path, "/") { to := origReq.URL.Path[:len(origReq.URL.Path)-1] fsrv.logger.Debug("redirecting to canonical URI (removing trailing slash for file)", zap.String("from_path", origReq.URL.Path), zap.String("to_path", to)) return redirect(w, r, to) } } } var file fs.File // etag is usually unset, but if the user knows what they're doing, let them override it etag := w.Header().Get("Etag") // check for precompressed files for _, ae := range encode.AcceptedEncodings(r, fsrv.PrecompressedOrder) { precompress, ok := fsrv.precompressors[ae] if !ok { continue } compressedFilename := filename + precompress.Suffix() compressedInfo, err := fs.Stat(fsrv.fileSystem, compressedFilename) if err != nil || compressedInfo.IsDir() { fsrv.logger.Debug("precompressed file not accessible", zap.String("filename", compressedFilename), zap.Error(err)) continue } fsrv.logger.Debug("opening compressed sidecar file", zap.String("filename", compressedFilename), zap.Error(err)) file, err = fsrv.openFile(compressedFilename, w) if err != nil { fsrv.logger.Warn("opening precompressed file failed", zap.String("filename", compressedFilename), zap.Error(err)) if caddyErr, ok := err.(caddyhttp.HandlerError); ok && caddyErr.StatusCode == http.StatusServiceUnavailable { return err } file = nil continue } defer file.Close() w.Header().Set("Content-Encoding", ae) w.Header().Del("Accept-Ranges") w.Header().Add("Vary", "Accept-Encoding") // don't assign info = compressedInfo because sidecars are kind // of transparent; however we do need to set the Etag: // https://caddy.community/t/gzipped-sidecar-file-wrong-same-etag/16793 if etag == "" { etag = calculateEtag(compressedInfo) } break } // no precompressed file found, use the actual file if file == nil { fsrv.logger.Debug("opening file", zap.String("filename", filename)) // open the file file, err = fsrv.openFile(filename, w) if err != nil { if herr, ok := err.(caddyhttp.HandlerError); ok && herr.StatusCode == http.StatusNotFound { return fsrv.notFound(w, r, next) } return err // error is already structured } defer file.Close() if etag == "" { etag = calculateEtag(info) } } // at this point, we're serving a file; Go std lib supports only // GET and HEAD, which is sensible for a static file server - reject // any other methods (see issue #5166) if r.Method != http.MethodGet && r.Method != http.MethodHead { // if we're in an error context, then it doesn't make sense // to repeat the error; just continue because we're probably // trying to write an error page response (see issue #5703) if _, ok := r.Context().Value(caddyhttp.ErrorCtxKey).(error); !ok { w.Header().Add("Allow", "GET, HEAD") return caddyhttp.Error(http.StatusMethodNotAllowed, nil) } } // set the Etag - note that a conditional If-None-Match request is handled // by http.ServeContent below, which checks against this Etag value if etag != "" { w.Header().Set("Etag", etag) } if w.Header().Get("Content-Type") == "" { mtyp := mime.TypeByExtension(filepath.Ext(filename)) if mtyp == "" { // do not allow Go to sniff the content-type; see https://www.youtube.com/watch?v=8t8JYpt0egE w.Header()["Content-Type"] = nil } else { w.Header().Set("Content-Type", mtyp) } } var statusCodeOverride int // if this handler exists in an error context (i.e. is part of a // handler chain that is supposed to handle a previous error), // we should set status code to the one from the error instead // of letting http.ServeContent set the default (usually 200) if reqErr, ok := r.Context().Value(caddyhttp.ErrorCtxKey).(error); ok { statusCodeOverride = http.StatusInternalServerError if handlerErr, ok := reqErr.(caddyhttp.HandlerError); ok { if handlerErr.StatusCode > 0 { statusCodeOverride = handlerErr.StatusCode } } } // if a status code override is configured, run the replacer on it if codeStr := fsrv.StatusCode.String(); codeStr != "" { statusCodeOverride, err = strconv.Atoi(repl.ReplaceAll(codeStr, "")) if err != nil { return caddyhttp.Error(http.StatusInternalServerError, err) } } // if we do have an override from the previous two parts, then // we wrap the response writer to intercept the WriteHeader call if statusCodeOverride > 0 { w = statusOverrideResponseWriter{ResponseWriter: w, code: statusCodeOverride} } // let the standard library do what it does best; note, however, // that errors generated by ServeContent are written immediately // to the response, so we cannot handle them (but errors there // are rare) http.ServeContent(w, r, info.Name(), info.ModTime(), file.(io.ReadSeeker)) return nil } // openFile opens the file at the given filename. If there was an error, // the response is configured to inform the client how to best handle it // and a well-described handler error is returned (do not wrap the // returned error value). func (fsrv *FileServer) openFile(filename string, w http.ResponseWriter) (fs.File, error) { file, err := fsrv.fileSystem.Open(filename) if err != nil { err = fsrv.mapDirOpenError(err, filename) if os.IsNotExist(err) { fsrv.logger.Debug("file not found", zap.String("filename", filename), zap.Error(err)) return nil, caddyhttp.Error(http.StatusNotFound, err) } else if os.IsPermission(err) { fsrv.logger.Debug("permission denied", zap.String("filename", filename), zap.Error(err)) return nil, caddyhttp.Error(http.StatusForbidden, err) } // maybe the server is under load and ran out of file descriptors? // have client wait arbitrary seconds to help prevent a stampede //nolint:gosec backoff := weakrand.Intn(maxBackoff-minBackoff) + minBackoff w.Header().Set("Retry-After", strconv.Itoa(backoff)) fsrv.logger.Debug("retry after backoff", zap.String("filename", filename), zap.Int("backoff", backoff), zap.Error(err)) return nil, caddyhttp.Error(http.StatusServiceUnavailable, err) } return file, nil } // mapDirOpenError maps the provided non-nil error from opening name // to a possibly better non-nil error. In particular, it turns OS-specific errors // about opening files in non-directories into os.ErrNotExist. See golang/go#18984. // Adapted from the Go standard library; originally written by Nathaniel Caza. // https://go-review.googlesource.com/c/go/+/36635/ // https://go-review.googlesource.com/c/go/+/36804/ func (fsrv *FileServer) mapDirOpenError(originalErr error, name string) error { if errors.Is(originalErr, fs.ErrNotExist) || errors.Is(originalErr, fs.ErrPermission) { return originalErr } parts := strings.Split(name, separator) for i := range parts { if parts[i] == "" { continue } fi, err := fs.Stat(fsrv.fileSystem, strings.Join(parts[:i+1], separator)) if err != nil { return originalErr } if !fi.IsDir() { return fs.ErrNotExist } } return originalErr } // transformHidePaths performs replacements for all the elements of fsrv.Hide and // makes them absolute paths (if they contain a path separator), then returns a // new list of the transformed values. func (fsrv *FileServer) transformHidePaths(repl *caddy.Replacer) []string { hide := make([]string, len(fsrv.Hide)) for i := range fsrv.Hide { hide[i] = repl.ReplaceAll(fsrv.Hide[i], "") if strings.Contains(hide[i], separator) { abs, err := filepath.Abs(hide[i]) if err == nil { hide[i] = abs } } } return hide } // fileHidden returns true if filename is hidden according to the hide list. // filename must be a relative or absolute file system path, not a request // URI path. It is expected that all the paths in the hide list are absolute // paths or are singular filenames (without a path separator). func fileHidden(filename string, hide []string) bool { if len(hide) == 0 { return false } // all path comparisons use the complete absolute path if possible filenameAbs, err := filepath.Abs(filename) if err == nil { filename = filenameAbs } var components []string for _, h := range hide { if !strings.Contains(h, separator) { // if there is no separator in h, then we assume the user // wants to hide any files or folders that match that // name; thus we have to compare against each component // of the filename, e.g. hiding "bar" would hide "/bar" // as well as "/foo/bar/baz" but not "/barstool". if len(components) == 0 { components = strings.Split(filename, separator) } for _, c := range components { if hidden, _ := filepath.Match(h, c); hidden { return true } } } else if strings.HasPrefix(filename, h) { // if there is a separator in h, and filename is exactly // prefixed with h, then we can do a prefix match so that // "/foo" matches "/foo/bar" but not "/foobar". withoutPrefix := strings.TrimPrefix(filename, h) if strings.HasPrefix(withoutPrefix, separator) { return true } } // in the general case, a glob match will suffice if hidden, _ := filepath.Match(h, filename); hidden { return true } } return false } // notFound returns a 404 error or, if pass-thru is enabled, // it calls the next handler in the chain. func (fsrv *FileServer) notFound(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { if fsrv.PassThru { return next.ServeHTTP(w, r) } return caddyhttp.Error(http.StatusNotFound, nil) } // calculateEtag produces a strong etag by default, although, for // efficiency reasons, it does not actually consume the contents // of the file to make a hash of all the bytes. ยฏ\_(ใƒ„)_/ยฏ // Prefix the etag with "W/" to convert it into a weak etag. // See: https://tools.ietf.org/html/rfc7232#section-2.3 func calculateEtag(d os.FileInfo) string { mtime := d.ModTime().Unix() if mtime == 0 || mtime == 1 { return "" // not useful anyway; see issue #5548 } t := strconv.FormatInt(mtime, 36) s := strconv.FormatInt(d.Size(), 36) return `"` + t + s + `"` } func redirect(w http.ResponseWriter, r *http.Request, to string) error { for strings.HasPrefix(to, "//") { // prevent path-based open redirects to = strings.TrimPrefix(to, "/") } http.Redirect(w, r, to, http.StatusPermanentRedirect) return nil } // statusOverrideResponseWriter intercepts WriteHeader calls // to instead write the HTTP status code we want instead // of the one http.ServeContent will use by default (usually 200) type statusOverrideResponseWriter struct { http.ResponseWriter code int } // WriteHeader intercepts calls by the stdlib to WriteHeader // to instead write the HTTP status code we want. func (wr statusOverrideResponseWriter) WriteHeader(int) { wr.ResponseWriter.WriteHeader(wr.code) } // Unwrap returns the underlying ResponseWriter, necessary for // http.ResponseController to work correctly. func (wr statusOverrideResponseWriter) Unwrap() http.ResponseWriter { return wr.ResponseWriter } // 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 defaultIndexNames = []string{"index.html", "index.txt"} const ( minBackoff, maxBackoff = 2, 5 separator = string(filepath.Separator) ) // Interface guards var ( _ caddy.Provisioner = (*FileServer)(nil) _ caddyhttp.MiddlewareHandler = (*FileServer)(nil) _ fs.StatFS = (*osFS)(nil) _ fs.GlobFS = (*osFS)(nil) _ fs.ReadDirFS = (*osFS)(nil) _ fs.ReadFileFS = (*osFS)(nil) )
Go
caddy/modules/caddyhttp/fileserver/staticfiles_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 fileserver import ( "path/filepath" "runtime" "strings" "testing" ) func TestFileHidden(t *testing.T) { for i, tc := range []struct { inputHide []string inputPath string expect bool }{ { inputHide: nil, inputPath: "", expect: false, }, { inputHide: []string{".gitignore"}, inputPath: "/.gitignore", expect: true, }, { inputHide: []string{".git"}, inputPath: "/.gitignore", expect: false, }, { inputHide: []string{"/.git"}, inputPath: "/.gitignore", expect: false, }, { inputHide: []string{".git"}, inputPath: "/.git", expect: true, }, { inputHide: []string{".git"}, inputPath: "/.git/foo", expect: true, }, { inputHide: []string{".git"}, inputPath: "/foo/.git/bar", expect: true, }, { inputHide: []string{"/prefix"}, inputPath: "/prefix/foo", expect: true, }, { inputHide: []string{"/foo/*/bar"}, inputPath: "/foo/asdf/bar", expect: true, }, { inputHide: []string{"*.txt"}, inputPath: "/foo/bar.txt", expect: true, }, { inputHide: []string{"/foo/bar/*.txt"}, inputPath: "/foo/bar/baz.txt", expect: true, }, { inputHide: []string{"/foo/bar/*.txt"}, inputPath: "/foo/bar.txt", expect: false, }, { inputHide: []string{"/foo/bar/*.txt"}, inputPath: "/foo/bar/index.html", expect: false, }, { inputHide: []string{"/foo"}, inputPath: "/foo", expect: true, }, { inputHide: []string{"/foo"}, inputPath: "/foobar", expect: false, }, { inputHide: []string{"first", "second"}, inputPath: "/second", expect: true, }, } { if runtime.GOOS == "windows" { if strings.HasPrefix(tc.inputPath, "/") { tc.inputPath, _ = filepath.Abs(tc.inputPath) } tc.inputPath = filepath.FromSlash(tc.inputPath) for i := range tc.inputHide { if strings.HasPrefix(tc.inputHide[i], "/") { tc.inputHide[i], _ = filepath.Abs(tc.inputHide[i]) } tc.inputHide[i] = filepath.FromSlash(tc.inputHide[i]) } } actual := fileHidden(tc.inputPath, tc.inputHide) if actual != tc.expect { t.Errorf("Test %d: Does %v hide %s? Got %t but expected %t", i, tc.inputHide, tc.inputPath, actual, tc.expect) } } }