language
stringlengths
0
24
filename
stringlengths
9
214
code
stringlengths
99
9.93M
Go
caddy/modules/caddyhttp/headers/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 headers import ( "fmt" "net/http" "reflect" "strings" "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func init() { httpcaddyfile.RegisterDirective("header", parseCaddyfile) httpcaddyfile.RegisterDirective("request_header", parseReqHdrCaddyfile) } // parseCaddyfile sets up the handler for response headers from // Caddyfile tokens. Syntax: // // header [<matcher>] [[+|-|?|>]<field> [<value|regexp>] [<replacement>]] { // [+]<field> [<value|regexp> [<replacement>]] // ?<field> <default_value> // -<field> // ><field> // [defer] // } // // Either a block can be opened or a single header field can be configured // in the first line, but not both in the same directive. Header operations // are deferred to write-time if any headers are being deleted or if the // 'defer' subdirective is used. + appends a header value, - deletes a field, // ? conditionally sets a value only if the header field is not already set, // and > sets a field with defer enabled. func parseCaddyfile(h httpcaddyfile.Helper) ([]httpcaddyfile.ConfigValue, error) { if !h.Next() { return nil, h.ArgErr() } matcherSet, err := h.ExtractMatcherSet() if err != nil { return nil, err } makeHandler := func() Handler { return Handler{ Response: &RespHeaderOps{ HeaderOps: &HeaderOps{}, }, } } handler, handlerWithRequire := makeHandler(), makeHandler() for h.Next() { // first see if headers are in the initial line var hasArgs bool if h.NextArg() { hasArgs = true field := h.Val() var value, replacement string if h.NextArg() { value = h.Val() } if h.NextArg() { replacement = h.Val() } err := applyHeaderOp( handler.Response.HeaderOps, handler.Response, field, value, replacement, ) if err != nil { return nil, h.Err(err.Error()) } if len(handler.Response.HeaderOps.Delete) > 0 { handler.Response.Deferred = true } } // if not, they should be in a block for h.NextBlock(0) { field := h.Val() if field == "defer" { handler.Response.Deferred = true continue } if hasArgs { return nil, h.Err("cannot specify headers in both arguments and block") // because it would be weird } // sometimes it is habitual for users to suffix a field name with a colon, // as if they were writing a curl command or something; see // https://caddy.community/t/v2-reverse-proxy-please-add-cors-example-to-the-docs/7349/19 field = strings.TrimSuffix(field, ":") var value, replacement string if h.NextArg() { value = h.Val() } if h.NextArg() { replacement = h.Val() } handlerToUse := handler if strings.HasPrefix(field, "?") { handlerToUse = handlerWithRequire } err := applyHeaderOp( handlerToUse.Response.HeaderOps, handlerToUse.Response, field, value, replacement, ) if err != nil { return nil, h.Err(err.Error()) } } } var configValues []httpcaddyfile.ConfigValue if !reflect.DeepEqual(handler, makeHandler()) { configValues = append(configValues, h.NewRoute(matcherSet, handler)...) } if !reflect.DeepEqual(handlerWithRequire, makeHandler()) { configValues = append(configValues, h.NewRoute(matcherSet, handlerWithRequire)...) } return configValues, nil } // parseReqHdrCaddyfile sets up the handler for request headers // from Caddyfile tokens. Syntax: // // request_header [<matcher>] [[+|-]<field> [<value|regexp>] [<replacement>]] func parseReqHdrCaddyfile(h httpcaddyfile.Helper) ([]httpcaddyfile.ConfigValue, error) { if !h.Next() { return nil, h.ArgErr() } matcherSet, err := h.ExtractMatcherSet() if err != nil { return nil, err } configValues := []httpcaddyfile.ConfigValue{} for h.Next() { if !h.NextArg() { return nil, h.ArgErr() } field := h.Val() hdr := Handler{ Request: &HeaderOps{}, } // sometimes it is habitual for users to suffix a field name with a colon, // as if they were writing a curl command or something; see // https://caddy.community/t/v2-reverse-proxy-please-add-cors-example-to-the-docs/7349/19 field = strings.TrimSuffix(field, ":") var value, replacement string if h.NextArg() { value = h.Val() } if h.NextArg() { replacement = h.Val() if h.NextArg() { return nil, h.ArgErr() } } if hdr.Request == nil { hdr.Request = new(HeaderOps) } if err := CaddyfileHeaderOp(hdr.Request, field, value, replacement); err != nil { return nil, h.Err(err.Error()) } configValues = append(configValues, h.NewRoute(matcherSet, hdr)...) if h.NextArg() { return nil, h.ArgErr() } } return configValues, nil } // CaddyfileHeaderOp applies a new header operation according to // field, value, and replacement. The field can be prefixed with // "+" or "-" to specify adding or removing; otherwise, the value // will be set (overriding any previous value). If replacement is // non-empty, value will be treated as a regular expression which // will be used to search and then replacement will be used to // complete the substring replacement; in that case, any + or - // prefix to field will be ignored. func CaddyfileHeaderOp(ops *HeaderOps, field, value, replacement string) error { return applyHeaderOp(ops, nil, field, value, replacement) } func applyHeaderOp(ops *HeaderOps, respHeaderOps *RespHeaderOps, field, value, replacement string) error { switch { case strings.HasPrefix(field, "+"): // append if ops.Add == nil { ops.Add = make(http.Header) } ops.Add.Add(field[1:], value) case strings.HasPrefix(field, "-"): // delete ops.Delete = append(ops.Delete, field[1:]) if respHeaderOps != nil { respHeaderOps.Deferred = true } case strings.HasPrefix(field, "?"): // default (conditional on not existing) - response headers only if respHeaderOps == nil { return fmt.Errorf("%v: the default header modifier ('?') can only be used on response headers; for conditional manipulation of request headers, use matchers", field) } if respHeaderOps.Require == nil { respHeaderOps.Require = &caddyhttp.ResponseMatcher{ Headers: make(http.Header), } } field = strings.TrimPrefix(field, "?") respHeaderOps.Require.Headers[field] = nil if respHeaderOps.Set == nil { respHeaderOps.Set = make(http.Header) } respHeaderOps.Set.Set(field, value) case replacement != "": // replace // allow defer shortcut for replace syntax if strings.HasPrefix(field, ">") && respHeaderOps != nil { respHeaderOps.Deferred = true } if ops.Replace == nil { ops.Replace = make(map[string][]Replacement) } field = strings.TrimLeft(field, "+-?>") ops.Replace[field] = append( ops.Replace[field], Replacement{ SearchRegexp: value, Replace: replacement, }, ) case strings.HasPrefix(field, ">"): // set (overwrite) with defer if ops.Set == nil { ops.Set = make(http.Header) } ops.Set.Set(field[1:], value) if respHeaderOps != nil { respHeaderOps.Deferred = true } default: // set (overwrite) if ops.Set == nil { ops.Set = make(http.Header) } ops.Set.Set(field, value) } return nil }
Go
caddy/modules/caddyhttp/headers/headers.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 headers import ( "fmt" "net/http" "regexp" "strings" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func init() { caddy.RegisterModule(Handler{}) } // Handler is a middleware which modifies request and response headers. // // Changes to headers are applied immediately, except for the response // headers when Deferred is true or when Required is set. In those cases, // the changes are applied when the headers are written to the response. // Note that deferred changes do not take effect if an error occurs later // in the middleware chain. // // Properties in this module accept placeholders. // // Response header operations can be conditioned upon response status code // and/or other header values. type Handler struct { Request *HeaderOps `json:"request,omitempty"` Response *RespHeaderOps `json:"response,omitempty"` } // CaddyModule returns the Caddy module information. func (Handler) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.handlers.headers", New: func() caddy.Module { return new(Handler) }, } } // Provision sets up h's configuration. func (h *Handler) Provision(ctx caddy.Context) error { if h.Request != nil { err := h.Request.Provision(ctx) if err != nil { return err } } if h.Response != nil { err := h.Response.Provision(ctx) if err != nil { return err } } return nil } // Validate ensures h's configuration is valid. func (h Handler) Validate() error { if h.Request != nil { err := h.Request.validate() if err != nil { return err } } if h.Response != nil { err := h.Response.validate() if err != nil { return err } } return nil } func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) if h.Request != nil { h.Request.ApplyToRequest(r) } if h.Response != nil { if h.Response.Deferred || h.Response.Require != nil { w = &responseWriterWrapper{ ResponseWriterWrapper: &caddyhttp.ResponseWriterWrapper{ResponseWriter: w}, replacer: repl, require: h.Response.Require, headerOps: h.Response.HeaderOps, } } else { h.Response.ApplyTo(w.Header(), repl) } } return next.ServeHTTP(w, r) } // HeaderOps defines manipulations for HTTP headers. type HeaderOps struct { // Adds HTTP headers; does not replace any existing header fields. Add http.Header `json:"add,omitempty"` // Sets HTTP headers; replaces existing header fields. Set http.Header `json:"set,omitempty"` // Names of HTTP header fields to delete. Basic wildcards are supported: // // - Start with `*` for all field names with the given suffix; // - End with `*` for all field names with the given prefix; // - Start and end with `*` for all field names containing a substring. Delete []string `json:"delete,omitempty"` // Performs in-situ substring replacements of HTTP headers. // Keys are the field names on which to perform the associated replacements. // If the field name is `*`, the replacements are performed on all header fields. Replace map[string][]Replacement `json:"replace,omitempty"` } // Provision sets up the header operations. func (ops *HeaderOps) Provision(_ caddy.Context) error { for fieldName, replacements := range ops.Replace { for i, r := range replacements { if r.SearchRegexp != "" { re, err := regexp.Compile(r.SearchRegexp) if err != nil { return fmt.Errorf("replacement %d for header field '%s': %v", i, fieldName, err) } replacements[i].re = re } } } return nil } func (ops HeaderOps) validate() error { for fieldName, replacements := range ops.Replace { for _, r := range replacements { if r.Search != "" && r.SearchRegexp != "" { return fmt.Errorf("cannot specify both a substring search and a regular expression search for field '%s'", fieldName) } } } return nil } // Replacement describes a string replacement, // either a simple and fast substring search // or a slower but more powerful regex search. type Replacement struct { // The substring to search for. Search string `json:"search,omitempty"` // The regular expression to search with. SearchRegexp string `json:"search_regexp,omitempty"` // The string with which to replace matches. Replace string `json:"replace,omitempty"` re *regexp.Regexp } // RespHeaderOps defines manipulations for response headers. type RespHeaderOps struct { *HeaderOps // If set, header operations will be deferred until // they are written out and only performed if the // response matches these criteria. Require *caddyhttp.ResponseMatcher `json:"require,omitempty"` // If true, header operations will be deferred until // they are written out. Superceded if Require is set. // Usually you will need to set this to true if any // fields are being deleted. Deferred bool `json:"deferred,omitempty"` } // ApplyTo applies ops to hdr using repl. func (ops HeaderOps) ApplyTo(hdr http.Header, repl *caddy.Replacer) { // before manipulating headers in other ways, check if there // is configuration to delete all headers, and do that first // because if a header is to be added, we don't want to delete // it also for _, fieldName := range ops.Delete { fieldName = repl.ReplaceKnown(fieldName, "") if fieldName == "*" { for existingField := range hdr { delete(hdr, existingField) } } } // add for fieldName, vals := range ops.Add { fieldName = repl.ReplaceKnown(fieldName, "") for _, v := range vals { hdr.Add(fieldName, repl.ReplaceKnown(v, "")) } } // set for fieldName, vals := range ops.Set { fieldName = repl.ReplaceKnown(fieldName, "") var newVals []string for i := range vals { // append to new slice so we don't overwrite // the original values in ops.Set newVals = append(newVals, repl.ReplaceKnown(vals[i], "")) } hdr.Set(fieldName, strings.Join(newVals, ",")) } // delete for _, fieldName := range ops.Delete { fieldName = strings.ToLower(repl.ReplaceKnown(fieldName, "")) if fieldName == "*" { continue // handled above } switch { case strings.HasPrefix(fieldName, "*") && strings.HasSuffix(fieldName, "*"): for existingField := range hdr { if strings.Contains(strings.ToLower(existingField), fieldName[1:len(fieldName)-1]) { delete(hdr, existingField) } } case strings.HasPrefix(fieldName, "*"): for existingField := range hdr { if strings.HasSuffix(strings.ToLower(existingField), fieldName[1:]) { delete(hdr, existingField) } } case strings.HasSuffix(fieldName, "*"): for existingField := range hdr { if strings.HasPrefix(strings.ToLower(existingField), fieldName[:len(fieldName)-1]) { delete(hdr, existingField) } } default: hdr.Del(fieldName) } } // replace for fieldName, replacements := range ops.Replace { fieldName = http.CanonicalHeaderKey(repl.ReplaceKnown(fieldName, "")) // all fields... if fieldName == "*" { for _, r := range replacements { search := repl.ReplaceKnown(r.Search, "") replace := repl.ReplaceKnown(r.Replace, "") for fieldName, vals := range hdr { for i := range vals { if r.re != nil { hdr[fieldName][i] = r.re.ReplaceAllString(hdr[fieldName][i], replace) } else { hdr[fieldName][i] = strings.ReplaceAll(hdr[fieldName][i], search, replace) } } } } continue } // ...or only with the named field for _, r := range replacements { search := repl.ReplaceKnown(r.Search, "") replace := repl.ReplaceKnown(r.Replace, "") for hdrFieldName, vals := range hdr { // see issue #4330 for why we don't simply use hdr[fieldName] if http.CanonicalHeaderKey(hdrFieldName) != fieldName { continue } for i := range vals { if r.re != nil { hdr[hdrFieldName][i] = r.re.ReplaceAllString(hdr[hdrFieldName][i], replace) } else { hdr[hdrFieldName][i] = strings.ReplaceAll(hdr[hdrFieldName][i], search, replace) } } } } } } // ApplyToRequest applies ops to r, specially handling the Host // header which the standard library does not include with the // header map with all the others. This method mutates r.Host. func (ops HeaderOps) ApplyToRequest(r *http.Request) { repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) // capture the current Host header so we can // reset to it when we're done origHost, hadHost := r.Header["Host"] // append r.Host; this way, we know that our value // was last in the list, and if an Add operation // appended something else after it, that's probably // fine because it's weird to have multiple Host // headers anyway and presumably the one they added // is the one they wanted r.Header["Host"] = append(r.Header["Host"], r.Host) // apply header operations ops.ApplyTo(r.Header, repl) // retrieve the last Host value (likely the one we appended) if len(r.Header["Host"]) > 0 { r.Host = r.Header["Host"][len(r.Header["Host"])-1] } else { r.Host = "" } // reset the Host header slice if hadHost { r.Header["Host"] = origHost } else { delete(r.Header, "Host") } } // responseWriterWrapper defers response header // operations until WriteHeader is called. type responseWriterWrapper struct { *caddyhttp.ResponseWriterWrapper replacer *caddy.Replacer require *caddyhttp.ResponseMatcher headerOps *HeaderOps wroteHeader bool } func (rww *responseWriterWrapper) WriteHeader(status int) { if rww.wroteHeader { return } // 1xx responses aren't final; just informational if status < 100 || status > 199 { rww.wroteHeader = true } if rww.require == nil || rww.require.Match(status, rww.ResponseWriterWrapper.Header()) { if rww.headerOps != nil { rww.headerOps.ApplyTo(rww.ResponseWriterWrapper.Header(), rww.replacer) } } rww.ResponseWriterWrapper.WriteHeader(status) } func (rww *responseWriterWrapper) Write(d []byte) (int, error) { if !rww.wroteHeader { rww.WriteHeader(http.StatusOK) } return rww.ResponseWriterWrapper.Write(d) } // Interface guards var ( _ caddy.Provisioner = (*Handler)(nil) _ caddyhttp.MiddlewareHandler = (*Handler)(nil) _ http.ResponseWriter = (*responseWriterWrapper)(nil) )
Go
caddy/modules/caddyhttp/headers/headers_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 headers import ( "context" "fmt" "net/http" "net/http/httptest" "reflect" "testing" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func TestHandler(t *testing.T) { for i, tc := range []struct { handler Handler reqHeader http.Header respHeader http.Header respStatusCode int expectedReqHeader http.Header expectedRespHeader http.Header }{ { handler: Handler{ Request: &HeaderOps{ Add: http.Header{ "Expose-Secrets": []string{"always"}, }, }, }, reqHeader: http.Header{ "Expose-Secrets": []string{"i'm serious"}, }, expectedReqHeader: http.Header{ "Expose-Secrets": []string{"i'm serious", "always"}, }, }, { handler: Handler{ Request: &HeaderOps{ Set: http.Header{ "Who-Wins": []string{"batman"}, }, }, }, reqHeader: http.Header{ "Who-Wins": []string{"joker"}, }, expectedReqHeader: http.Header{ "Who-Wins": []string{"batman"}, }, }, { handler: Handler{ Request: &HeaderOps{ Delete: []string{"Kick-Me"}, }, }, reqHeader: http.Header{ "Kick-Me": []string{"if you can"}, "Keep-Me": []string{"i swear i'm innocent"}, }, expectedReqHeader: http.Header{ "Keep-Me": []string{"i swear i'm innocent"}, }, }, { handler: Handler{ Request: &HeaderOps{ Delete: []string{ "*-suffix", "prefix-*", "*_*", }, }, }, reqHeader: http.Header{ "Header-Suffix": []string{"lalala"}, "Prefix-Test": []string{"asdf"}, "Host_Header": []string{"silly django... sigh"}, // see issue #4830 "Keep-Me": []string{"foofoofoo"}, }, expectedReqHeader: http.Header{ "Keep-Me": []string{"foofoofoo"}, }, }, { handler: Handler{ Request: &HeaderOps{ Replace: map[string][]Replacement{ "Best-Server": { Replacement{ Search: "NGINX", Replace: "the Caddy web server", }, Replacement{ SearchRegexp: `Apache(\d+)`, Replace: "Caddy", }, }, }, }, }, reqHeader: http.Header{ "Best-Server": []string{"it's NGINX, undoubtedly", "I love Apache2"}, }, expectedReqHeader: http.Header{ "Best-Server": []string{"it's the Caddy web server, undoubtedly", "I love Caddy"}, }, }, { handler: Handler{ Response: &RespHeaderOps{ Require: &caddyhttp.ResponseMatcher{ Headers: http.Header{ "Cache-Control": nil, }, }, HeaderOps: &HeaderOps{ Add: http.Header{ "Cache-Control": []string{"no-cache"}, }, }, }, }, respHeader: http.Header{}, expectedRespHeader: http.Header{ "Cache-Control": []string{"no-cache"}, }, }, { handler: Handler{ Response: &RespHeaderOps{ Require: &caddyhttp.ResponseMatcher{ Headers: http.Header{ "Cache-Control": []string{"no-cache"}, }, }, HeaderOps: &HeaderOps{ Delete: []string{"Cache-Control"}, }, }, }, respHeader: http.Header{ "Cache-Control": []string{"no-cache"}, }, expectedRespHeader: http.Header{}, }, { handler: Handler{ Response: &RespHeaderOps{ Require: &caddyhttp.ResponseMatcher{ StatusCode: []int{5}, }, HeaderOps: &HeaderOps{ Add: http.Header{ "Fail-5xx": []string{"true"}, }, }, }, }, respStatusCode: 503, respHeader: http.Header{}, expectedRespHeader: http.Header{ "Fail-5xx": []string{"true"}, }, }, { handler: Handler{ Request: &HeaderOps{ Replace: map[string][]Replacement{ "Case-Insensitive": { Replacement{ Search: "issue4330", Replace: "issue #4330", }, }, }, }, }, reqHeader: http.Header{ "case-insensitive": []string{"issue4330"}, "Other-Header": []string{"issue4330"}, }, expectedReqHeader: http.Header{ "case-insensitive": []string{"issue #4330"}, "Other-Header": []string{"issue4330"}, }, }, } { rr := httptest.NewRecorder() req := &http.Request{Header: tc.reqHeader} repl := caddy.NewReplacer() ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl) req = req.WithContext(ctx) tc.handler.Provision(caddy.Context{}) next := nextHandler(func(w http.ResponseWriter, r *http.Request) error { for k, hdrs := range tc.respHeader { for _, v := range hdrs { w.Header().Add(k, v) } } status := 200 if tc.respStatusCode != 0 { status = tc.respStatusCode } w.WriteHeader(status) if tc.expectedReqHeader != nil && !reflect.DeepEqual(r.Header, tc.expectedReqHeader) { return fmt.Errorf("expected request header %v, got %v", tc.expectedReqHeader, r.Header) } return nil }) if err := tc.handler.ServeHTTP(rr, req, next); err != nil { t.Errorf("Test %d: %v", i, err) continue } actual := rr.Header() if tc.expectedRespHeader != nil && !reflect.DeepEqual(actual, tc.expectedRespHeader) { t.Errorf("Test %d: expected response header %v, got %v", i, tc.expectedRespHeader, actual) continue } } } type nextHandler func(http.ResponseWriter, *http.Request) error func (f nextHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) error { return f(w, r) }
Go
caddy/modules/caddyhttp/map/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 maphandler import ( "strings" "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func init() { httpcaddyfile.RegisterHandlerDirective("map", parseCaddyfile) } // parseCaddyfile sets up the map handler from Caddyfile tokens. Syntax: // // map [<matcher>] <source> <destinations...> { // [~]<input> <outputs...> // default <defaults...> // } // // If the input value is prefixed with a tilde (~), then the input will be parsed as a // regular expression. // // The Caddyfile adapter treats outputs that are a literal hyphen (-) as a null/nil // value. This is useful if you want to fall back to default for that particular output. // // The number of outputs for each mapping must not be more than the number of destinations. // However, for convenience, there may be fewer outputs than destinations and any missing // outputs will be filled in implicitly. func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) { var handler Handler for h.Next() { // source if !h.NextArg() { return nil, h.ArgErr() } handler.Source = h.Val() // destinations handler.Destinations = h.RemainingArgs() if len(handler.Destinations) == 0 { return nil, h.Err("missing destination argument(s)") } for _, dest := range handler.Destinations { if shorthand := httpcaddyfile.WasReplacedPlaceholderShorthand(dest); shorthand != "" { return nil, h.Errf("destination %s conflicts with a Caddyfile placeholder shorthand", shorthand) } } // mappings for h.NextBlock(0) { // defaults are a special case if h.Val() == "default" { if len(handler.Defaults) > 0 { return nil, h.Err("defaults already defined") } handler.Defaults = h.RemainingArgs() for len(handler.Defaults) < len(handler.Destinations) { handler.Defaults = append(handler.Defaults, "") } continue } // every line maps an input value to one or more outputs in := h.Val() var outs []any for h.NextArg() { val := h.ScalarVal() if val == "-" { outs = append(outs, nil) } else { outs = append(outs, val) } } // cannot have more outputs than destinations if len(outs) > len(handler.Destinations) { return nil, h.Err("too many outputs") } // for convenience, can have fewer outputs than destinations, but the // underlying handler won't accept that, so we fill in nil values for len(outs) < len(handler.Destinations) { outs = append(outs, nil) } // create the mapping mapping := Mapping{Outputs: outs} if strings.HasPrefix(in, "~") { mapping.InputRegexp = in[1:] } else { mapping.Input = in } handler.Mappings = append(handler.Mappings, mapping) } } return handler, nil }
Go
caddy/modules/caddyhttp/map/map.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 maphandler import ( "fmt" "net/http" "regexp" "strings" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func init() { caddy.RegisterModule(Handler{}) } // Handler implements a middleware that maps inputs to outputs. Specifically, it // compares a source value against the map inputs, and for one that matches, it // applies the output values to each destination. Destinations become placeholder // names. // // Mapped placeholders are not evaluated until they are used, so even for very // large mappings, this handler is quite efficient. type Handler struct { // Source is the placeholder from which to get the input value. Source string `json:"source,omitempty"` // Destinations are the names of placeholders in which to store the outputs. // Destination values should be wrapped in braces, for example, {my_placeholder}. Destinations []string `json:"destinations,omitempty"` // Mappings from source values (inputs) to destination values (outputs). // The first matching, non-nil mapping will be applied. Mappings []Mapping `json:"mappings,omitempty"` // If no mappings match or if the mapped output is null/nil, the associated // default output will be applied (optional). Defaults []string `json:"defaults,omitempty"` } // CaddyModule returns the Caddy module information. func (Handler) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.handlers.map", New: func() caddy.Module { return new(Handler) }, } } // Provision sets up h. func (h *Handler) Provision(_ caddy.Context) error { for j, dest := range h.Destinations { if strings.Count(dest, "{") != 1 || !strings.HasPrefix(dest, "{") { return fmt.Errorf("destination must be a placeholder and only a placeholder") } h.Destinations[j] = strings.Trim(dest, "{}") } for i, m := range h.Mappings { if m.InputRegexp == "" { continue } var err error h.Mappings[i].re, err = regexp.Compile(m.InputRegexp) if err != nil { return fmt.Errorf("compiling regexp for mapping %d: %v", i, err) } } // TODO: improve efficiency even further by using an actual map type // for the non-regexp mappings, OR sort them and do a binary search return nil } // Validate ensures that h is configured properly. func (h *Handler) Validate() error { nDest, nDef := len(h.Destinations), len(h.Defaults) if nDef > 0 && nDef != nDest { return fmt.Errorf("%d destinations != %d defaults", nDest, nDef) } seen := make(map[string]int) for i, m := range h.Mappings { // prevent confusing/ambiguous mappings if m.Input != "" && m.InputRegexp != "" { return fmt.Errorf("mapping %d has both input and input_regexp fields specified, which is confusing", i) } // prevent duplicate mappings input := m.Input if m.InputRegexp != "" { input = m.InputRegexp } if prev, ok := seen[input]; ok { return fmt.Errorf("mapping %d has a duplicate input '%s' previously used with mapping %d", i, input, prev) } seen[input] = i // ensure mappings have 1:1 output-to-destination correspondence nOut := len(m.Outputs) if nOut != nDest { return fmt.Errorf("mapping %d has %d outputs but there are %d destinations defined", i, nOut, nDest) } } return nil } func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) // defer work until a variable is actually evaluated by using replacer's Map callback repl.Map(func(key string) (any, bool) { // return early if the variable is not even a configured destination destIdx := h.destinationIndex(key) if destIdx < 0 { return nil, false } input := repl.ReplaceAll(h.Source, "") // find the first mapping matching the input and return // the requested destination/output value for _, m := range h.Mappings { output := m.Outputs[destIdx] if output == nil { continue } outputStr := caddy.ToString(output) // evaluate regular expression if configured if m.re != nil { var result []byte matches := m.re.FindStringSubmatchIndex(input) if matches == nil { continue } result = m.re.ExpandString(result, outputStr, input, matches) return string(result), true } // otherwise simple string comparison if input == m.Input { return repl.ReplaceAll(outputStr, ""), true } } // fall back to default if no match or if matched nil value if len(h.Defaults) > destIdx { return repl.ReplaceAll(h.Defaults[destIdx], ""), true } return nil, true }) return next.ServeHTTP(w, r) } // destinationIndex returns the positional index of the destination // is name is a known destination; otherwise it returns -1. func (h Handler) destinationIndex(name string) int { for i, dest := range h.Destinations { if dest == name { return i } } return -1 } // Mapping describes a mapping from input to outputs. type Mapping struct { // The input value to match. Must be distinct from other mappings. // Mutually exclusive to input_regexp. Input string `json:"input,omitempty"` // The input regular expression to match. Mutually exclusive to input. InputRegexp string `json:"input_regexp,omitempty"` // Upon a match with the input, each output is positionally correlated // with each destination of the parent handler. An output that is null // (nil) will be treated as if it was not mapped at all. Outputs []any `json:"outputs,omitempty"` re *regexp.Regexp } // Interface guards var ( _ caddy.Provisioner = (*Handler)(nil) _ caddy.Validator = (*Handler)(nil) _ caddyhttp.MiddlewareHandler = (*Handler)(nil) )
Go
caddy/modules/caddyhttp/map/map_test.go
package maphandler import ( "context" "net/http" "net/http/httptest" "reflect" "testing" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func TestHandler(t *testing.T) { for i, tc := range []struct { handler Handler reqURI string expect map[string]any }{ { reqURI: "/foo", handler: Handler{ Source: "{http.request.uri.path}", Destinations: []string{"{output}"}, Mappings: []Mapping{ { Input: "/foo", Outputs: []any{"FOO"}, }, }, }, expect: map[string]any{ "output": "FOO", }, }, { reqURI: "/abcdef", handler: Handler{ Source: "{http.request.uri.path}", Destinations: []string{"{output}"}, Mappings: []Mapping{ { InputRegexp: "(/abc)", Outputs: []any{"ABC"}, }, }, }, expect: map[string]any{ "output": "ABC", }, }, { reqURI: "/ABCxyzDEF", handler: Handler{ Source: "{http.request.uri.path}", Destinations: []string{"{output}"}, Mappings: []Mapping{ { InputRegexp: "(xyz)", Outputs: []any{"...${1}..."}, }, }, }, expect: map[string]any{ "output": "...xyz...", }, }, { // Test case from https://caddy.community/t/map-directive-and-regular-expressions/13866/14?u=matt reqURI: "/?s=0%27+AND+%28SELECT+0+FROM+%28SELECT+count%28%2A%29%2C+CONCAT%28%28SELECT+%40%40version%29%2C+0x23%2C+FLOOR%28RAND%280%29%2A2%29%29+AS+x+FROM+information_schema.columns+GROUP+BY+x%29+y%29+-+-+%27", handler: Handler{ Source: "{http.request.uri}", Destinations: []string{"{output}"}, Mappings: []Mapping{ { InputRegexp: "(?i)(\\^|`|<|>|%|\\\\|\\{|\\}|\\|)", Outputs: []any{"3"}, }, }, }, expect: map[string]any{ "output": "3", }, }, { reqURI: "/foo", handler: Handler{ Source: "{http.request.uri.path}", Destinations: []string{"{output}"}, Mappings: []Mapping{ { Input: "/foo", Outputs: []any{"{testvar}"}, }, }, }, expect: map[string]any{ "output": "testing", }, }, { reqURI: "/foo", handler: Handler{ Source: "{http.request.uri.path}", Destinations: []string{"{output}"}, Defaults: []string{"default"}, }, expect: map[string]any{ "output": "default", }, }, { reqURI: "/foo", handler: Handler{ Source: "{http.request.uri.path}", Destinations: []string{"{output}"}, Defaults: []string{"{testvar}"}, }, expect: map[string]any{ "output": "testing", }, }, } { if err := tc.handler.Provision(caddy.Context{}); err != nil { t.Fatalf("Test %d: Provisioning handler: %v", i, err) } req, err := http.NewRequest(http.MethodGet, tc.reqURI, nil) if err != nil { t.Fatalf("Test %d: Creating request: %v", i, err) } repl := caddyhttp.NewTestReplacer(req) repl.Set("testvar", "testing") ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl) req = req.WithContext(ctx) rr := httptest.NewRecorder() noop := caddyhttp.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) error { return nil }) if err := tc.handler.ServeHTTP(rr, req, noop); err != nil { t.Errorf("Test %d: Handler returned error: %v", i, err) continue } for key, expected := range tc.expect { actual, _ := repl.Get(key) if !reflect.DeepEqual(actual, expected) { t.Errorf("Test %d: Expected %#v but got %#v for {%s}", i, expected, actual, key) } } } }
Go
caddy/modules/caddyhttp/proxyprotocol/listenerwrapper.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package proxyprotocol import ( "fmt" "net" "time" "github.com/mastercactapus/proxyprotocol" "github.com/caddyserver/caddy/v2" ) // ListenerWrapper provides PROXY protocol support to Caddy by implementing // the caddy.ListenerWrapper interface. It must be loaded before the `tls` listener. // // Credit goes to https://github.com/mastercactapus/caddy2-proxyprotocol for having // initially implemented this as a plugin. type ListenerWrapper struct { // Timeout specifies an optional maximum time for // the PROXY header to be received. // If zero, timeout is disabled. Default is 5s. Timeout caddy.Duration `json:"timeout,omitempty"` // Allow is an optional list of CIDR ranges to // allow/require PROXY headers from. Allow []string `json:"allow,omitempty"` rules []proxyprotocol.Rule } // Provision sets up the listener wrapper. func (pp *ListenerWrapper) Provision(ctx caddy.Context) error { rules := make([]proxyprotocol.Rule, 0, len(pp.Allow)) for _, s := range pp.Allow { _, n, err := net.ParseCIDR(s) if err != nil { return fmt.Errorf("invalid subnet '%s': %w", s, err) } rules = append(rules, proxyprotocol.Rule{ Timeout: time.Duration(pp.Timeout), Subnet: n, }) } pp.rules = rules return nil } // WrapListener adds PROXY protocol support to the listener. func (pp *ListenerWrapper) WrapListener(l net.Listener) net.Listener { pl := proxyprotocol.NewListener(l, time.Duration(pp.Timeout)) pl.SetFilter(pp.rules) return pl }
Go
caddy/modules/caddyhttp/proxyprotocol/module.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package proxyprotocol import ( "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func init() { caddy.RegisterModule(ListenerWrapper{}) } func (ListenerWrapper) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "caddy.listeners.proxy_protocol", New: func() caddy.Module { return new(ListenerWrapper) }, } } // UnmarshalCaddyfile sets up the listener Listenerwrapper from Caddyfile tokens. Syntax: // // proxy_protocol { // timeout <duration> // allow <IPs...> // } func (w *ListenerWrapper) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { // No same-line options are supported if d.NextArg() { return d.ArgErr() } for d.NextBlock(0) { switch d.Val() { case "timeout": if !d.NextArg() { return d.ArgErr() } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("parsing proxy_protocol timeout duration: %v", err) } w.Timeout = caddy.Duration(dur) case "allow": w.Allow = append(w.Allow, d.RemainingArgs()...) default: return d.ArgErr() } } } return nil } // Interface guards var ( _ caddy.Provisioner = (*ListenerWrapper)(nil) _ caddy.Module = (*ListenerWrapper)(nil) _ caddy.ListenerWrapper = (*ListenerWrapper)(nil) _ caddyfile.Unmarshaler = (*ListenerWrapper)(nil) )
Go
caddy/modules/caddyhttp/push/caddyfile.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package push import ( "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" "github.com/caddyserver/caddy/v2/modules/caddyhttp/headers" ) func init() { httpcaddyfile.RegisterHandlerDirective("push", parseCaddyfile) } // parseCaddyfile sets up the push handler. Syntax: // // push [<matcher>] [<resource>] { // [GET|HEAD] <resource> // headers { // [+]<field> [<value|regexp> [<replacement>]] // -<field> // } // } // // A single resource can be specified inline without opening a // block for the most common/simple case. Or, a block can be // opened and multiple resources can be specified, one per // line, optionally preceded by the method. The headers // subdirective can be used to customize the headers that // are set on each (synthetic) push request, using the same // syntax as the 'header' directive for request headers. // Placeholders are accepted in resource and header field // name and value and replacement tokens. func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) { handler := new(Handler) for h.Next() { if h.NextArg() { handler.Resources = append(handler.Resources, Resource{Target: h.Val()}) } // optional block for outerNesting := h.Nesting(); h.NextBlock(outerNesting); { switch h.Val() { case "headers": if h.NextArg() { return nil, h.ArgErr() } for innerNesting := h.Nesting(); h.NextBlock(innerNesting); { var err error // include current token, which we treat as an argument here args := []string{h.Val()} args = append(args, h.RemainingArgs()...) if handler.Headers == nil { handler.Headers = new(HeaderConfig) } switch len(args) { case 1: err = headers.CaddyfileHeaderOp(&handler.Headers.HeaderOps, args[0], "", "") case 2: err = headers.CaddyfileHeaderOp(&handler.Headers.HeaderOps, args[0], args[1], "") case 3: err = headers.CaddyfileHeaderOp(&handler.Headers.HeaderOps, args[0], args[1], args[2]) default: return nil, h.ArgErr() } if err != nil { return nil, h.Err(err.Error()) } } case "GET", "HEAD": method := h.Val() if !h.NextArg() { return nil, h.ArgErr() } target := h.Val() handler.Resources = append(handler.Resources, Resource{ Method: method, Target: target, }) default: handler.Resources = append(handler.Resources, Resource{Target: h.Val()}) } } } return handler, nil }
Go
caddy/modules/caddyhttp/push/handler.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package push import ( "fmt" "net/http" "strings" "go.uber.org/zap" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" "github.com/caddyserver/caddy/v2/modules/caddyhttp/headers" ) func init() { caddy.RegisterModule(Handler{}) } // Handler is a middleware for HTTP/2 server push. Note that // HTTP/2 server push has been deprecated by some clients and // its use is discouraged unless you can accurately predict // which resources actually need to be pushed to the client; // it can be difficult to know what the client already has // cached. Pushing unnecessary resources results in worse // performance. Consider using HTTP 103 Early Hints instead. // // This handler supports pushing from Link headers; in other // words, if the eventual response has Link headers, this // handler will push the resources indicated by those headers, // even without specifying any resources in its config. type Handler struct { // The resources to push. Resources []Resource `json:"resources,omitempty"` // Headers to modify for the push requests. Headers *HeaderConfig `json:"headers,omitempty"` logger *zap.Logger } // CaddyModule returns the Caddy module information. func (Handler) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.handlers.push", New: func() caddy.Module { return new(Handler) }, } } // Provision sets up h. func (h *Handler) Provision(ctx caddy.Context) error { h.logger = ctx.Logger() if h.Headers != nil { err := h.Headers.Provision(ctx) if err != nil { return fmt.Errorf("provisioning header operations: %v", err) } } return nil } func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { pusher, ok := w.(http.Pusher) if !ok { return next.ServeHTTP(w, r) } // short-circuit recursive pushes if _, ok := r.Header[pushHeader]; ok { return next.ServeHTTP(w, r) } repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) server := r.Context().Value(caddyhttp.ServerCtxKey).(*caddyhttp.Server) shouldLogCredentials := server.Logs != nil && server.Logs.ShouldLogCredentials // create header for push requests hdr := h.initializePushHeaders(r, repl) // push first! for _, resource := range h.Resources { h.logger.Debug("pushing resource", zap.String("uri", r.RequestURI), zap.String("push_method", resource.Method), zap.String("push_target", resource.Target), zap.Object("push_headers", caddyhttp.LoggableHTTPHeader{ Header: hdr, ShouldLogCredentials: shouldLogCredentials, })) err := pusher.Push(repl.ReplaceAll(resource.Target, "."), &http.PushOptions{ Method: resource.Method, Header: hdr, }) if err != nil { // usually this means either that push is not // supported or concurrent streams are full break } } // wrap the response writer so that we can initiate push of any resources // described in Link header fields before the response is written lp := linkPusher{ ResponseWriterWrapper: &caddyhttp.ResponseWriterWrapper{ResponseWriter: w}, handler: h, pusher: pusher, header: hdr, request: r, } // serve only after pushing! if err := next.ServeHTTP(lp, r); err != nil { return err } return nil } func (h Handler) initializePushHeaders(r *http.Request, repl *caddy.Replacer) http.Header { hdr := make(http.Header) // prevent recursive pushes hdr.Set(pushHeader, "1") // set initial header fields; since exactly how headers should // be implemented for server push is not well-understood, we // are being conservative for now like httpd is: // https://httpd.apache.org/docs/2.4/en/howto/http2.html#push // we only copy some well-known, safe headers that are likely // crucial when requesting certain kinds of content for _, fieldName := range safeHeaders { if vals, ok := r.Header[fieldName]; ok { hdr[fieldName] = vals } } // user can customize the push request headers if h.Headers != nil { h.Headers.ApplyTo(hdr, repl) } return hdr } // servePreloadLinks parses Link headers from upstream and pushes // resources described by them. If a resource has the "nopush" // attribute or describes an external entity (meaning, the resource // URI includes a scheme), it will not be pushed. func (h Handler) servePreloadLinks(pusher http.Pusher, hdr http.Header, resources []string) { for _, resource := range resources { for _, resource := range parseLinkHeader(resource) { if _, ok := resource.params["nopush"]; ok { continue } if isRemoteResource(resource.uri) { continue } err := pusher.Push(resource.uri, &http.PushOptions{ Header: hdr, }) if err != nil { return } } } } // Resource represents a request for a resource to push. type Resource struct { // Method is the request method, which must be GET or HEAD. // Default is GET. Method string `json:"method,omitempty"` // Target is the path to the resource being pushed. Target string `json:"target,omitempty"` } // HeaderConfig configures headers for synthetic push requests. type HeaderConfig struct { headers.HeaderOps } // linkPusher is a http.ResponseWriter that intercepts // the WriteHeader() call to ensure that any resources // described by Link response headers get pushed before // the response is allowed to be written. type linkPusher struct { *caddyhttp.ResponseWriterWrapper handler Handler pusher http.Pusher header http.Header request *http.Request } func (lp linkPusher) WriteHeader(statusCode int) { if links, ok := lp.ResponseWriter.Header()["Link"]; ok { // only initiate these pushes if it hasn't been done yet if val := caddyhttp.GetVar(lp.request.Context(), pushedLink); val == nil { lp.handler.logger.Debug("pushing Link resources", zap.Strings("linked", links)) caddyhttp.SetVar(lp.request.Context(), pushedLink, true) lp.handler.servePreloadLinks(lp.pusher, lp.header, links) } } lp.ResponseWriter.WriteHeader(statusCode) } // isRemoteResource returns true if resource starts with // a scheme or is a protocol-relative URI. func isRemoteResource(resource string) bool { return strings.HasPrefix(resource, "//") || strings.HasPrefix(resource, "http://") || strings.HasPrefix(resource, "https://") } // safeHeaders is a list of header fields that are // safe to copy to push requests implicitly. It is // assumed that requests for certain kinds of content // would fail without these fields present. var safeHeaders = []string{ "Accept-Encoding", "Accept-Language", "Accept", "Cache-Control", "User-Agent", } // pushHeader is a header field that gets added to push requests // in order to avoid recursive/infinite pushes. const pushHeader = "Caddy-Push" // pushedLink is the key for the variable on the request // context that we use to remember whether we have already // pushed resources from Link headers yet; otherwise, if // multiple push handlers are invoked, it would repeat the // pushing of Link headers. const pushedLink = "http.handlers.push.pushed_link" // Interface guards var ( _ caddy.Provisioner = (*Handler)(nil) _ caddyhttp.MiddlewareHandler = (*Handler)(nil) _ http.ResponseWriter = (*linkPusher)(nil) _ http.Pusher = (*linkPusher)(nil) )
Go
caddy/modules/caddyhttp/push/link.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package push import ( "strings" ) // linkResource contains the results of a parsed Link header. type linkResource struct { uri string params map[string]string } // parseLinkHeader is responsible for parsing Link header // and returning list of found resources. // // Accepted formats are: // // Link: <resource>; as=script // Link: <resource>; as=script,<resource>; as=style // Link: <resource>;<resource2> // // where <resource> begins with a forward slash (/). func parseLinkHeader(header string) []linkResource { resources := []linkResource{} if header == "" { return resources } for _, link := range strings.Split(header, comma) { l := linkResource{params: make(map[string]string)} li, ri := strings.Index(link, "<"), strings.Index(link, ">") if li == -1 || ri == -1 { continue } l.uri = strings.TrimSpace(link[li+1 : ri]) for _, param := range strings.Split(strings.TrimSpace(link[ri+1:]), semicolon) { before, after, isCut := strings.Cut(strings.TrimSpace(param), equal) key := strings.TrimSpace(before) if key == "" { continue } if isCut { l.params[key] = strings.TrimSpace(after) } else { l.params[key] = key } } resources = append(resources, l) } return resources } const ( comma = "," semicolon = ";" equal = "=" )
Go
caddy/modules/caddyhttp/push/link_test.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package push import ( "reflect" "testing" ) func TestParseLinkHeader(t *testing.T) { testCases := []struct { header string expectedResources []linkResource }{ { header: "</resource>; as=script", expectedResources: []linkResource{{uri: "/resource", params: map[string]string{"as": "script"}}}, }, { header: "</resource>", expectedResources: []linkResource{{uri: "/resource", params: map[string]string{}}}, }, { header: "</resource>; nopush", expectedResources: []linkResource{{uri: "/resource", params: map[string]string{"nopush": "nopush"}}}, }, { header: "</resource>;nopush;rel=next", expectedResources: []linkResource{{uri: "/resource", params: map[string]string{"nopush": "nopush", "rel": "next"}}}, }, { header: "</resource>;nopush;rel=next,</resource2>;nopush", expectedResources: []linkResource{ {uri: "/resource", params: map[string]string{"nopush": "nopush", "rel": "next"}}, {uri: "/resource2", params: map[string]string{"nopush": "nopush"}}, }, }, { header: "</resource>,</resource2>", expectedResources: []linkResource{ {uri: "/resource", params: map[string]string{}}, {uri: "/resource2", params: map[string]string{}}, }, }, { header: "malformed", expectedResources: []linkResource{}, }, { header: "<malformed", expectedResources: []linkResource{}, }, { header: ",", expectedResources: []linkResource{}, }, { header: ";", expectedResources: []linkResource{}, }, { header: "</resource> ; ", expectedResources: []linkResource{{uri: "/resource", params: map[string]string{}}}, }, } for i, test := range testCases { actualResources := parseLinkHeader(test.header) if !reflect.DeepEqual(actualResources, test.expectedResources) { t.Errorf("Test %d (header: %s) - expected resources %v, got %v", i, test.header, test.expectedResources, actualResources) } } }
Go
caddy/modules/caddyhttp/requestbody/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 requestbody import ( "github.com/dustin/go-humanize" "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func init() { httpcaddyfile.RegisterHandlerDirective("request_body", parseCaddyfile) } func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) { rb := new(RequestBody) for h.Next() { // configuration should be in a block for h.NextBlock(0) { switch h.Val() { case "max_size": var sizeStr string if !h.AllArgs(&sizeStr) { return nil, h.ArgErr() } size, err := humanize.ParseBytes(sizeStr) if err != nil { return nil, h.Errf("parsing max_size: %v", err) } rb.MaxSize = int64(size) default: return nil, h.Errf("unrecognized servers option '%s'", h.Val()) } } } return rb, nil }
Go
caddy/modules/caddyhttp/requestbody/requestbody.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 requestbody import ( "io" "net/http" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func init() { caddy.RegisterModule(RequestBody{}) } // RequestBody is a middleware for manipulating the request body. type RequestBody struct { // The maximum number of bytes to allow reading from the body by a later handler. // If more bytes are read, an error with HTTP status 413 is returned. MaxSize int64 `json:"max_size,omitempty"` } // CaddyModule returns the Caddy module information. func (RequestBody) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.handlers.request_body", New: func() caddy.Module { return new(RequestBody) }, } } func (rb RequestBody) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { if r.Body == nil { return next.ServeHTTP(w, r) } if rb.MaxSize > 0 { r.Body = errorWrapper{http.MaxBytesReader(w, r.Body, rb.MaxSize)} } return next.ServeHTTP(w, r) } // errorWrapper wraps errors that are returned from Read() // so that they can be associated with a proper status code. type errorWrapper struct { io.ReadCloser } func (ew errorWrapper) Read(p []byte) (n int, err error) { n, err = ew.ReadCloser.Read(p) if err != nil && err.Error() == "http: request body too large" { err = caddyhttp.Error(http.StatusRequestEntityTooLarge, err) } return } // Interface guard var _ caddyhttp.MiddlewareHandler = (*RequestBody)(nil)
Go
caddy/modules/caddyhttp/reverseproxy/addresses.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package reverseproxy import ( "fmt" "net" "net/url" "strings" "github.com/caddyserver/caddy/v2" ) type parsedAddr struct { network, scheme, host, port string valid bool } func (p parsedAddr) dialAddr() string { if !p.valid { return "" } // for simplest possible config, we only need to include // the network portion if the user specified one if p.network != "" { return caddy.JoinNetworkAddress(p.network, p.host, p.port) } // if the host is a placeholder, then we don't want to join with an empty port, // because that would just append an extra ':' at the end of the address. if p.port == "" && strings.Contains(p.host, "{") { return p.host } return net.JoinHostPort(p.host, p.port) } func (p parsedAddr) rangedPort() bool { return strings.Contains(p.port, "-") } func (p parsedAddr) replaceablePort() bool { return strings.Contains(p.port, "{") && strings.Contains(p.port, "}") } func (p parsedAddr) isUnix() bool { return caddy.IsUnixNetwork(p.network) } // parseUpstreamDialAddress parses configuration inputs for // the dial address, including support for a scheme in front // as a shortcut for the port number, and a network type, // for example 'unix' to dial a unix socket. func parseUpstreamDialAddress(upstreamAddr string) (parsedAddr, error) { var network, scheme, host, port string if strings.Contains(upstreamAddr, "://") { // we get a parsing error if a placeholder is specified // so we return a more user-friendly error message instead // to explain what to do instead if strings.Contains(upstreamAddr, "{") { return parsedAddr{}, fmt.Errorf("due to parsing difficulties, placeholders are not allowed when an upstream address contains a scheme") } toURL, err := url.Parse(upstreamAddr) if err != nil { // if the error seems to be due to a port range, // try to replace the port range with a dummy // single port so that url.Parse() will succeed if strings.Contains(err.Error(), "invalid port") && strings.Contains(err.Error(), "-") { index := strings.LastIndex(upstreamAddr, ":") if index == -1 { return parsedAddr{}, fmt.Errorf("parsing upstream URL: %v", err) } portRange := upstreamAddr[index+1:] if strings.Count(portRange, "-") != 1 { return parsedAddr{}, fmt.Errorf("parsing upstream URL: parse \"%v\": port range invalid: %v", upstreamAddr, portRange) } toURL, err = url.Parse(strings.ReplaceAll(upstreamAddr, portRange, "0")) if err != nil { return parsedAddr{}, fmt.Errorf("parsing upstream URL: %v", err) } port = portRange } else { return parsedAddr{}, fmt.Errorf("parsing upstream URL: %v", err) } } if port == "" { port = toURL.Port() } // there is currently no way to perform a URL rewrite between choosing // a backend and proxying to it, so we cannot allow extra components // in backend URLs if toURL.Path != "" || toURL.RawQuery != "" || toURL.Fragment != "" { return parsedAddr{}, fmt.Errorf("for now, URLs for proxy upstreams only support scheme, host, and port components") } // ensure the port and scheme aren't in conflict if toURL.Scheme == "http" && port == "443" { return parsedAddr{}, fmt.Errorf("upstream address has conflicting scheme (http://) and port (:443, the HTTPS port)") } if toURL.Scheme == "https" && port == "80" { return parsedAddr{}, fmt.Errorf("upstream address has conflicting scheme (https://) and port (:80, the HTTP port)") } if toURL.Scheme == "h2c" && port == "443" { return parsedAddr{}, fmt.Errorf("upstream address has conflicting scheme (h2c://) and port (:443, the HTTPS port)") } // if port is missing, attempt to infer from scheme if port == "" { switch toURL.Scheme { case "", "http", "h2c": port = "80" case "https": port = "443" } } scheme, host = toURL.Scheme, toURL.Hostname() } else { var err error network, host, port, err = caddy.SplitNetworkAddress(upstreamAddr) if err != nil { host = upstreamAddr } // we can assume a port if only a hostname is specified, but use of a // placeholder without a port likely means a port will be filled in if port == "" && !strings.Contains(host, "{") && !caddy.IsUnixNetwork(network) { port = "80" } } // special case network to support both unix and h2c at the same time if network == "unix+h2c" { network = "unix" scheme = "h2c" } return parsedAddr{network, scheme, host, port, true}, nil }
Go
caddy/modules/caddyhttp/reverseproxy/addresses_test.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package reverseproxy import "testing" func TestParseUpstreamDialAddress(t *testing.T) { for i, tc := range []struct { input string expectHostPort string expectScheme string expectErr bool }{ { input: "foo", expectHostPort: "foo:80", }, { input: "foo:1234", expectHostPort: "foo:1234", }, { input: "127.0.0.1", expectHostPort: "127.0.0.1:80", }, { input: "127.0.0.1:1234", expectHostPort: "127.0.0.1:1234", }, { input: "[::1]", expectHostPort: "[::1]:80", }, { input: "[::1]:1234", expectHostPort: "[::1]:1234", }, { input: "{foo}", expectHostPort: "{foo}", }, { input: "{foo}:80", expectHostPort: "{foo}:80", }, { input: "{foo}:{bar}", expectHostPort: "{foo}:{bar}", }, { input: "http://foo", expectHostPort: "foo:80", expectScheme: "http", }, { input: "http://foo:1234", expectHostPort: "foo:1234", expectScheme: "http", }, { input: "http://127.0.0.1", expectHostPort: "127.0.0.1:80", expectScheme: "http", }, { input: "http://127.0.0.1:1234", expectHostPort: "127.0.0.1:1234", expectScheme: "http", }, { input: "http://[::1]", expectHostPort: "[::1]:80", expectScheme: "http", }, { input: "http://[::1]:80", expectHostPort: "[::1]:80", expectScheme: "http", }, { input: "https://foo", expectHostPort: "foo:443", expectScheme: "https", }, { input: "https://foo:1234", expectHostPort: "foo:1234", expectScheme: "https", }, { input: "https://127.0.0.1", expectHostPort: "127.0.0.1:443", expectScheme: "https", }, { input: "https://127.0.0.1:1234", expectHostPort: "127.0.0.1:1234", expectScheme: "https", }, { input: "https://[::1]", expectHostPort: "[::1]:443", expectScheme: "https", }, { input: "https://[::1]:1234", expectHostPort: "[::1]:1234", expectScheme: "https", }, { input: "h2c://foo", expectHostPort: "foo:80", expectScheme: "h2c", }, { input: "h2c://foo:1234", expectHostPort: "foo:1234", expectScheme: "h2c", }, { input: "h2c://127.0.0.1", expectHostPort: "127.0.0.1:80", expectScheme: "h2c", }, { input: "h2c://127.0.0.1:1234", expectHostPort: "127.0.0.1:1234", expectScheme: "h2c", }, { input: "h2c://[::1]", expectHostPort: "[::1]:80", expectScheme: "h2c", }, { input: "h2c://[::1]:1234", expectHostPort: "[::1]:1234", expectScheme: "h2c", }, { input: "localhost:1001-1009", expectHostPort: "localhost:1001-1009", }, { input: "{host}:1001-1009", expectHostPort: "{host}:1001-1009", }, { input: "http://localhost:1001-1009", expectHostPort: "localhost:1001-1009", expectScheme: "http", }, { input: "https://localhost:1001-1009", expectHostPort: "localhost:1001-1009", expectScheme: "https", }, { input: "unix//var/php.sock", expectHostPort: "unix//var/php.sock", }, { input: "unix+h2c//var/grpc.sock", expectHostPort: "unix//var/grpc.sock", expectScheme: "h2c", }, { input: "unix/{foo}", expectHostPort: "unix/{foo}", }, { input: "unix+h2c/{foo}", expectHostPort: "unix/{foo}", expectScheme: "h2c", }, { input: "unix//foo/{foo}/bar", expectHostPort: "unix//foo/{foo}/bar", }, { input: "unix+h2c//foo/{foo}/bar", expectHostPort: "unix//foo/{foo}/bar", expectScheme: "h2c", }, { input: "http://{foo}", expectErr: true, }, { input: "http:// :80", expectErr: true, }, { input: "http://localhost/path", expectErr: true, }, { input: "http://localhost?key=value", expectErr: true, }, { input: "http://localhost#fragment", expectErr: true, }, { input: "http://localhost:8001-8002-8003", expectErr: true, }, { input: "http://localhost:8001-8002/foo:bar", expectErr: true, }, { input: "http://localhost:8001-8002/foo:1", expectErr: true, }, { input: "http://localhost:8001-8002/foo:1-2", expectErr: true, }, { input: "http://localhost:8001-8002#foo:1", expectErr: true, }, { input: "http://foo:443", expectErr: true, }, { input: "https://foo:80", expectErr: true, }, { input: "h2c://foo:443", expectErr: true, }, { input: `unix/c:\absolute\path`, expectHostPort: `unix/c:\absolute\path`, }, { input: `unix+h2c/c:\absolute\path`, expectHostPort: `unix/c:\absolute\path`, expectScheme: "h2c", }, { input: "unix/c:/absolute/path", expectHostPort: "unix/c:/absolute/path", }, { input: "unix+h2c/c:/absolute/path", expectHostPort: "unix/c:/absolute/path", expectScheme: "h2c", }, } { actualAddr, err := parseUpstreamDialAddress(tc.input) if tc.expectErr && err == nil { t.Errorf("Test %d: Expected error but got %v", i, err) } if !tc.expectErr && err != nil { t.Errorf("Test %d: Expected no error but got %v", i, err) } if actualAddr.dialAddr() != tc.expectHostPort { t.Errorf("Test %d: input %s: Expected host and port '%s' but got '%s'", i, tc.input, tc.expectHostPort, actualAddr.dialAddr()) } if actualAddr.scheme != tc.expectScheme { t.Errorf("Test %d: Expected scheme '%s' but got '%s'", i, tc.expectScheme, actualAddr.scheme) } } }
Go
caddy/modules/caddyhttp/reverseproxy/admin.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package reverseproxy import ( "encoding/json" "fmt" "net/http" "github.com/caddyserver/caddy/v2" ) func init() { caddy.RegisterModule(adminUpstreams{}) } // adminUpstreams is a module that provides the // /reverse_proxy/upstreams endpoint for the Caddy admin // API. This allows for checking the health of configured // reverse proxy upstreams in the pool. type adminUpstreams struct{} // upstreamResults holds the status of a particular upstream type upstreamStatus struct { Address string `json:"address"` NumRequests int `json:"num_requests"` Fails int `json:"fails"` } // CaddyModule returns the Caddy module information. func (adminUpstreams) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "admin.api.reverse_proxy", New: func() caddy.Module { return new(adminUpstreams) }, } } // Routes returns a route for the /reverse_proxy/upstreams endpoint. func (al adminUpstreams) Routes() []caddy.AdminRoute { return []caddy.AdminRoute{ { Pattern: "/reverse_proxy/upstreams", Handler: caddy.AdminHandlerFunc(al.handleUpstreams), }, } } // handleUpstreams reports the status of the reverse proxy // upstream pool. func (adminUpstreams) handleUpstreams(w http.ResponseWriter, r *http.Request) error { if r.Method != http.MethodGet { return caddy.APIError{ HTTPStatus: http.StatusMethodNotAllowed, Err: fmt.Errorf("method not allowed"), } } // Prep for a JSON response w.Header().Set("Content-Type", "application/json") enc := json.NewEncoder(w) // Collect the results to respond with results := []upstreamStatus{} // Iterate over the upstream pool (needs to be fast) var rangeErr error hosts.Range(func(key, val any) bool { address, ok := key.(string) if !ok { rangeErr = caddy.APIError{ HTTPStatus: http.StatusInternalServerError, Err: fmt.Errorf("could not type assert upstream address"), } return false } upstream, ok := val.(*Host) if !ok { rangeErr = caddy.APIError{ HTTPStatus: http.StatusInternalServerError, Err: fmt.Errorf("could not type assert upstream struct"), } return false } results = append(results, upstreamStatus{ Address: address, NumRequests: upstream.NumRequests(), Fails: upstream.Fails(), }) return true }) // If an error happened during the range, return it if rangeErr != nil { return rangeErr } err := enc.Encode(results) if err != nil { return caddy.APIError{ HTTPStatus: http.StatusInternalServerError, Err: err, } } return nil }
Go
caddy/modules/caddyhttp/reverseproxy/ascii.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Most of the code in this file was initially borrowed from the Go // standard library and modified; It had this copyright notice: // Copyright 2021 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Original source, copied because the package was marked internal: // https://github.com/golang/go/blob/5c489514bc5e61ad9b5b07bd7d8ec65d66a0512a/src/net/http/internal/ascii/print.go package reverseproxy // asciiEqualFold is strings.EqualFold, ASCII only. It reports whether s and t // are equal, ASCII-case-insensitively. func asciiEqualFold(s, t string) bool { if len(s) != len(t) { return false } for i := 0; i < len(s); i++ { if asciiLower(s[i]) != asciiLower(t[i]) { return false } } return true } // asciiLower returns the ASCII lowercase version of b. func asciiLower(b byte) byte { if 'A' <= b && b <= 'Z' { return b + ('a' - 'A') } return b } // asciiIsPrint returns whether s is ASCII and printable according to // https://tools.ietf.org/html/rfc20#section-4.2. func asciiIsPrint(s string) bool { for i := 0; i < len(s); i++ { if s[i] < ' ' || s[i] > '~' { return false } } return true }
Go
caddy/modules/caddyhttp/reverseproxy/ascii_test.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Most of the code in this file was initially borrowed from the Go // standard library and modified; It had this copyright notice: // Copyright 2021 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Original source, copied because the package was marked internal: // https://github.com/golang/go/blob/5c489514bc5e61ad9b5b07bd7d8ec65d66a0512a/src/net/http/internal/ascii/print_test.go package reverseproxy import "testing" func TestEqualFold(t *testing.T) { var tests = []struct { name string a, b string want bool }{ { name: "empty", want: true, }, { name: "simple match", a: "CHUNKED", b: "chunked", want: true, }, { name: "same string", a: "chunked", b: "chunked", want: true, }, { name: "Unicode Kelvin symbol", a: "chunKed", // This "K" is 'KELVIN SIGN' (\u212A) b: "chunked", want: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := asciiEqualFold(tt.a, tt.b); got != tt.want { t.Errorf("AsciiEqualFold(%q,%q): got %v want %v", tt.a, tt.b, got, tt.want) } }) } } func TestIsPrint(t *testing.T) { var tests = []struct { name string in string want bool }{ { name: "empty", want: true, }, { name: "ASCII low", in: "This is a space: ' '", want: true, }, { name: "ASCII high", in: "This is a tilde: '~'", want: true, }, { name: "ASCII low non-print", in: "This is a unit separator: \x1F", want: false, }, { name: "Ascii high non-print", in: "This is a Delete: \x7F", want: false, }, { name: "Unicode letter", in: "Today it's 280K outside: it's freezing!", // This "K" is 'KELVIN SIGN' (\u212A) want: false, }, { name: "Unicode emoji", in: "Gophers like 🧀", want: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := asciiIsPrint(tt.in); got != tt.want { t.Errorf("IsASCIIPrint(%q): got %v want %v", tt.in, got, tt.want) } }) } }
Go
caddy/modules/caddyhttp/reverseproxy/caddyfile.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package reverseproxy import ( "fmt" "net/http" "reflect" "strconv" "strings" "github.com/dustin/go-humanize" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" "github.com/caddyserver/caddy/v2/modules/caddyhttp/headers" "github.com/caddyserver/caddy/v2/modules/caddyhttp/rewrite" ) func init() { httpcaddyfile.RegisterHandlerDirective("reverse_proxy", parseCaddyfile) httpcaddyfile.RegisterHandlerDirective("copy_response", parseCopyResponseCaddyfile) httpcaddyfile.RegisterHandlerDirective("copy_response_headers", parseCopyResponseHeadersCaddyfile) } func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) { rp := new(Handler) err := rp.UnmarshalCaddyfile(h.Dispenser) if err != nil { return nil, err } err = rp.FinalizeUnmarshalCaddyfile(h) if err != nil { return nil, err } return rp, nil } // UnmarshalCaddyfile sets up the handler from Caddyfile tokens. Syntax: // // reverse_proxy [<matcher>] [<upstreams...>] { // # backends // to <upstreams...> // dynamic <name> [...] // // # load balancing // lb_policy <name> [<options...>] // lb_retries <retries> // lb_try_duration <duration> // lb_try_interval <interval> // lb_retry_match <request-matcher> // // # active health checking // health_uri <uri> // health_port <port> // health_interval <interval> // health_timeout <duration> // health_status <status> // health_body <regexp> // health_headers { // <field> [<values...>] // } // // # passive health checking // fail_duration <duration> // max_fails <num> // unhealthy_status <status> // unhealthy_latency <duration> // unhealthy_request_count <num> // // # streaming // flush_interval <duration> // buffer_requests // buffer_responses // max_buffer_size <size> // stream_timeout <duration> // stream_close_delay <duration> // // # request manipulation // trusted_proxies [private_ranges] <ranges...> // header_up [+|-]<field> [<value|regexp> [<replacement>]] // header_down [+|-]<field> [<value|regexp> [<replacement>]] // method <method> // rewrite <to> // // # round trip // transport <name> { // ... // } // // # optionally intercept responses from upstream // @name { // status <code...> // header <field> [<value>] // } // replace_status [<matcher>] <status_code> // handle_response [<matcher>] { // <directives...> // // # special directives only available in handle_response // copy_response [<matcher>] [<status>] { // status <status> // } // copy_response_headers [<matcher>] { // include <fields...> // exclude <fields...> // } // } // } // // Proxy upstream addresses should be network dial addresses such // as `host:port`, or a URL such as `scheme://host:port`. Scheme // and port may be inferred from other parts of the address/URL; if // either are missing, defaults to HTTP. // // The FinalizeUnmarshalCaddyfile method should be called after this // to finalize parsing of "handle_response" blocks, if possible. func (h *Handler) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { // currently, all backends must use the same scheme/protocol (the // underlying JSON does not yet support per-backend transports) var commonScheme string // we'll wait until the very end of parsing before // validating and encoding the transport var transport http.RoundTripper var transportModuleName string // collect the response matchers defined as subdirectives // prefixed with "@" for use with "handle_response" blocks h.responseMatchers = make(map[string]caddyhttp.ResponseMatcher) // appendUpstream creates an upstream for address and adds // it to the list. appendUpstream := func(address string) error { pa, err := parseUpstreamDialAddress(address) if err != nil { return d.WrapErr(err) } // the underlying JSON does not yet support different // transports (protocols or schemes) to each backend, // so we remember the last one we see and compare them switch pa.scheme { case "wss": return d.Errf("the scheme wss:// is only supported in browsers; use https:// instead") case "ws": return d.Errf("the scheme ws:// is only supported in browsers; use http:// instead") case "https", "http", "h2c", "": // Do nothing or handle the valid schemes default: return d.Errf("unsupported URL scheme %s://", pa.scheme) } if commonScheme != "" && pa.scheme != commonScheme { return d.Errf("for now, all proxy upstreams must use the same scheme (transport protocol); expecting '%s://' but got '%s://'", commonScheme, pa.scheme) } commonScheme = pa.scheme // if the port of upstream address contains a placeholder, only wrap it with the `Upstream` struct, // delaying actual resolution of the address until request time. if pa.replaceablePort() { h.Upstreams = append(h.Upstreams, &Upstream{Dial: pa.dialAddr()}) return nil } parsedAddr, err := caddy.ParseNetworkAddress(pa.dialAddr()) if err != nil { return d.WrapErr(err) } if pa.isUnix() || !pa.rangedPort() { // unix networks don't have ports h.Upstreams = append(h.Upstreams, &Upstream{ Dial: pa.dialAddr(), }) } else { // expand a port range into multiple upstreams for i := parsedAddr.StartPort; i <= parsedAddr.EndPort; i++ { h.Upstreams = append(h.Upstreams, &Upstream{ Dial: caddy.JoinNetworkAddress("", parsedAddr.Host, fmt.Sprint(i)), }) } } return nil } d.Next() // consume the directive name for _, up := range d.RemainingArgs() { err := appendUpstream(up) if err != nil { return fmt.Errorf("parsing upstream '%s': %w", up, err) } } for nesting := d.Nesting(); d.NextBlock(nesting); { // if the subdirective has an "@" prefix then we // parse it as a response matcher for use with "handle_response" if strings.HasPrefix(d.Val(), matcherPrefix) { err := caddyhttp.ParseNamedResponseMatcher(d.NewFromNextSegment(), h.responseMatchers) if err != nil { return err } continue } switch d.Val() { case "to": args := d.RemainingArgs() if len(args) == 0 { return d.ArgErr() } for _, up := range args { err := appendUpstream(up) if err != nil { return fmt.Errorf("parsing upstream '%s': %w", up, err) } } case "dynamic": if !d.NextArg() { return d.ArgErr() } if h.DynamicUpstreams != nil { return d.Err("dynamic upstreams already specified") } dynModule := d.Val() modID := "http.reverse_proxy.upstreams." + dynModule unm, err := caddyfile.UnmarshalModule(d, modID) if err != nil { return err } source, ok := unm.(UpstreamSource) if !ok { return d.Errf("module %s (%T) is not an UpstreamSource", modID, unm) } h.DynamicUpstreamsRaw = caddyconfig.JSONModuleObject(source, "source", dynModule, nil) case "lb_policy": if !d.NextArg() { return d.ArgErr() } if h.LoadBalancing != nil && h.LoadBalancing.SelectionPolicyRaw != nil { return d.Err("load balancing selection policy already specified") } name := d.Val() modID := "http.reverse_proxy.selection_policies." + name unm, err := caddyfile.UnmarshalModule(d, modID) if err != nil { return err } sel, ok := unm.(Selector) if !ok { return d.Errf("module %s (%T) is not a reverseproxy.Selector", modID, unm) } if h.LoadBalancing == nil { h.LoadBalancing = new(LoadBalancing) } h.LoadBalancing.SelectionPolicyRaw = caddyconfig.JSONModuleObject(sel, "policy", name, nil) case "lb_retries": if !d.NextArg() { return d.ArgErr() } tries, err := strconv.Atoi(d.Val()) if err != nil { return d.Errf("bad lb_retries number '%s': %v", d.Val(), err) } if h.LoadBalancing == nil { h.LoadBalancing = new(LoadBalancing) } h.LoadBalancing.Retries = tries case "lb_try_duration": if !d.NextArg() { return d.ArgErr() } if h.LoadBalancing == nil { h.LoadBalancing = new(LoadBalancing) } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("bad duration value %s: %v", d.Val(), err) } h.LoadBalancing.TryDuration = caddy.Duration(dur) case "lb_try_interval": if !d.NextArg() { return d.ArgErr() } if h.LoadBalancing == nil { h.LoadBalancing = new(LoadBalancing) } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("bad interval value '%s': %v", d.Val(), err) } h.LoadBalancing.TryInterval = caddy.Duration(dur) case "lb_retry_match": matcherSet, err := caddyhttp.ParseCaddyfileNestedMatcherSet(d) if err != nil { return d.Errf("failed to parse lb_retry_match: %v", err) } if h.LoadBalancing == nil { h.LoadBalancing = new(LoadBalancing) } h.LoadBalancing.RetryMatchRaw = append(h.LoadBalancing.RetryMatchRaw, matcherSet) case "health_uri": if !d.NextArg() { return d.ArgErr() } if h.HealthChecks == nil { h.HealthChecks = new(HealthChecks) } if h.HealthChecks.Active == nil { h.HealthChecks.Active = new(ActiveHealthChecks) } h.HealthChecks.Active.URI = d.Val() case "health_path": if !d.NextArg() { return d.ArgErr() } if h.HealthChecks == nil { h.HealthChecks = new(HealthChecks) } if h.HealthChecks.Active == nil { h.HealthChecks.Active = new(ActiveHealthChecks) } h.HealthChecks.Active.Path = d.Val() caddy.Log().Named("config.adapter.caddyfile").Warn("the 'health_path' subdirective is deprecated, please use 'health_uri' instead!") case "health_port": if !d.NextArg() { return d.ArgErr() } if h.HealthChecks == nil { h.HealthChecks = new(HealthChecks) } if h.HealthChecks.Active == nil { h.HealthChecks.Active = new(ActiveHealthChecks) } portNum, err := strconv.Atoi(d.Val()) if err != nil { return d.Errf("bad port number '%s': %v", d.Val(), err) } h.HealthChecks.Active.Port = portNum case "health_headers": healthHeaders := make(http.Header) for nesting := d.Nesting(); d.NextBlock(nesting); { key := d.Val() values := d.RemainingArgs() if len(values) == 0 { values = append(values, "") } healthHeaders[key] = values } if h.HealthChecks == nil { h.HealthChecks = new(HealthChecks) } if h.HealthChecks.Active == nil { h.HealthChecks.Active = new(ActiveHealthChecks) } h.HealthChecks.Active.Headers = healthHeaders case "health_interval": if !d.NextArg() { return d.ArgErr() } if h.HealthChecks == nil { h.HealthChecks = new(HealthChecks) } if h.HealthChecks.Active == nil { h.HealthChecks.Active = new(ActiveHealthChecks) } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("bad interval value %s: %v", d.Val(), err) } h.HealthChecks.Active.Interval = caddy.Duration(dur) case "health_timeout": if !d.NextArg() { return d.ArgErr() } if h.HealthChecks == nil { h.HealthChecks = new(HealthChecks) } if h.HealthChecks.Active == nil { h.HealthChecks.Active = new(ActiveHealthChecks) } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("bad timeout value %s: %v", d.Val(), err) } h.HealthChecks.Active.Timeout = caddy.Duration(dur) case "health_status": if !d.NextArg() { return d.ArgErr() } if h.HealthChecks == nil { h.HealthChecks = new(HealthChecks) } if h.HealthChecks.Active == nil { h.HealthChecks.Active = new(ActiveHealthChecks) } val := d.Val() if len(val) == 3 && strings.HasSuffix(val, "xx") { val = val[:1] } statusNum, err := strconv.Atoi(val) if err != nil { return d.Errf("bad status value '%s': %v", d.Val(), err) } h.HealthChecks.Active.ExpectStatus = statusNum case "health_body": if !d.NextArg() { return d.ArgErr() } if h.HealthChecks == nil { h.HealthChecks = new(HealthChecks) } if h.HealthChecks.Active == nil { h.HealthChecks.Active = new(ActiveHealthChecks) } h.HealthChecks.Active.ExpectBody = d.Val() case "max_fails": if !d.NextArg() { return d.ArgErr() } if h.HealthChecks == nil { h.HealthChecks = new(HealthChecks) } if h.HealthChecks.Passive == nil { h.HealthChecks.Passive = new(PassiveHealthChecks) } maxFails, err := strconv.Atoi(d.Val()) if err != nil { return d.Errf("invalid maximum fail count '%s': %v", d.Val(), err) } h.HealthChecks.Passive.MaxFails = maxFails case "fail_duration": if !d.NextArg() { return d.ArgErr() } if h.HealthChecks == nil { h.HealthChecks = new(HealthChecks) } if h.HealthChecks.Passive == nil { h.HealthChecks.Passive = new(PassiveHealthChecks) } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("bad duration value '%s': %v", d.Val(), err) } h.HealthChecks.Passive.FailDuration = caddy.Duration(dur) case "unhealthy_request_count": if !d.NextArg() { return d.ArgErr() } if h.HealthChecks == nil { h.HealthChecks = new(HealthChecks) } if h.HealthChecks.Passive == nil { h.HealthChecks.Passive = new(PassiveHealthChecks) } maxConns, err := strconv.Atoi(d.Val()) if err != nil { return d.Errf("invalid maximum connection count '%s': %v", d.Val(), err) } h.HealthChecks.Passive.UnhealthyRequestCount = maxConns case "unhealthy_status": args := d.RemainingArgs() if len(args) == 0 { return d.ArgErr() } if h.HealthChecks == nil { h.HealthChecks = new(HealthChecks) } if h.HealthChecks.Passive == nil { h.HealthChecks.Passive = new(PassiveHealthChecks) } for _, arg := range args { if len(arg) == 3 && strings.HasSuffix(arg, "xx") { arg = arg[:1] } statusNum, err := strconv.Atoi(arg) if err != nil { return d.Errf("bad status value '%s': %v", d.Val(), err) } h.HealthChecks.Passive.UnhealthyStatus = append(h.HealthChecks.Passive.UnhealthyStatus, statusNum) } case "unhealthy_latency": if !d.NextArg() { return d.ArgErr() } if h.HealthChecks == nil { h.HealthChecks = new(HealthChecks) } if h.HealthChecks.Passive == nil { h.HealthChecks.Passive = new(PassiveHealthChecks) } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("bad duration value '%s': %v", d.Val(), err) } h.HealthChecks.Passive.UnhealthyLatency = caddy.Duration(dur) case "flush_interval": if !d.NextArg() { return d.ArgErr() } if fi, err := strconv.Atoi(d.Val()); err == nil { h.FlushInterval = caddy.Duration(fi) } else { dur, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("bad duration value '%s': %v", d.Val(), err) } h.FlushInterval = caddy.Duration(dur) } case "request_buffers", "response_buffers": subdir := d.Val() if !d.NextArg() { return d.ArgErr() } size, err := humanize.ParseBytes(d.Val()) if err != nil { return d.Errf("invalid byte size '%s': %v", d.Val(), err) } if d.NextArg() { return d.ArgErr() } if subdir == "request_buffers" { h.RequestBuffers = int64(size) } else if subdir == "response_buffers" { h.ResponseBuffers = int64(size) } // TODO: These three properties are deprecated; remove them sometime after v2.6.4 case "buffer_requests": // TODO: deprecated if d.NextArg() { return d.ArgErr() } caddy.Log().Named("config.adapter.caddyfile").Warn("DEPRECATED: buffer_requests: use request_buffers instead (with a maximum buffer size)") h.DeprecatedBufferRequests = true case "buffer_responses": // TODO: deprecated if d.NextArg() { return d.ArgErr() } caddy.Log().Named("config.adapter.caddyfile").Warn("DEPRECATED: buffer_responses: use response_buffers instead (with a maximum buffer size)") h.DeprecatedBufferResponses = true case "max_buffer_size": // TODO: deprecated if !d.NextArg() { return d.ArgErr() } size, err := humanize.ParseBytes(d.Val()) if err != nil { return d.Errf("invalid byte size '%s': %v", d.Val(), err) } if d.NextArg() { return d.ArgErr() } caddy.Log().Named("config.adapter.caddyfile").Warn("DEPRECATED: max_buffer_size: use request_buffers and/or response_buffers instead (with maximum buffer sizes)") h.DeprecatedMaxBufferSize = int64(size) case "stream_timeout": if !d.NextArg() { return d.ArgErr() } if fi, err := strconv.Atoi(d.Val()); err == nil { h.StreamTimeout = caddy.Duration(fi) } else { dur, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("bad duration value '%s': %v", d.Val(), err) } h.StreamTimeout = caddy.Duration(dur) } case "stream_close_delay": if !d.NextArg() { return d.ArgErr() } if fi, err := strconv.Atoi(d.Val()); err == nil { h.StreamCloseDelay = caddy.Duration(fi) } else { dur, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("bad duration value '%s': %v", d.Val(), err) } h.StreamCloseDelay = caddy.Duration(dur) } case "trusted_proxies": for d.NextArg() { if d.Val() == "private_ranges" { h.TrustedProxies = append(h.TrustedProxies, caddyhttp.PrivateRangesCIDR()...) continue } h.TrustedProxies = append(h.TrustedProxies, d.Val()) } case "header_up": var err error if h.Headers == nil { h.Headers = new(headers.Handler) } if h.Headers.Request == nil { h.Headers.Request = new(headers.HeaderOps) } args := d.RemainingArgs() switch len(args) { case 1: err = headers.CaddyfileHeaderOp(h.Headers.Request, args[0], "", "") case 2: // some lint checks, I guess if strings.EqualFold(args[0], "host") && (args[1] == "{hostport}" || args[1] == "{http.request.hostport}") { caddy.Log().Named("caddyfile").Warn("Unnecessary header_up Host: the reverse proxy's default behavior is to pass headers to the upstream") } if strings.EqualFold(args[0], "x-forwarded-for") && (args[1] == "{remote}" || args[1] == "{http.request.remote}" || args[1] == "{remote_host}" || args[1] == "{http.request.remote.host}") { caddy.Log().Named("caddyfile").Warn("Unnecessary header_up X-Forwarded-For: the reverse proxy's default behavior is to pass headers to the upstream") } if strings.EqualFold(args[0], "x-forwarded-proto") && (args[1] == "{scheme}" || args[1] == "{http.request.scheme}") { caddy.Log().Named("caddyfile").Warn("Unnecessary header_up X-Forwarded-Proto: the reverse proxy's default behavior is to pass headers to the upstream") } if strings.EqualFold(args[0], "x-forwarded-host") && (args[1] == "{host}" || args[1] == "{http.request.host}" || args[1] == "{hostport}" || args[1] == "{http.request.hostport}") { caddy.Log().Named("caddyfile").Warn("Unnecessary header_up X-Forwarded-Host: the reverse proxy's default behavior is to pass headers to the upstream") } err = headers.CaddyfileHeaderOp(h.Headers.Request, args[0], args[1], "") case 3: err = headers.CaddyfileHeaderOp(h.Headers.Request, args[0], args[1], args[2]) default: return d.ArgErr() } if err != nil { return d.Err(err.Error()) } case "header_down": var err error if h.Headers == nil { h.Headers = new(headers.Handler) } if h.Headers.Response == nil { h.Headers.Response = &headers.RespHeaderOps{ HeaderOps: new(headers.HeaderOps), } } args := d.RemainingArgs() switch len(args) { case 1: err = headers.CaddyfileHeaderOp(h.Headers.Response.HeaderOps, args[0], "", "") case 2: err = headers.CaddyfileHeaderOp(h.Headers.Response.HeaderOps, args[0], args[1], "") case 3: err = headers.CaddyfileHeaderOp(h.Headers.Response.HeaderOps, args[0], args[1], args[2]) default: return d.ArgErr() } if err != nil { return d.Err(err.Error()) } case "method": if !d.NextArg() { return d.ArgErr() } if h.Rewrite == nil { h.Rewrite = &rewrite.Rewrite{} } h.Rewrite.Method = d.Val() if d.NextArg() { return d.ArgErr() } case "rewrite": if !d.NextArg() { return d.ArgErr() } if h.Rewrite == nil { h.Rewrite = &rewrite.Rewrite{} } h.Rewrite.URI = d.Val() if d.NextArg() { return d.ArgErr() } case "transport": if !d.NextArg() { return d.ArgErr() } if h.TransportRaw != nil { return d.Err("transport already specified") } transportModuleName = d.Val() modID := "http.reverse_proxy.transport." + transportModuleName unm, err := caddyfile.UnmarshalModule(d, modID) if err != nil { return err } rt, ok := unm.(http.RoundTripper) if !ok { return d.Errf("module %s (%T) is not a RoundTripper", modID, unm) } transport = rt case "handle_response": // delegate the parsing of handle_response to the caller, // since we need the httpcaddyfile.Helper to parse subroutes. // See h.FinalizeUnmarshalCaddyfile h.handleResponseSegments = append(h.handleResponseSegments, d.NewFromNextSegment()) case "replace_status": args := d.RemainingArgs() if len(args) != 1 && len(args) != 2 { return d.Errf("must have one or two arguments: an optional response matcher, and a status code") } responseHandler := caddyhttp.ResponseHandler{} if len(args) == 2 { if !strings.HasPrefix(args[0], matcherPrefix) { return d.Errf("must use a named response matcher, starting with '@'") } foundMatcher, ok := h.responseMatchers[args[0]] if !ok { return d.Errf("no named response matcher defined with name '%s'", args[0][1:]) } responseHandler.Match = &foundMatcher responseHandler.StatusCode = caddyhttp.WeakString(args[1]) } else if len(args) == 1 { responseHandler.StatusCode = caddyhttp.WeakString(args[0]) } // make sure there's no block, cause it doesn't make sense if d.NextBlock(1) { return d.Errf("cannot define routes for 'replace_status', use 'handle_response' instead.") } h.HandleResponse = append( h.HandleResponse, responseHandler, ) default: return d.Errf("unrecognized subdirective %s", d.Val()) } } // if the scheme inferred from the backends' addresses is // HTTPS, we will need a non-nil transport to enable TLS, // or if H2C, to set the transport versions. if (commonScheme == "https" || commonScheme == "h2c") && transport == nil { transport = new(HTTPTransport) transportModuleName = "http" } // verify transport configuration, and finally encode it if transport != nil { if te, ok := transport.(TLSTransport); ok { if commonScheme == "https" && !te.TLSEnabled() { err := te.EnableTLS(new(TLSConfig)) if err != nil { return err } } if commonScheme == "http" && te.TLSEnabled() { return d.Errf("upstream address scheme is HTTP but transport is configured for HTTP+TLS (HTTPS)") } if te, ok := transport.(*HTTPTransport); ok && commonScheme == "h2c" { te.Versions = []string{"h2c", "2"} } } else if commonScheme == "https" { return d.Errf("upstreams are configured for HTTPS but transport module does not support TLS: %T", transport) } // no need to encode empty default transport if !reflect.DeepEqual(transport, new(HTTPTransport)) { h.TransportRaw = caddyconfig.JSONModuleObject(transport, "protocol", transportModuleName, nil) } } return nil } // FinalizeUnmarshalCaddyfile finalizes the Caddyfile parsing which // requires having an httpcaddyfile.Helper to function, to parse subroutes. func (h *Handler) FinalizeUnmarshalCaddyfile(helper httpcaddyfile.Helper) error { for _, d := range h.handleResponseSegments { // consume the "handle_response" token d.Next() args := d.RemainingArgs() // TODO: Remove this check at some point in the future if len(args) == 2 { return d.Errf("configuring 'handle_response' for status code replacement is no longer supported. Use 'replace_status' instead.") } if len(args) > 1 { return d.Errf("too many arguments for 'handle_response': %s", args) } var matcher *caddyhttp.ResponseMatcher if len(args) == 1 { // the first arg should always be a matcher. if !strings.HasPrefix(args[0], matcherPrefix) { return d.Errf("must use a named response matcher, starting with '@'") } foundMatcher, ok := h.responseMatchers[args[0]] if !ok { return d.Errf("no named response matcher defined with name '%s'", args[0][1:]) } matcher = &foundMatcher } // parse the block as routes handler, err := httpcaddyfile.ParseSegmentAsSubroute(helper.WithDispenser(d.NewFromNextSegment())) if err != nil { return err } subroute, ok := handler.(*caddyhttp.Subroute) if !ok { return helper.Errf("segment was not parsed as a subroute") } h.HandleResponse = append( h.HandleResponse, caddyhttp.ResponseHandler{ Match: matcher, Routes: subroute.Routes, }, ) } // move the handle_response entries without a matcher to the end. // we can't use sort.SliceStable because it will reorder the rest of the // entries which may be undesirable because we don't have a good // heuristic to use for sorting. withoutMatchers := []caddyhttp.ResponseHandler{} withMatchers := []caddyhttp.ResponseHandler{} for _, hr := range h.HandleResponse { if hr.Match == nil { withoutMatchers = append(withoutMatchers, hr) } else { withMatchers = append(withMatchers, hr) } } h.HandleResponse = append(withMatchers, withoutMatchers...) // clean up the bits we only needed for adapting h.handleResponseSegments = nil h.responseMatchers = nil return nil } // UnmarshalCaddyfile deserializes Caddyfile tokens into h. // // transport http { // read_buffer <size> // write_buffer <size> // max_response_header <size> // dial_timeout <duration> // dial_fallback_delay <duration> // response_header_timeout <duration> // expect_continue_timeout <duration> // resolvers <resolvers...> // tls // tls_client_auth <automate_name> | <cert_file> <key_file> // tls_insecure_skip_verify // tls_timeout <duration> // tls_trusted_ca_certs <cert_files...> // tls_server_name <sni> // tls_renegotiation <level> // tls_except_ports <ports...> // keepalive [off|<duration>] // keepalive_interval <interval> // keepalive_idle_conns <max_count> // keepalive_idle_conns_per_host <count> // versions <versions...> // compression off // max_conns_per_host <count> // max_idle_conns_per_host <count> // } func (h *HTTPTransport) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { for d.NextBlock(0) { switch d.Val() { case "read_buffer": if !d.NextArg() { return d.ArgErr() } size, err := humanize.ParseBytes(d.Val()) if err != nil { return d.Errf("invalid read buffer size '%s': %v", d.Val(), err) } h.ReadBufferSize = int(size) case "write_buffer": if !d.NextArg() { return d.ArgErr() } size, err := humanize.ParseBytes(d.Val()) if err != nil { return d.Errf("invalid write buffer size '%s': %v", d.Val(), err) } h.WriteBufferSize = int(size) case "read_timeout": if !d.NextArg() { return d.ArgErr() } timeout, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("invalid read timeout duration '%s': %v", d.Val(), err) } h.ReadTimeout = caddy.Duration(timeout) case "write_timeout": if !d.NextArg() { return d.ArgErr() } timeout, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("invalid write timeout duration '%s': %v", d.Val(), err) } h.WriteTimeout = caddy.Duration(timeout) case "max_response_header": if !d.NextArg() { return d.ArgErr() } size, err := humanize.ParseBytes(d.Val()) if err != nil { return d.Errf("invalid max response header size '%s': %v", d.Val(), err) } h.MaxResponseHeaderSize = int64(size) case "proxy_protocol": if !d.NextArg() { return d.ArgErr() } switch proxyProtocol := d.Val(); proxyProtocol { case "v1", "v2": h.ProxyProtocol = proxyProtocol default: return d.Errf("invalid proxy protocol version '%s'", proxyProtocol) } case "dial_timeout": if !d.NextArg() { return d.ArgErr() } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("bad timeout value '%s': %v", d.Val(), err) } h.DialTimeout = caddy.Duration(dur) case "dial_fallback_delay": if !d.NextArg() { return d.ArgErr() } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("bad fallback delay value '%s': %v", d.Val(), err) } h.FallbackDelay = caddy.Duration(dur) case "response_header_timeout": if !d.NextArg() { return d.ArgErr() } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("bad timeout value '%s': %v", d.Val(), err) } h.ResponseHeaderTimeout = caddy.Duration(dur) case "expect_continue_timeout": if !d.NextArg() { return d.ArgErr() } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("bad timeout value '%s': %v", d.Val(), err) } h.ExpectContinueTimeout = caddy.Duration(dur) case "resolvers": if h.Resolver == nil { h.Resolver = new(UpstreamResolver) } h.Resolver.Addresses = d.RemainingArgs() if len(h.Resolver.Addresses) == 0 { return d.Errf("must specify at least one resolver address") } case "tls": if h.TLS == nil { h.TLS = new(TLSConfig) } case "tls_client_auth": if h.TLS == nil { h.TLS = new(TLSConfig) } args := d.RemainingArgs() switch len(args) { case 1: h.TLS.ClientCertificateAutomate = args[0] case 2: h.TLS.ClientCertificateFile = args[0] h.TLS.ClientCertificateKeyFile = args[1] default: return d.ArgErr() } case "tls_insecure_skip_verify": if d.NextArg() { return d.ArgErr() } if h.TLS == nil { h.TLS = new(TLSConfig) } h.TLS.InsecureSkipVerify = true case "tls_timeout": if !d.NextArg() { return d.ArgErr() } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("bad timeout value '%s': %v", d.Val(), err) } if h.TLS == nil { h.TLS = new(TLSConfig) } h.TLS.HandshakeTimeout = caddy.Duration(dur) case "tls_trusted_ca_certs": args := d.RemainingArgs() if len(args) == 0 { return d.ArgErr() } if h.TLS == nil { h.TLS = new(TLSConfig) } h.TLS.RootCAPEMFiles = args case "tls_server_name": if !d.NextArg() { return d.ArgErr() } if h.TLS == nil { h.TLS = new(TLSConfig) } h.TLS.ServerName = d.Val() case "tls_renegotiation": if h.TLS == nil { h.TLS = new(TLSConfig) } if !d.NextArg() { return d.ArgErr() } switch renegotiation := d.Val(); renegotiation { case "never", "once", "freely": h.TLS.Renegotiation = renegotiation default: return d.ArgErr() } case "tls_except_ports": if h.TLS == nil { h.TLS = new(TLSConfig) } h.TLS.ExceptPorts = d.RemainingArgs() if len(h.TLS.ExceptPorts) == 0 { return d.ArgErr() } case "keepalive": if !d.NextArg() { return d.ArgErr() } if h.KeepAlive == nil { h.KeepAlive = new(KeepAlive) } if d.Val() == "off" { var disable bool h.KeepAlive.Enabled = &disable break } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("bad duration value '%s': %v", d.Val(), err) } h.KeepAlive.IdleConnTimeout = caddy.Duration(dur) case "keepalive_interval": if !d.NextArg() { return d.ArgErr() } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("bad interval value '%s': %v", d.Val(), err) } if h.KeepAlive == nil { h.KeepAlive = new(KeepAlive) } h.KeepAlive.ProbeInterval = caddy.Duration(dur) case "keepalive_idle_conns": if !d.NextArg() { return d.ArgErr() } num, err := strconv.Atoi(d.Val()) if err != nil { return d.Errf("bad integer value '%s': %v", d.Val(), err) } if h.KeepAlive == nil { h.KeepAlive = new(KeepAlive) } h.KeepAlive.MaxIdleConns = num case "keepalive_idle_conns_per_host": if !d.NextArg() { return d.ArgErr() } num, err := strconv.Atoi(d.Val()) if err != nil { return d.Errf("bad integer value '%s': %v", d.Val(), err) } if h.KeepAlive == nil { h.KeepAlive = new(KeepAlive) } h.KeepAlive.MaxIdleConnsPerHost = num case "versions": h.Versions = d.RemainingArgs() if len(h.Versions) == 0 { return d.ArgErr() } case "compression": if d.NextArg() { if d.Val() == "off" { var disable bool h.Compression = &disable } } case "max_conns_per_host": if !d.NextArg() { return d.ArgErr() } num, err := strconv.Atoi(d.Val()) if err != nil { return d.Errf("bad integer value '%s': %v", d.Val(), err) } h.MaxConnsPerHost = num default: return d.Errf("unrecognized subdirective %s", d.Val()) } } } return nil } func parseCopyResponseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) { crh := new(CopyResponseHandler) err := crh.UnmarshalCaddyfile(h.Dispenser) if err != nil { return nil, err } return crh, nil } // UnmarshalCaddyfile sets up the handler from Caddyfile tokens. Syntax: // // copy_response [<matcher>] [<status>] { // status <status> // } func (h *CopyResponseHandler) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { args := d.RemainingArgs() if len(args) == 1 { if num, err := strconv.Atoi(args[0]); err == nil && num > 0 { h.StatusCode = caddyhttp.WeakString(args[0]) break } } for d.NextBlock(0) { switch d.Val() { case "status": if !d.NextArg() { return d.ArgErr() } h.StatusCode = caddyhttp.WeakString(d.Val()) default: return d.Errf("unrecognized subdirective '%s'", d.Val()) } } } return nil } func parseCopyResponseHeadersCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) { crh := new(CopyResponseHeadersHandler) err := crh.UnmarshalCaddyfile(h.Dispenser) if err != nil { return nil, err } return crh, nil } // UnmarshalCaddyfile sets up the handler from Caddyfile tokens. Syntax: // // copy_response_headers [<matcher>] { // include <fields...> // exclude <fields...> // } func (h *CopyResponseHeadersHandler) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { args := d.RemainingArgs() if len(args) > 0 { return d.ArgErr() } for d.NextBlock(0) { switch d.Val() { case "include": h.Include = append(h.Include, d.RemainingArgs()...) case "exclude": h.Exclude = append(h.Exclude, d.RemainingArgs()...) default: return d.Errf("unrecognized subdirective '%s'", d.Val()) } } } return nil } // UnmarshalCaddyfile deserializes Caddyfile tokens into h. // // dynamic srv [<name>] { // service <service> // proto <proto> // name <name> // refresh <interval> // resolvers <resolvers...> // dial_timeout <timeout> // dial_fallback_delay <timeout> // } func (u *SRVUpstreams) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { args := d.RemainingArgs() if len(args) > 1 { return d.ArgErr() } if len(args) > 0 { u.Name = args[0] } for d.NextBlock(0) { switch d.Val() { case "service": if !d.NextArg() { return d.ArgErr() } if u.Service != "" { return d.Errf("srv service has already been specified") } u.Service = d.Val() case "proto": if !d.NextArg() { return d.ArgErr() } if u.Proto != "" { return d.Errf("srv proto has already been specified") } u.Proto = d.Val() case "name": if !d.NextArg() { return d.ArgErr() } if u.Name != "" { return d.Errf("srv name has already been specified") } u.Name = d.Val() case "refresh": if !d.NextArg() { return d.ArgErr() } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("parsing refresh interval duration: %v", err) } u.Refresh = caddy.Duration(dur) case "resolvers": if u.Resolver == nil { u.Resolver = new(UpstreamResolver) } u.Resolver.Addresses = d.RemainingArgs() if len(u.Resolver.Addresses) == 0 { return d.Errf("must specify at least one resolver address") } case "dial_timeout": if !d.NextArg() { return d.ArgErr() } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("bad timeout value '%s': %v", d.Val(), err) } u.DialTimeout = caddy.Duration(dur) case "dial_fallback_delay": if !d.NextArg() { return d.ArgErr() } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("bad delay value '%s': %v", d.Val(), err) } u.FallbackDelay = caddy.Duration(dur) default: return d.Errf("unrecognized srv option '%s'", d.Val()) } } } return nil } // UnmarshalCaddyfile deserializes Caddyfile tokens into h. // // dynamic a [<name> <port] { // name <name> // port <port> // refresh <interval> // resolvers <resolvers...> // dial_timeout <timeout> // dial_fallback_delay <timeout> // versions ipv4|ipv6 // } func (u *AUpstreams) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { args := d.RemainingArgs() if len(args) > 2 { return d.ArgErr() } if len(args) > 0 { u.Name = args[0] if len(args) == 2 { u.Port = args[1] } } for d.NextBlock(0) { switch d.Val() { case "name": if !d.NextArg() { return d.ArgErr() } if u.Name != "" { return d.Errf("a name has already been specified") } u.Name = d.Val() case "port": if !d.NextArg() { return d.ArgErr() } if u.Port != "" { return d.Errf("a port has already been specified") } u.Port = d.Val() case "refresh": if !d.NextArg() { return d.ArgErr() } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("parsing refresh interval duration: %v", err) } u.Refresh = caddy.Duration(dur) case "resolvers": if u.Resolver == nil { u.Resolver = new(UpstreamResolver) } u.Resolver.Addresses = d.RemainingArgs() if len(u.Resolver.Addresses) == 0 { return d.Errf("must specify at least one resolver address") } case "dial_timeout": if !d.NextArg() { return d.ArgErr() } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("bad timeout value '%s': %v", d.Val(), err) } u.DialTimeout = caddy.Duration(dur) case "dial_fallback_delay": if !d.NextArg() { return d.ArgErr() } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("bad delay value '%s': %v", d.Val(), err) } u.FallbackDelay = caddy.Duration(dur) case "versions": args := d.RemainingArgs() if len(args) == 0 { return d.Errf("must specify at least one version") } if u.Versions == nil { u.Versions = &IPVersions{} } trueBool := true for _, arg := range args { switch arg { case "ipv4": u.Versions.IPv4 = &trueBool case "ipv6": u.Versions.IPv6 = &trueBool default: return d.Errf("unsupported version: '%s'", arg) } } default: return d.Errf("unrecognized a option '%s'", d.Val()) } } } return nil } // UnmarshalCaddyfile deserializes Caddyfile tokens into h. // // dynamic multi { // <source> [...] // } func (u *MultiUpstreams) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { if d.NextArg() { return d.ArgErr() } for nesting := d.Nesting(); d.NextBlock(nesting); { dynModule := d.Val() modID := "http.reverse_proxy.upstreams." + dynModule unm, err := caddyfile.UnmarshalModule(d, modID) if err != nil { return err } source, ok := unm.(UpstreamSource) if !ok { return d.Errf("module %s (%T) is not an UpstreamSource", modID, unm) } u.SourcesRaw = append(u.SourcesRaw, caddyconfig.JSONModuleObject(source, "source", dynModule, nil)) } } return nil } const matcherPrefix = "@" // Interface guards var ( _ caddyfile.Unmarshaler = (*Handler)(nil) _ caddyfile.Unmarshaler = (*HTTPTransport)(nil) _ caddyfile.Unmarshaler = (*SRVUpstreams)(nil) _ caddyfile.Unmarshaler = (*AUpstreams)(nil) _ caddyfile.Unmarshaler = (*MultiUpstreams)(nil) )
Go
caddy/modules/caddyhttp/reverseproxy/command.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package reverseproxy import ( "encoding/json" "fmt" "net/http" "strconv" "strings" "github.com/spf13/cobra" "go.uber.org/zap" caddycmd "github.com/caddyserver/caddy/v2/cmd" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" "github.com/caddyserver/caddy/v2/modules/caddyhttp/headers" "github.com/caddyserver/caddy/v2/modules/caddytls" ) func init() { caddycmd.RegisterCommand(caddycmd.Command{ Name: "reverse-proxy", Usage: `[--from <addr>] [--to <addr>] [--change-host-header] [--insecure] [--internal-certs] [--disable-redirects] [--header-up "Field: value"] [--header-down "Field: value"] [--access-log] [--debug]`, Short: "A quick and production-ready reverse proxy", Long: ` A simple but production-ready reverse proxy. Useful for quick deployments, demos, and development. Simply shuttles HTTP(S) traffic from the --from address to the --to address. Multiple --to addresses may be specified by repeating the flag. Unless otherwise specified in the addresses, the --from address will be assumed to be HTTPS if a hostname is given, and the --to address will be assumed to be HTTP. If the --from address has a host or IP, Caddy will attempt to serve the proxy over HTTPS with a certificate (unless overridden by the HTTP scheme or port). If serving HTTPS: --disable-redirects can be used to avoid binding to the HTTP port. --internal-certs can be used to force issuance certs using the internal CA instead of attempting to issue a public certificate. For proxying: --header-up can be used to set a request header to send to the upstream. --header-down can be used to set a response header to send back to the client. --change-host-header sets the Host header on the request to the address of the upstream, instead of defaulting to the incoming Host header. This is a shortcut for --header-up "Host: {http.reverse_proxy.upstream.hostport}". --insecure disables TLS verification with the upstream. WARNING: THIS DISABLES SECURITY BY NOT VERIFYING THE UPSTREAM'S CERTIFICATE. `, CobraFunc: func(cmd *cobra.Command) { cmd.Flags().StringP("from", "f", "localhost", "Address on which to receive traffic") cmd.Flags().StringSliceP("to", "t", []string{}, "Upstream address(es) to which traffic should be sent") cmd.Flags().BoolP("change-host-header", "c", false, "Set upstream Host header to address of upstream") cmd.Flags().BoolP("insecure", "", false, "Disable TLS verification (WARNING: DISABLES SECURITY BY NOT VERIFYING TLS CERTIFICATES!)") cmd.Flags().BoolP("disable-redirects", "r", false, "Disable HTTP->HTTPS redirects") cmd.Flags().BoolP("internal-certs", "i", false, "Use internal CA for issuing certs") cmd.Flags().StringSliceP("header-up", "H", []string{}, "Set a request header to send to the upstream (format: \"Field: value\")") cmd.Flags().StringSliceP("header-down", "d", []string{}, "Set a response header to send back to the client (format: \"Field: value\")") cmd.Flags().BoolP("access-log", "", false, "Enable the access log") cmd.Flags().BoolP("debug", "v", false, "Enable verbose debug logs") cmd.RunE = caddycmd.WrapCommandFuncForCobra(cmdReverseProxy) }, }) } func cmdReverseProxy(fs caddycmd.Flags) (int, error) { caddy.TrapSignals() from := fs.String("from") changeHost := fs.Bool("change-host-header") insecure := fs.Bool("insecure") disableRedir := fs.Bool("disable-redirects") internalCerts := fs.Bool("internal-certs") accessLog := fs.Bool("access-log") debug := fs.Bool("debug") httpPort := strconv.Itoa(caddyhttp.DefaultHTTPPort) httpsPort := strconv.Itoa(caddyhttp.DefaultHTTPSPort) to, err := fs.GetStringSlice("to") if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("invalid to flag: %v", err) } if len(to) == 0 { return caddy.ExitCodeFailedStartup, fmt.Errorf("--to is required") } // set up the downstream address; assume missing information from given parts fromAddr, err := httpcaddyfile.ParseAddress(from) if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("invalid downstream address %s: %v", from, err) } if fromAddr.Path != "" { return caddy.ExitCodeFailedStartup, fmt.Errorf("paths are not allowed: %s", from) } if fromAddr.Scheme == "" { if fromAddr.Port == httpPort || fromAddr.Host == "" { fromAddr.Scheme = "http" } else { fromAddr.Scheme = "https" } } if fromAddr.Port == "" { if fromAddr.Scheme == "http" { fromAddr.Port = httpPort } else if fromAddr.Scheme == "https" { fromAddr.Port = httpsPort } } // set up the upstream address; assume missing information from given parts // mixing schemes isn't supported, so use first defined (if available) toAddresses := make([]string, len(to)) var toScheme string for i, toLoc := range to { addr, err := parseUpstreamDialAddress(toLoc) if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("invalid upstream address %s: %v", toLoc, err) } if addr.scheme != "" && toScheme == "" { toScheme = addr.scheme } toAddresses[i] = addr.dialAddr() } // proceed to build the handler and server ht := HTTPTransport{} if toScheme == "https" { ht.TLS = new(TLSConfig) if insecure { ht.TLS.InsecureSkipVerify = true } } upstreamPool := UpstreamPool{} for _, toAddr := range toAddresses { parsedAddr, err := caddy.ParseNetworkAddress(toAddr) if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("invalid upstream address %s: %v", toAddr, err) } if parsedAddr.StartPort == 0 && parsedAddr.EndPort == 0 { // unix networks don't have ports upstreamPool = append(upstreamPool, &Upstream{ Dial: toAddr, }) } else { // expand a port range into multiple upstreams for i := parsedAddr.StartPort; i <= parsedAddr.EndPort; i++ { upstreamPool = append(upstreamPool, &Upstream{ Dial: caddy.JoinNetworkAddress("", parsedAddr.Host, fmt.Sprint(i)), }) } } } handler := Handler{ TransportRaw: caddyconfig.JSONModuleObject(ht, "protocol", "http", nil), Upstreams: upstreamPool, } // set up header_up headerUp, err := fs.GetStringSlice("header-up") if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("invalid header flag: %v", err) } if len(headerUp) > 0 { reqHdr := make(http.Header) for i, h := range headerUp { key, val, found := strings.Cut(h, ":") key, val = strings.TrimSpace(key), strings.TrimSpace(val) if !found || key == "" || val == "" { return caddy.ExitCodeFailedStartup, fmt.Errorf("header-up %d: invalid format \"%s\" (expecting \"Field: value\")", i, h) } reqHdr.Set(key, val) } handler.Headers = &headers.Handler{ Request: &headers.HeaderOps{ Set: reqHdr, }, } } // set up header_down headerDown, err := fs.GetStringSlice("header-down") if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("invalid header flag: %v", err) } if len(headerDown) > 0 { respHdr := make(http.Header) for i, h := range headerDown { key, val, found := strings.Cut(h, ":") key, val = strings.TrimSpace(key), strings.TrimSpace(val) if !found || key == "" || val == "" { return caddy.ExitCodeFailedStartup, fmt.Errorf("header-down %d: invalid format \"%s\" (expecting \"Field: value\")", i, h) } respHdr.Set(key, val) } if handler.Headers == nil { handler.Headers = &headers.Handler{} } handler.Headers.Response = &headers.RespHeaderOps{ HeaderOps: &headers.HeaderOps{ Set: respHdr, }, } } if changeHost { if handler.Headers == nil { handler.Headers = &headers.Handler{ Request: &headers.HeaderOps{ Set: http.Header{}, }, } } handler.Headers.Request.Set.Set("Host", "{http.reverse_proxy.upstream.hostport}") } route := caddyhttp.Route{ HandlersRaw: []json.RawMessage{ caddyconfig.JSONModuleObject(handler, "handler", "reverse_proxy", nil), }, } if fromAddr.Host != "" { route.MatcherSetsRaw = []caddy.ModuleMap{ { "host": caddyconfig.JSON(caddyhttp.MatchHost{fromAddr.Host}, nil), }, } } server := &caddyhttp.Server{ Routes: caddyhttp.RouteList{route}, Listen: []string{":" + fromAddr.Port}, } if accessLog { server.Logs = &caddyhttp.ServerLogConfig{} } if fromAddr.Scheme == "http" { server.AutoHTTPS = &caddyhttp.AutoHTTPSConfig{Disabled: true} } else if disableRedir { server.AutoHTTPS = &caddyhttp.AutoHTTPSConfig{DisableRedir: true} } httpApp := caddyhttp.App{ Servers: map[string]*caddyhttp.Server{"proxy": server}, } appsRaw := caddy.ModuleMap{ "http": caddyconfig.JSON(httpApp, nil), } if internalCerts && fromAddr.Host != "" { tlsApp := caddytls.TLS{ Automation: &caddytls.AutomationConfig{ Policies: []*caddytls.AutomationPolicy{{ SubjectsRaw: []string{fromAddr.Host}, IssuersRaw: []json.RawMessage{json.RawMessage(`{"module":"internal"}`)}, }}, }, } appsRaw["tls"] = caddyconfig.JSON(tlsApp, nil) } var false bool cfg := &caddy.Config{ Admin: &caddy.AdminConfig{ Disabled: true, Config: &caddy.ConfigSettings{ Persist: &false, }, }, AppsRaw: appsRaw, } if debug { cfg.Logging = &caddy.Logging{ Logs: map[string]*caddy.CustomLog{ "default": {BaseLog: caddy.BaseLog{Level: zap.DebugLevel.CapitalString()}}, }, } } err = caddy.Run(cfg) if err != nil { return caddy.ExitCodeFailedStartup, err } for _, to := range toAddresses { fmt.Printf("Caddy proxying %s -> %s\n", fromAddr.String(), to) } if len(toAddresses) > 1 { fmt.Println("Load balancing policy: random") } select {} }
Go
caddy/modules/caddyhttp/reverseproxy/copyresponse.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package reverseproxy import ( "fmt" "net/http" "strconv" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func init() { caddy.RegisterModule(CopyResponseHandler{}) caddy.RegisterModule(CopyResponseHeadersHandler{}) } // CopyResponseHandler is a special HTTP handler which may // only be used within reverse_proxy's handle_response routes, // to copy the proxy response. EXPERIMENTAL, subject to change. type CopyResponseHandler struct { // To write the upstream response's body but with a different // status code, set this field to the desired status code. StatusCode caddyhttp.WeakString `json:"status_code,omitempty"` ctx caddy.Context } // CaddyModule returns the Caddy module information. func (CopyResponseHandler) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.handlers.copy_response", New: func() caddy.Module { return new(CopyResponseHandler) }, } } // Provision ensures that h is set up properly before use. func (h *CopyResponseHandler) Provision(ctx caddy.Context) error { h.ctx = ctx return nil } // ServeHTTP implements the Handler interface. func (h CopyResponseHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request, _ caddyhttp.Handler) error { repl := req.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) hrc, ok := req.Context().Value(proxyHandleResponseContextCtxKey).(*handleResponseContext) // don't allow this to be used outside of handle_response routes if !ok { return caddyhttp.Error(http.StatusInternalServerError, fmt.Errorf("cannot use 'copy_response' outside of reverse_proxy's handle_response routes")) } // allow a custom status code to be written; otherwise the // status code from the upstream response is written if codeStr := h.StatusCode.String(); codeStr != "" { intVal, err := strconv.Atoi(repl.ReplaceAll(codeStr, "")) if err != nil { return caddyhttp.Error(http.StatusInternalServerError, err) } hrc.response.StatusCode = intVal } // make sure the reverse_proxy handler doesn't try to call // finalizeResponse again after we've already done it here. hrc.isFinalized = true // write the response return hrc.handler.finalizeResponse(rw, req, hrc.response, repl, hrc.start, hrc.logger) } // CopyResponseHeadersHandler is a special HTTP handler which may // only be used within reverse_proxy's handle_response routes, // to copy headers from the proxy response. EXPERIMENTAL; // subject to change. type CopyResponseHeadersHandler struct { // A list of header fields to copy from the response. // Cannot be defined at the same time as Exclude. Include []string `json:"include,omitempty"` // A list of header fields to skip copying from the response. // Cannot be defined at the same time as Include. Exclude []string `json:"exclude,omitempty"` includeMap map[string]struct{} excludeMap map[string]struct{} ctx caddy.Context } // CaddyModule returns the Caddy module information. func (CopyResponseHeadersHandler) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.handlers.copy_response_headers", New: func() caddy.Module { return new(CopyResponseHeadersHandler) }, } } // Validate ensures the h's configuration is valid. func (h *CopyResponseHeadersHandler) Validate() error { if len(h.Exclude) > 0 && len(h.Include) > 0 { return fmt.Errorf("cannot define both 'exclude' and 'include' lists at the same time") } return nil } // Provision ensures that h is set up properly before use. func (h *CopyResponseHeadersHandler) Provision(ctx caddy.Context) error { h.ctx = ctx // Optimize the include list by converting it to a map if len(h.Include) > 0 { h.includeMap = map[string]struct{}{} } for _, field := range h.Include { h.includeMap[http.CanonicalHeaderKey(field)] = struct{}{} } // Optimize the exclude list by converting it to a map if len(h.Exclude) > 0 { h.excludeMap = map[string]struct{}{} } for _, field := range h.Exclude { h.excludeMap[http.CanonicalHeaderKey(field)] = struct{}{} } return nil } // ServeHTTP implements the Handler interface. func (h CopyResponseHeadersHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request, next caddyhttp.Handler) error { hrc, ok := req.Context().Value(proxyHandleResponseContextCtxKey).(*handleResponseContext) // don't allow this to be used outside of handle_response routes if !ok { return caddyhttp.Error(http.StatusInternalServerError, fmt.Errorf("cannot use 'copy_response_headers' outside of reverse_proxy's handle_response routes")) } for field, values := range hrc.response.Header { // Check the include list first, skip // the header if it's _not_ in this list. if len(h.includeMap) > 0 { if _, ok := h.includeMap[field]; !ok { continue } } // Then, check the exclude list, skip // the header if it _is_ in this list. if len(h.excludeMap) > 0 { if _, ok := h.excludeMap[field]; ok { continue } } // Copy all the values for the header. for _, value := range values { rw.Header().Add(field, value) } } return next.ServeHTTP(rw, req) } // Interface guards var ( _ caddyhttp.MiddlewareHandler = (*CopyResponseHandler)(nil) _ caddyfile.Unmarshaler = (*CopyResponseHandler)(nil) _ caddy.Provisioner = (*CopyResponseHandler)(nil) _ caddyhttp.MiddlewareHandler = (*CopyResponseHeadersHandler)(nil) _ caddyfile.Unmarshaler = (*CopyResponseHeadersHandler)(nil) _ caddy.Provisioner = (*CopyResponseHeadersHandler)(nil) _ caddy.Validator = (*CopyResponseHeadersHandler)(nil) )
Go
caddy/modules/caddyhttp/reverseproxy/healthchecks.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package reverseproxy import ( "context" "fmt" "io" "net" "net/http" "net/url" "regexp" "runtime/debug" "strconv" "time" "go.uber.org/zap" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) // HealthChecks configures active and passive health checks. type HealthChecks struct { // Active health checks run in the background on a timer. To // minimally enable active health checks, set either path or // port (or both). Note that active health check status // (healthy/unhealthy) is stored per-proxy-handler, not // globally; this allows different handlers to use different // criteria to decide what defines a healthy backend. // // Active health checks do not run for dynamic upstreams. Active *ActiveHealthChecks `json:"active,omitempty"` // Passive health checks monitor proxied requests for errors or timeouts. // To minimally enable passive health checks, specify at least an empty // config object with fail_duration > 0. Passive health check state is // shared (stored globally), so a failure from one handler will be counted // by all handlers; but the tolerances or standards for what defines // healthy/unhealthy backends is configured per-proxy-handler. // // Passive health checks technically do operate on dynamic upstreams, // but are only effective for very busy proxies where the list of // upstreams is mostly stable. This is because the shared/global // state of upstreams is cleaned up when the upstreams are no longer // used. Since dynamic upstreams are allocated dynamically at each // request (specifically, each iteration of the proxy loop per request), // they are also cleaned up after every request. Thus, if there is a // moment when no requests are actively referring to a particular // upstream host, the passive health check state will be reset because // it will be garbage-collected. It is usually better for the dynamic // upstream module to only return healthy, available backends instead. Passive *PassiveHealthChecks `json:"passive,omitempty"` } // ActiveHealthChecks holds configuration related to active // health checks (that is, health checks which occur in a // background goroutine independently). type ActiveHealthChecks struct { // DEPRECATED: Use 'uri' instead. This field will be removed. TODO: remove this field Path string `json:"path,omitempty"` // The URI (path and query) to use for health checks URI string `json:"uri,omitempty"` // The port to use (if different from the upstream's dial // address) for health checks. Port int `json:"port,omitempty"` // HTTP headers to set on health check requests. Headers http.Header `json:"headers,omitempty"` // How frequently to perform active health checks (default 30s). Interval caddy.Duration `json:"interval,omitempty"` // How long to wait for a response from a backend before // considering it unhealthy (default 5s). Timeout caddy.Duration `json:"timeout,omitempty"` // The maximum response body to download from the backend // during a health check. MaxSize int64 `json:"max_size,omitempty"` // The HTTP status code to expect from a healthy backend. ExpectStatus int `json:"expect_status,omitempty"` // A regular expression against which to match the response // body of a healthy backend. ExpectBody string `json:"expect_body,omitempty"` uri *url.URL httpClient *http.Client bodyRegexp *regexp.Regexp logger *zap.Logger } // Provision ensures that a is set up properly before use. func (a *ActiveHealthChecks) Provision(ctx caddy.Context, h *Handler) error { if !a.IsEnabled() { return nil } // Canonicalize the header keys ahead of time, since // JSON unmarshaled headers may be incorrect cleaned := http.Header{} for key, hdrs := range a.Headers { for _, val := range hdrs { cleaned.Add(key, val) } } a.Headers = cleaned h.HealthChecks.Active.logger = h.logger.Named("health_checker.active") timeout := time.Duration(a.Timeout) if timeout == 0 { timeout = 5 * time.Second } if a.Path != "" { a.logger.Warn("the 'path' option is deprecated, please use 'uri' instead!") } // parse the URI string (supports path and query) if a.URI != "" { parsedURI, err := url.Parse(a.URI) if err != nil { return err } a.uri = parsedURI } a.httpClient = &http.Client{ Timeout: timeout, Transport: h.Transport, } for _, upstream := range h.Upstreams { // if there's an alternative port for health-check provided in the config, // then use it, otherwise use the port of upstream. if a.Port != 0 { upstream.activeHealthCheckPort = a.Port } } if a.Interval == 0 { a.Interval = caddy.Duration(30 * time.Second) } if a.ExpectBody != "" { var err error a.bodyRegexp, err = regexp.Compile(a.ExpectBody) if err != nil { return fmt.Errorf("expect_body: compiling regular expression: %v", err) } } return nil } // IsEnabled checks if the active health checks have // the minimum config necessary to be enabled. func (a *ActiveHealthChecks) IsEnabled() bool { return a.Path != "" || a.URI != "" || a.Port != 0 } // PassiveHealthChecks holds configuration related to passive // health checks (that is, health checks which occur during // the normal flow of request proxying). type PassiveHealthChecks struct { // How long to remember a failed request to a backend. A duration > 0 // enables passive health checking. Default is 0. FailDuration caddy.Duration `json:"fail_duration,omitempty"` // The number of failed requests within the FailDuration window to // consider a backend as "down". Must be >= 1; default is 1. Requires // that FailDuration be > 0. MaxFails int `json:"max_fails,omitempty"` // Limits the number of simultaneous requests to a backend by // marking the backend as "down" if it has this many concurrent // requests or more. UnhealthyRequestCount int `json:"unhealthy_request_count,omitempty"` // Count the request as failed if the response comes back with // one of these status codes. UnhealthyStatus []int `json:"unhealthy_status,omitempty"` // Count the request as failed if the response takes at least this // long to receive. UnhealthyLatency caddy.Duration `json:"unhealthy_latency,omitempty"` logger *zap.Logger } // CircuitBreaker is a type that can act as an early-warning // system for the health checker when backends are getting // overloaded. This interface is still experimental and is // subject to change. type CircuitBreaker interface { OK() bool RecordMetric(statusCode int, latency time.Duration) } // activeHealthChecker runs active health checks on a // regular basis and blocks until // h.HealthChecks.Active.stopChan is closed. func (h *Handler) activeHealthChecker() { defer func() { if err := recover(); err != nil { h.HealthChecks.Active.logger.Error("active health checker panicked", zap.Any("error", err), zap.ByteString("stack", debug.Stack())) } }() ticker := time.NewTicker(time.Duration(h.HealthChecks.Active.Interval)) h.doActiveHealthCheckForAllHosts() for { select { case <-ticker.C: h.doActiveHealthCheckForAllHosts() case <-h.ctx.Done(): ticker.Stop() return } } } // doActiveHealthCheckForAllHosts immediately performs a // health checks for all upstream hosts configured by h. func (h *Handler) doActiveHealthCheckForAllHosts() { for _, upstream := range h.Upstreams { go func(upstream *Upstream) { defer func() { if err := recover(); err != nil { h.HealthChecks.Active.logger.Error("active health check panicked", zap.Any("error", err), zap.ByteString("stack", debug.Stack())) } }() networkAddr, err := caddy.NewReplacer().ReplaceOrErr(upstream.Dial, true, true) if err != nil { h.HealthChecks.Active.logger.Error("invalid use of placeholders in dial address for active health checks", zap.String("address", networkAddr), zap.Error(err), ) return } addr, err := caddy.ParseNetworkAddress(networkAddr) if err != nil { h.HealthChecks.Active.logger.Error("bad network address", zap.String("address", networkAddr), zap.Error(err), ) return } if hcp := uint(upstream.activeHealthCheckPort); hcp != 0 { if addr.IsUnixNetwork() { addr.Network = "tcp" // I guess we just assume TCP since we are using a port?? } addr.StartPort, addr.EndPort = hcp, hcp } if addr.PortRangeSize() != 1 { h.HealthChecks.Active.logger.Error("multiple addresses (upstream must map to only one address)", zap.String("address", networkAddr), ) return } hostAddr := addr.JoinHostPort(0) dialAddr := hostAddr if addr.IsUnixNetwork() { // this will be used as the Host portion of a http.Request URL, and // paths to socket files would produce an error when creating URL, // so use a fake Host value instead; unix sockets are usually local hostAddr = "localhost" } err = h.doActiveHealthCheck(DialInfo{Network: addr.Network, Address: dialAddr}, hostAddr, upstream) if err != nil { h.HealthChecks.Active.logger.Error("active health check failed", zap.String("address", hostAddr), zap.Error(err), ) } }(upstream) } } // doActiveHealthCheck performs a health check to upstream which // can be reached at address hostAddr. The actual address for // the request will be built according to active health checker // config. The health status of the host will be updated // according to whether it passes the health check. An error is // returned only if the health check fails to occur or if marking // the host's health status fails. func (h *Handler) doActiveHealthCheck(dialInfo DialInfo, hostAddr string, upstream *Upstream) error { // create the URL for the request that acts as a health check u := &url.URL{ Scheme: "http", Host: hostAddr, } // split the host and port if possible, override the port if configured host, port, err := net.SplitHostPort(hostAddr) if err != nil { host = hostAddr } if h.HealthChecks.Active.Port != 0 { port := strconv.Itoa(h.HealthChecks.Active.Port) u.Host = net.JoinHostPort(host, port) } // this is kind of a hacky way to know if we should use HTTPS, but whatever if tt, ok := h.Transport.(TLSTransport); ok && tt.TLSEnabled() { u.Scheme = "https" // if the port is in the except list, flip back to HTTP if ht, ok := h.Transport.(*HTTPTransport); ok { for _, exceptPort := range ht.TLS.ExceptPorts { if exceptPort == port { u.Scheme = "http" } } } } // if we have a provisioned uri, use that, otherwise use // the deprecated Path option if h.HealthChecks.Active.uri != nil { u.Path = h.HealthChecks.Active.uri.Path u.RawQuery = h.HealthChecks.Active.uri.RawQuery } else { u.Path = h.HealthChecks.Active.Path } // attach dialing information to this request, as well as context values that // may be expected by handlers of this request ctx := h.ctx.Context ctx = context.WithValue(ctx, caddy.ReplacerCtxKey, caddy.NewReplacer()) ctx = context.WithValue(ctx, caddyhttp.VarsCtxKey, map[string]any{ dialInfoVarKey: dialInfo, }) req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil) if err != nil { return fmt.Errorf("making request: %v", err) } ctx = context.WithValue(ctx, caddyhttp.OriginalRequestCtxKey, *req) req = req.WithContext(ctx) for key, hdrs := range h.HealthChecks.Active.Headers { if key == "Host" { req.Host = h.HealthChecks.Active.Headers.Get(key) } else { req.Header[key] = hdrs } } markUnhealthy := func() { // dispatch an event that the host newly became unhealthy if upstream.setHealthy(false) { h.events.Emit(h.ctx, "unhealthy", map[string]any{"host": hostAddr}) } } // do the request, being careful to tame the response body resp, err := h.HealthChecks.Active.httpClient.Do(req) if err != nil { h.HealthChecks.Active.logger.Info("HTTP request failed", zap.String("host", hostAddr), zap.Error(err), ) markUnhealthy() return nil } var body io.Reader = resp.Body if h.HealthChecks.Active.MaxSize > 0 { body = io.LimitReader(body, h.HealthChecks.Active.MaxSize) } defer func() { // drain any remaining body so connection could be re-used _, _ = io.Copy(io.Discard, body) resp.Body.Close() }() // if status code is outside criteria, mark down if h.HealthChecks.Active.ExpectStatus > 0 { if !caddyhttp.StatusCodeMatches(resp.StatusCode, h.HealthChecks.Active.ExpectStatus) { h.HealthChecks.Active.logger.Info("unexpected status code", zap.Int("status_code", resp.StatusCode), zap.String("host", hostAddr), ) markUnhealthy() return nil } } else if resp.StatusCode < 200 || resp.StatusCode >= 400 { h.HealthChecks.Active.logger.Info("status code out of tolerances", zap.Int("status_code", resp.StatusCode), zap.String("host", hostAddr), ) markUnhealthy() return nil } // if body does not match regex, mark down if h.HealthChecks.Active.bodyRegexp != nil { bodyBytes, err := io.ReadAll(body) if err != nil { h.HealthChecks.Active.logger.Info("failed to read response body", zap.String("host", hostAddr), zap.Error(err), ) markUnhealthy() return nil } if !h.HealthChecks.Active.bodyRegexp.Match(bodyBytes) { h.HealthChecks.Active.logger.Info("response body failed expectations", zap.String("host", hostAddr), ) markUnhealthy() return nil } } // passed health check parameters, so mark as healthy if upstream.setHealthy(true) { h.HealthChecks.Active.logger.Info("host is up", zap.String("host", hostAddr)) h.events.Emit(h.ctx, "healthy", map[string]any{"host": hostAddr}) } return nil } // countFailure is used with passive health checks. It // remembers 1 failure for upstream for the configured // duration. If passive health checks are disabled or // failure expiry is 0, this is a no-op. func (h *Handler) countFailure(upstream *Upstream) { // only count failures if passive health checking is enabled // and if failures are configured have a non-zero expiry if h.HealthChecks == nil || h.HealthChecks.Passive == nil { return } failDuration := time.Duration(h.HealthChecks.Passive.FailDuration) if failDuration == 0 { return } // count failure immediately err := upstream.Host.countFail(1) if err != nil { h.HealthChecks.Passive.logger.Error("could not count failure", zap.String("host", upstream.Dial), zap.Error(err)) return } // forget it later go func(host *Host, failDuration time.Duration) { defer func() { if err := recover(); err != nil { h.HealthChecks.Passive.logger.Error("passive health check failure forgetter panicked", zap.Any("error", err), zap.ByteString("stack", debug.Stack())) } }() timer := time.NewTimer(failDuration) select { case <-h.ctx.Done(): if !timer.Stop() { <-timer.C } case <-timer.C: } err := host.countFail(-1) if err != nil { h.HealthChecks.Passive.logger.Error("could not forget failure", zap.String("host", upstream.Dial), zap.Error(err)) } }(upstream.Host, failDuration) }
Go
caddy/modules/caddyhttp/reverseproxy/hosts.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package reverseproxy import ( "context" "fmt" "net/http" "net/netip" "strconv" "sync/atomic" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) // UpstreamPool is a collection of upstreams. type UpstreamPool []*Upstream // Upstream bridges this proxy's configuration to the // state of the backend host it is correlated with. // Upstream values must not be copied. type Upstream struct { *Host `json:"-"` // The [network address](/docs/conventions#network-addresses) // to dial to connect to the upstream. Must represent precisely // one socket (i.e. no port ranges). A valid network address // either has a host and port or is a unix socket address. // // Placeholders may be used to make the upstream dynamic, but be // aware of the health check implications of this: a single // upstream that represents numerous (perhaps arbitrary) backends // can be considered down if one or enough of the arbitrary // backends is down. Also be aware of open proxy vulnerabilities. Dial string `json:"dial,omitempty"` // The maximum number of simultaneous requests to allow to // this upstream. If set, overrides the global passive health // check UnhealthyRequestCount value. MaxRequests int `json:"max_requests,omitempty"` // TODO: This could be really useful, to bind requests // with certain properties to specific backends // HeaderAffinity string // IPAffinity string activeHealthCheckPort int healthCheckPolicy *PassiveHealthChecks cb CircuitBreaker unhealthy int32 // accessed atomically; status from active health checker } // (pointer receiver necessary to avoid a race condition, since // copying the Upstream reads the 'unhealthy' field which is // accessed atomically) func (u *Upstream) String() string { return u.Dial } // Available returns true if the remote host // is available to receive requests. This is // the method that should be used by selection // policies, etc. to determine if a backend // should be able to be sent a request. func (u *Upstream) Available() bool { return u.Healthy() && !u.Full() } // Healthy returns true if the remote host // is currently known to be healthy or "up". // It consults the circuit breaker, if any. func (u *Upstream) Healthy() bool { healthy := u.healthy() if healthy && u.healthCheckPolicy != nil { healthy = u.Host.Fails() < u.healthCheckPolicy.MaxFails } if healthy && u.cb != nil { healthy = u.cb.OK() } return healthy } // Full returns true if the remote host // cannot receive more requests at this time. func (u *Upstream) Full() bool { return u.MaxRequests > 0 && u.Host.NumRequests() >= u.MaxRequests } // fillDialInfo returns a filled DialInfo for upstream u, using the request // context. Note that the returned value is not a pointer. func (u *Upstream) fillDialInfo(r *http.Request) (DialInfo, error) { repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) var addr caddy.NetworkAddress // use provided dial address var err error dial := repl.ReplaceAll(u.Dial, "") addr, err = caddy.ParseNetworkAddress(dial) if err != nil { return DialInfo{}, fmt.Errorf("upstream %s: invalid dial address %s: %v", u.Dial, dial, err) } if numPorts := addr.PortRangeSize(); numPorts != 1 { return DialInfo{}, fmt.Errorf("upstream %s: dial address must represent precisely one socket: %s represents %d", u.Dial, dial, numPorts) } return DialInfo{ Upstream: u, Network: addr.Network, Address: addr.JoinHostPort(0), Host: addr.Host, Port: strconv.Itoa(int(addr.StartPort)), }, nil } func (u *Upstream) fillHost() { host := new(Host) existingHost, loaded := hosts.LoadOrStore(u.String(), host) if loaded { host = existingHost.(*Host) } u.Host = host } // Host is the basic, in-memory representation of the state of a remote host. // Its fields are accessed atomically and Host values must not be copied. type Host struct { numRequests int64 // must be 64-bit aligned on 32-bit systems (see https://golang.org/pkg/sync/atomic/#pkg-note-BUG) fails int64 } // NumRequests returns the number of active requests to the upstream. func (h *Host) NumRequests() int { return int(atomic.LoadInt64(&h.numRequests)) } // Fails returns the number of recent failures with the upstream. func (h *Host) Fails() int { return int(atomic.LoadInt64(&h.fails)) } // countRequest mutates the active request count by // delta. It returns an error if the adjustment fails. func (h *Host) countRequest(delta int) error { result := atomic.AddInt64(&h.numRequests, int64(delta)) if result < 0 { return fmt.Errorf("count below 0: %d", result) } return nil } // countFail mutates the recent failures count by // delta. It returns an error if the adjustment fails. func (h *Host) countFail(delta int) error { result := atomic.AddInt64(&h.fails, int64(delta)) if result < 0 { return fmt.Errorf("count below 0: %d", result) } return nil } // healthy returns true if the upstream is not actively marked as unhealthy. // (This returns the status only from the "active" health checks.) func (u *Upstream) healthy() bool { return atomic.LoadInt32(&u.unhealthy) == 0 } // SetHealthy sets the upstream has healthy or unhealthy // and returns true if the new value is different. This // sets the status only for the "active" health checks. func (u *Upstream) setHealthy(healthy bool) bool { var unhealthy, compare int32 = 1, 0 if healthy { unhealthy, compare = 0, 1 } return atomic.CompareAndSwapInt32(&u.unhealthy, compare, unhealthy) } // DialInfo contains information needed to dial a // connection to an upstream host. This information // may be different than that which is represented // in a URL (for example, unix sockets don't have // a host that can be represented in a URL, but // they certainly have a network name and address). type DialInfo struct { // Upstream is the Upstream associated with // this DialInfo. It may be nil. Upstream *Upstream // The network to use. This should be one of // the values that is accepted by net.Dial: // https://golang.org/pkg/net/#Dial Network string // The address to dial. Follows the same // semantics and rules as net.Dial. Address string // Host and Port are components of Address. Host, Port string } // String returns the Caddy network address form // by joining the network and address with a // forward slash. func (di DialInfo) String() string { return caddy.JoinNetworkAddress(di.Network, di.Host, di.Port) } // GetDialInfo gets the upstream dialing info out of the context, // and returns true if there was a valid value; false otherwise. func GetDialInfo(ctx context.Context) (DialInfo, bool) { dialInfo, ok := caddyhttp.GetVar(ctx, dialInfoVarKey).(DialInfo) return dialInfo, ok } // hosts is the global repository for hosts that are // currently in use by active configuration(s). This // allows the state of remote hosts to be preserved // through config reloads. var hosts = caddy.NewUsagePool() // dialInfoVarKey is the key used for the variable that holds // the dial info for the upstream connection. const dialInfoVarKey = "reverse_proxy.dial_info" // proxyProtocolInfoVarKey is the key used for the variable that holds // the proxy protocol info for the upstream connection. const proxyProtocolInfoVarKey = "reverse_proxy.proxy_protocol_info" // ProxyProtocolInfo contains information needed to write proxy protocol to a // connection to an upstream host. type ProxyProtocolInfo struct { AddrPort netip.AddrPort }
Go
caddy/modules/caddyhttp/reverseproxy/httptransport.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package reverseproxy import ( "context" "crypto/tls" "crypto/x509" "encoding/base64" "fmt" weakrand "math/rand" "net" "net/http" "os" "reflect" "strings" "time" "github.com/mastercactapus/proxyprotocol" "go.uber.org/zap" "golang.org/x/net/http2" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" "github.com/caddyserver/caddy/v2/modules/caddytls" ) func init() { caddy.RegisterModule(HTTPTransport{}) } // HTTPTransport is essentially a configuration wrapper for http.Transport. // It defines a JSON structure useful when configuring the HTTP transport // for Caddy's reverse proxy. It builds its http.Transport at Provision. type HTTPTransport struct { // TODO: It's possible that other transports (like fastcgi) might be // able to borrow/use at least some of these config fields; if so, // maybe move them into a type called CommonTransport and embed it? // Configures the DNS resolver used to resolve the IP address of upstream hostnames. Resolver *UpstreamResolver `json:"resolver,omitempty"` // Configures TLS to the upstream. Setting this to an empty struct // is sufficient to enable TLS with reasonable defaults. TLS *TLSConfig `json:"tls,omitempty"` // Configures HTTP Keep-Alive (enabled by default). Should only be // necessary if rigorous testing has shown that tuning this helps // improve performance. KeepAlive *KeepAlive `json:"keep_alive,omitempty"` // Whether to enable compression to upstream. Default: true Compression *bool `json:"compression,omitempty"` // Maximum number of connections per host. Default: 0 (no limit) MaxConnsPerHost int `json:"max_conns_per_host,omitempty"` // If non-empty, which PROXY protocol version to send when // connecting to an upstream. Default: off. ProxyProtocol string `json:"proxy_protocol,omitempty"` // How long to wait before timing out trying to connect to // an upstream. Default: `3s`. DialTimeout caddy.Duration `json:"dial_timeout,omitempty"` // How long to wait before spawning an RFC 6555 Fast Fallback // connection. A negative value disables this. Default: `300ms`. FallbackDelay caddy.Duration `json:"dial_fallback_delay,omitempty"` // How long to wait for reading response headers from server. Default: No timeout. ResponseHeaderTimeout caddy.Duration `json:"response_header_timeout,omitempty"` // The length of time to wait for a server's first response // headers after fully writing the request headers if the // request has a header "Expect: 100-continue". Default: No timeout. ExpectContinueTimeout caddy.Duration `json:"expect_continue_timeout,omitempty"` // The maximum bytes to read from response headers. Default: `10MiB`. MaxResponseHeaderSize int64 `json:"max_response_header_size,omitempty"` // The size of the write buffer in bytes. Default: `4KiB`. WriteBufferSize int `json:"write_buffer_size,omitempty"` // The size of the read buffer in bytes. Default: `4KiB`. ReadBufferSize int `json:"read_buffer_size,omitempty"` // The maximum time to wait for next read from backend. Default: no timeout. ReadTimeout caddy.Duration `json:"read_timeout,omitempty"` // The maximum time to wait for next write to backend. Default: no timeout. WriteTimeout caddy.Duration `json:"write_timeout,omitempty"` // The versions of HTTP to support. As a special case, "h2c" // can be specified to use H2C (HTTP/2 over Cleartext) to the // upstream (this feature is experimental and subject to // change or removal). Default: ["1.1", "2"] Versions []string `json:"versions,omitempty"` // The pre-configured underlying HTTP transport. Transport *http.Transport `json:"-"` h2cTransport *http2.Transport } // CaddyModule returns the Caddy module information. func (HTTPTransport) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.reverse_proxy.transport.http", New: func() caddy.Module { return new(HTTPTransport) }, } } // Provision sets up h.Transport with a *http.Transport // that is ready to use. func (h *HTTPTransport) Provision(ctx caddy.Context) error { if len(h.Versions) == 0 { h.Versions = []string{"1.1", "2"} } rt, err := h.NewTransport(ctx) if err != nil { return err } h.Transport = rt return nil } // NewTransport builds a standard-lib-compatible http.Transport value from h. func (h *HTTPTransport) NewTransport(caddyCtx caddy.Context) (*http.Transport, error) { // Set keep-alive defaults if it wasn't otherwise configured if h.KeepAlive == nil { h.KeepAlive = &KeepAlive{ ProbeInterval: caddy.Duration(30 * time.Second), IdleConnTimeout: caddy.Duration(2 * time.Minute), MaxIdleConnsPerHost: 32, // seems about optimal, see #2805 } } // Set a relatively short default dial timeout. // This is helpful to make load-balancer retries more speedy. if h.DialTimeout == 0 { h.DialTimeout = caddy.Duration(3 * time.Second) } dialer := &net.Dialer{ Timeout: time.Duration(h.DialTimeout), FallbackDelay: time.Duration(h.FallbackDelay), } if h.Resolver != nil { err := h.Resolver.ParseAddresses() if err != nil { return nil, err } d := &net.Dialer{ Timeout: time.Duration(h.DialTimeout), FallbackDelay: time.Duration(h.FallbackDelay), } dialer.Resolver = &net.Resolver{ PreferGo: true, Dial: func(ctx context.Context, _, _ string) (net.Conn, error) { //nolint:gosec addr := h.Resolver.netAddrs[weakrand.Intn(len(h.Resolver.netAddrs))] return d.DialContext(ctx, addr.Network, addr.JoinHostPort(0)) }, } } dialContext := func(ctx context.Context, network, address string) (net.Conn, error) { // For unix socket upstreams, we need to recover the dial info from // the request's context, because the Host on the request's URL // will have been modified by directing the request, overwriting // the unix socket filename. // Also, we need to avoid overwriting the address at this point // when not necessary, because http.ProxyFromEnvironment may have // modified the address according to the user's env proxy config. if dialInfo, ok := GetDialInfo(ctx); ok { if strings.HasPrefix(dialInfo.Network, "unix") { network = dialInfo.Network address = dialInfo.Address } } conn, err := dialer.DialContext(ctx, network, address) if err != nil { // identify this error as one that occurred during // dialing, which can be important when trying to // decide whether to retry a request return nil, DialError{err} } if h.ProxyProtocol != "" { proxyProtocolInfo, ok := caddyhttp.GetVar(ctx, proxyProtocolInfoVarKey).(ProxyProtocolInfo) if !ok { return nil, fmt.Errorf("failed to get proxy protocol info from context") } // The src and dst have to be of the some address family. As we don't know the original // dst address (it's kind of impossible to know) and this address is generelly of very // little interest, we just set it to all zeros. var destIP net.IP switch { case proxyProtocolInfo.AddrPort.Addr().Is4(): destIP = net.IPv4zero case proxyProtocolInfo.AddrPort.Addr().Is6(): destIP = net.IPv6zero default: return nil, fmt.Errorf("unexpected remote addr type in proxy protocol info") } // TODO: We should probably migrate away from net.IP to use netip.Addr, // but due to the upstream dependency, we can't do that yet. switch h.ProxyProtocol { case "v1": header := proxyprotocol.HeaderV1{ SrcIP: net.IP(proxyProtocolInfo.AddrPort.Addr().AsSlice()), SrcPort: int(proxyProtocolInfo.AddrPort.Port()), DestIP: destIP, DestPort: 0, } caddyCtx.Logger().Debug("sending proxy protocol header v1", zap.Any("header", header)) _, err = header.WriteTo(conn) case "v2": header := proxyprotocol.HeaderV2{ Command: proxyprotocol.CmdProxy, Src: &net.TCPAddr{IP: net.IP(proxyProtocolInfo.AddrPort.Addr().AsSlice()), Port: int(proxyProtocolInfo.AddrPort.Port())}, Dest: &net.TCPAddr{IP: destIP, Port: 0}, } caddyCtx.Logger().Debug("sending proxy protocol header v2", zap.Any("header", header)) _, err = header.WriteTo(conn) default: return nil, fmt.Errorf("unexpected proxy protocol version") } if err != nil { // identify this error as one that occurred during // dialing, which can be important when trying to // decide whether to retry a request return nil, DialError{err} } } // if read/write timeouts are configured and this is a TCP connection, // enforce the timeouts by wrapping the connection with our own type if tcpConn, ok := conn.(*net.TCPConn); ok && (h.ReadTimeout > 0 || h.WriteTimeout > 0) { conn = &tcpRWTimeoutConn{ TCPConn: tcpConn, readTimeout: time.Duration(h.ReadTimeout), writeTimeout: time.Duration(h.WriteTimeout), logger: caddyCtx.Logger(), } } return conn, nil } rt := &http.Transport{ Proxy: http.ProxyFromEnvironment, DialContext: dialContext, MaxConnsPerHost: h.MaxConnsPerHost, ResponseHeaderTimeout: time.Duration(h.ResponseHeaderTimeout), ExpectContinueTimeout: time.Duration(h.ExpectContinueTimeout), MaxResponseHeaderBytes: h.MaxResponseHeaderSize, WriteBufferSize: h.WriteBufferSize, ReadBufferSize: h.ReadBufferSize, } if h.TLS != nil { rt.TLSHandshakeTimeout = time.Duration(h.TLS.HandshakeTimeout) var err error rt.TLSClientConfig, err = h.TLS.MakeTLSClientConfig(caddyCtx) if err != nil { return nil, fmt.Errorf("making TLS client config: %v", err) } } if h.KeepAlive != nil { dialer.KeepAlive = time.Duration(h.KeepAlive.ProbeInterval) if h.KeepAlive.Enabled != nil { rt.DisableKeepAlives = !*h.KeepAlive.Enabled } rt.MaxIdleConns = h.KeepAlive.MaxIdleConns rt.MaxIdleConnsPerHost = h.KeepAlive.MaxIdleConnsPerHost rt.IdleConnTimeout = time.Duration(h.KeepAlive.IdleConnTimeout) } // The proxy protocol header can only be sent once right after opening the connection. // So single connection must not be used for multiple requests, which can potentially // come from different clients. if !rt.DisableKeepAlives && h.ProxyProtocol != "" { caddyCtx.Logger().Warn("disabling keepalives, they are incompatible with using PROXY protocol") rt.DisableKeepAlives = true } if h.Compression != nil { rt.DisableCompression = !*h.Compression } if sliceContains(h.Versions, "2") { if err := http2.ConfigureTransport(rt); err != nil { return nil, err } } // if h2c is enabled, configure its transport (std lib http.Transport // does not "HTTP/2 over cleartext TCP") if sliceContains(h.Versions, "h2c") { // crafting our own http2.Transport doesn't allow us to utilize // most of the customizations/preferences on the http.Transport, // because, for some reason, only http2.ConfigureTransport() // is allowed to set the unexported field that refers to a base // http.Transport config; oh well h2t := &http2.Transport{ // kind of a hack, but for plaintext/H2C requests, pretend to dial TLS DialTLSContext: func(ctx context.Context, network, address string, _ *tls.Config) (net.Conn, error) { return dialContext(ctx, network, address) }, AllowHTTP: true, } if h.Compression != nil { h2t.DisableCompression = !*h.Compression } h.h2cTransport = h2t } return rt, nil } // replaceTLSServername checks TLS servername to see if it needs replacing // if it does need replacing, it creates a new cloned HTTPTransport object to avoid any races // and does the replacing of the TLS servername on that and returns the new object // if no replacement is necessary it returns the original func (h *HTTPTransport) replaceTLSServername(repl *caddy.Replacer) *HTTPTransport { // check whether we have TLS and need to replace the servername in the TLSClientConfig if h.TLSEnabled() && strings.Contains(h.TLS.ServerName, "{") { // make a new h, "copy" the parts we don't need to touch, add a new *tls.Config and replace servername newtransport := &HTTPTransport{ Resolver: h.Resolver, TLS: h.TLS, KeepAlive: h.KeepAlive, Compression: h.Compression, MaxConnsPerHost: h.MaxConnsPerHost, DialTimeout: h.DialTimeout, FallbackDelay: h.FallbackDelay, ResponseHeaderTimeout: h.ResponseHeaderTimeout, ExpectContinueTimeout: h.ExpectContinueTimeout, MaxResponseHeaderSize: h.MaxResponseHeaderSize, WriteBufferSize: h.WriteBufferSize, ReadBufferSize: h.ReadBufferSize, Versions: h.Versions, Transport: h.Transport.Clone(), h2cTransport: h.h2cTransport, } newtransport.Transport.TLSClientConfig.ServerName = repl.ReplaceAll(newtransport.Transport.TLSClientConfig.ServerName, "") return newtransport } return h } // RoundTrip implements http.RoundTripper. func (h *HTTPTransport) RoundTrip(req *http.Request) (*http.Response, error) { // Try to replace TLS servername if needed repl := req.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) transport := h.replaceTLSServername(repl) transport.SetScheme(req) // if H2C ("HTTP/2 over cleartext") is enabled and the upstream request is // HTTP without TLS, use the alternate H2C-capable transport instead if req.URL.Scheme == "http" && h.h2cTransport != nil { return h.h2cTransport.RoundTrip(req) } return transport.Transport.RoundTrip(req) } // SetScheme ensures that the outbound request req // has the scheme set in its URL; the underlying // http.Transport requires a scheme to be set. // // This method may be used by other transport modules // that wrap/use this one. func (h *HTTPTransport) SetScheme(req *http.Request) { if req.URL.Scheme != "" { return } if h.shouldUseTLS(req) { req.URL.Scheme = "https" } else { req.URL.Scheme = "http" } } // shouldUseTLS returns true if TLS should be used for req. func (h *HTTPTransport) shouldUseTLS(req *http.Request) bool { if h.TLS == nil { return false } port := req.URL.Port() for i := range h.TLS.ExceptPorts { if h.TLS.ExceptPorts[i] == port { return false } } return true } // TLSEnabled returns true if TLS is enabled. func (h HTTPTransport) TLSEnabled() bool { return h.TLS != nil } // EnableTLS enables TLS on the transport. func (h *HTTPTransport) EnableTLS(base *TLSConfig) error { h.TLS = base return nil } // Cleanup implements caddy.CleanerUpper and closes any idle connections. func (h HTTPTransport) Cleanup() error { if h.Transport == nil { return nil } h.Transport.CloseIdleConnections() return nil } // TLSConfig holds configuration related to the TLS configuration for the // transport/client. type TLSConfig struct { // Optional list of base64-encoded DER-encoded CA certificates to trust. RootCAPool []string `json:"root_ca_pool,omitempty"` // List of PEM-encoded CA certificate files to add to the same trust // store as RootCAPool (or root_ca_pool in the JSON). RootCAPEMFiles []string `json:"root_ca_pem_files,omitempty"` // PEM-encoded client certificate filename to present to servers. ClientCertificateFile string `json:"client_certificate_file,omitempty"` // PEM-encoded key to use with the client certificate. ClientCertificateKeyFile string `json:"client_certificate_key_file,omitempty"` // If specified, Caddy will use and automate a client certificate // with this subject name. ClientCertificateAutomate string `json:"client_certificate_automate,omitempty"` // If true, TLS verification of server certificates will be disabled. // This is insecure and may be removed in the future. Do not use this // option except in testing or local development environments. InsecureSkipVerify bool `json:"insecure_skip_verify,omitempty"` // The duration to allow a TLS handshake to a server. Default: No timeout. HandshakeTimeout caddy.Duration `json:"handshake_timeout,omitempty"` // The server name used when verifying the certificate received in the TLS // handshake. By default, this will use the upstream address' host part. // You only need to override this if your upstream address does not match the // certificate the upstream is likely to use. For example if the upstream // address is an IP address, then you would need to configure this to the // hostname being served by the upstream server. Currently, this does not // support placeholders because the TLS config is not provisioned on each // connection, so a static value must be used. ServerName string `json:"server_name,omitempty"` // TLS renegotiation level. TLS renegotiation is the act of performing // subsequent handshakes on a connection after the first. // The level can be: // - "never": (the default) disables renegotiation. // - "once": allows a remote server to request renegotiation once per connection. // - "freely": allows a remote server to repeatedly request renegotiation. Renegotiation string `json:"renegotiation,omitempty"` // Skip TLS ports specifies a list of upstream ports on which TLS should not be // attempted even if it is configured. Handy when using dynamic upstreams that // return HTTP and HTTPS endpoints too. // When specified, TLS will automatically be configured on the transport. // The value can be a list of any valid tcp port numbers, default empty. ExceptPorts []string `json:"except_ports,omitempty"` } // MakeTLSClientConfig returns a tls.Config usable by a client to a backend. // If there is no custom TLS configuration, a nil config may be returned. func (t TLSConfig) MakeTLSClientConfig(ctx caddy.Context) (*tls.Config, error) { cfg := new(tls.Config) // client auth if t.ClientCertificateFile != "" && t.ClientCertificateKeyFile == "" { return nil, fmt.Errorf("client_certificate_file specified without client_certificate_key_file") } if t.ClientCertificateFile == "" && t.ClientCertificateKeyFile != "" { return nil, fmt.Errorf("client_certificate_key_file specified without client_certificate_file") } if t.ClientCertificateFile != "" && t.ClientCertificateKeyFile != "" { cert, err := tls.LoadX509KeyPair(t.ClientCertificateFile, t.ClientCertificateKeyFile) if err != nil { return nil, fmt.Errorf("loading client certificate key pair: %v", err) } cfg.Certificates = []tls.Certificate{cert} } if t.ClientCertificateAutomate != "" { // TODO: use or enable ctx.IdentityCredentials() ... tlsAppIface, err := ctx.App("tls") if err != nil { return nil, fmt.Errorf("getting tls app: %v", err) } tlsApp := tlsAppIface.(*caddytls.TLS) err = tlsApp.Manage([]string{t.ClientCertificateAutomate}) if err != nil { return nil, fmt.Errorf("managing client certificate: %v", err) } cfg.GetClientCertificate = func(cri *tls.CertificateRequestInfo) (*tls.Certificate, error) { certs := caddytls.AllMatchingCertificates(t.ClientCertificateAutomate) var err error for _, cert := range certs { err = cri.SupportsCertificate(&cert.Certificate) if err == nil { return &cert.Certificate, nil } } if err == nil { err = fmt.Errorf("no client certificate found for automate name: %s", t.ClientCertificateAutomate) } return nil, err } } // trusted root CAs if len(t.RootCAPool) > 0 || len(t.RootCAPEMFiles) > 0 { rootPool := x509.NewCertPool() for _, encodedCACert := range t.RootCAPool { caCert, err := decodeBase64DERCert(encodedCACert) if err != nil { return nil, fmt.Errorf("parsing CA certificate: %v", err) } rootPool.AddCert(caCert) } for _, pemFile := range t.RootCAPEMFiles { pemData, err := os.ReadFile(pemFile) if err != nil { return nil, fmt.Errorf("failed reading ca cert: %v", err) } rootPool.AppendCertsFromPEM(pemData) } cfg.RootCAs = rootPool } // Renegotiation switch t.Renegotiation { case "never", "": cfg.Renegotiation = tls.RenegotiateNever case "once": cfg.Renegotiation = tls.RenegotiateOnceAsClient case "freely": cfg.Renegotiation = tls.RenegotiateFreelyAsClient default: return nil, fmt.Errorf("invalid TLS renegotiation level: %v", t.Renegotiation) } // override for the server name used verify the TLS handshake cfg.ServerName = t.ServerName // throw all security out the window cfg.InsecureSkipVerify = t.InsecureSkipVerify // only return a config if it's not empty if reflect.DeepEqual(cfg, new(tls.Config)) { return nil, nil } return cfg, nil } // KeepAlive holds configuration pertaining to HTTP Keep-Alive. type KeepAlive struct { // Whether HTTP Keep-Alive is enabled. Default: `true` Enabled *bool `json:"enabled,omitempty"` // How often to probe for liveness. Default: `30s`. ProbeInterval caddy.Duration `json:"probe_interval,omitempty"` // Maximum number of idle connections. Default: `0`, which means no limit. MaxIdleConns int `json:"max_idle_conns,omitempty"` // Maximum number of idle connections per host. Default: `32`. MaxIdleConnsPerHost int `json:"max_idle_conns_per_host,omitempty"` // How long connections should be kept alive when idle. Default: `2m`. IdleConnTimeout caddy.Duration `json:"idle_timeout,omitempty"` } // tcpRWTimeoutConn enforces read/write timeouts for a TCP connection. // If it fails to set deadlines, the error is logged but does not abort // the read/write attempt (ignoring the error is consistent with what // the standard library does: https://github.com/golang/go/blob/c5da4fb7ac5cb7434b41fc9a1df3bee66c7f1a4d/src/net/http/server.go#L981-L986) type tcpRWTimeoutConn struct { *net.TCPConn readTimeout, writeTimeout time.Duration logger *zap.Logger } func (c *tcpRWTimeoutConn) Read(b []byte) (int, error) { if c.readTimeout > 0 { err := c.TCPConn.SetReadDeadline(time.Now().Add(c.readTimeout)) if err != nil { c.logger.Error("failed to set read deadline", zap.Error(err)) } } return c.TCPConn.Read(b) } func (c *tcpRWTimeoutConn) Write(b []byte) (int, error) { if c.writeTimeout > 0 { err := c.TCPConn.SetWriteDeadline(time.Now().Add(c.writeTimeout)) if err != nil { c.logger.Error("failed to set write deadline", zap.Error(err)) } } return c.TCPConn.Write(b) } // decodeBase64DERCert base64-decodes, then DER-decodes, certStr. func decodeBase64DERCert(certStr string) (*x509.Certificate, error) { // decode base64 derBytes, err := base64.StdEncoding.DecodeString(certStr) if err != nil { return nil, err } // parse the DER-encoded certificate return x509.ParseCertificate(derBytes) } // 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 } // Interface guards var ( _ caddy.Provisioner = (*HTTPTransport)(nil) _ http.RoundTripper = (*HTTPTransport)(nil) _ caddy.CleanerUpper = (*HTTPTransport)(nil) _ TLSTransport = (*HTTPTransport)(nil) )
Go
caddy/modules/caddyhttp/reverseproxy/metrics.go
package reverseproxy import ( "runtime/debug" "sync" "time" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" "go.uber.org/zap" ) var reverseProxyMetrics = struct { init sync.Once upstreamsHealthy *prometheus.GaugeVec logger *zap.Logger }{} func initReverseProxyMetrics(handler *Handler) { const ns, sub = "caddy", "reverse_proxy" upstreamsLabels := []string{"upstream"} reverseProxyMetrics.upstreamsHealthy = promauto.NewGaugeVec(prometheus.GaugeOpts{ Namespace: ns, Subsystem: sub, Name: "upstreams_healthy", Help: "Health status of reverse proxy upstreams.", }, upstreamsLabels) reverseProxyMetrics.logger = handler.logger.Named("reverse_proxy.metrics") } type metricsUpstreamsHealthyUpdater struct { handler *Handler } func newMetricsUpstreamsHealthyUpdater(handler *Handler) *metricsUpstreamsHealthyUpdater { reverseProxyMetrics.init.Do(func() { initReverseProxyMetrics(handler) }) reverseProxyMetrics.upstreamsHealthy.Reset() return &metricsUpstreamsHealthyUpdater{handler} } func (m *metricsUpstreamsHealthyUpdater) Init() { go func() { defer func() { if err := recover(); err != nil { reverseProxyMetrics.logger.Error("upstreams healthy metrics updater panicked", zap.Any("error", err), zap.ByteString("stack", debug.Stack())) } }() m.update() ticker := time.NewTicker(10 * time.Second) for { select { case <-ticker.C: m.update() case <-m.handler.ctx.Done(): ticker.Stop() return } } }() } func (m *metricsUpstreamsHealthyUpdater) update() { for _, upstream := range m.handler.Upstreams { labels := prometheus.Labels{"upstream": upstream.Dial} gaugeValue := 0.0 if upstream.Healthy() { gaugeValue = 1.0 } reverseProxyMetrics.upstreamsHealthy.With(labels).Set(gaugeValue) } }
Go
caddy/modules/caddyhttp/reverseproxy/reverseproxy.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package reverseproxy import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "net" "net/http" "net/http/httptrace" "net/netip" "net/textproto" "net/url" "strconv" "strings" "sync" "time" "go.uber.org/zap" "golang.org/x/net/http/httpguts" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/modules/caddyevents" "github.com/caddyserver/caddy/v2/modules/caddyhttp" "github.com/caddyserver/caddy/v2/modules/caddyhttp/headers" "github.com/caddyserver/caddy/v2/modules/caddyhttp/rewrite" ) func init() { caddy.RegisterModule(Handler{}) } // Handler implements a highly configurable and production-ready reverse proxy. // // Upon proxying, this module sets the following placeholders (which can be used // both within and after this handler; for example, in response headers): // // Placeholder | Description // ------------|------------- // `{http.reverse_proxy.upstream.address}` | The full address to the upstream as given in the config // `{http.reverse_proxy.upstream.hostport}` | The host:port of the upstream // `{http.reverse_proxy.upstream.host}` | The host of the upstream // `{http.reverse_proxy.upstream.port}` | The port of the upstream // `{http.reverse_proxy.upstream.requests}` | The approximate current number of requests to the upstream // `{http.reverse_proxy.upstream.max_requests}` | The maximum approximate number of requests allowed to the upstream // `{http.reverse_proxy.upstream.fails}` | The number of recent failed requests to the upstream // `{http.reverse_proxy.upstream.latency}` | How long it took the proxy upstream to write the response header. // `{http.reverse_proxy.upstream.latency_ms}` | Same as 'latency', but in milliseconds. // `{http.reverse_proxy.upstream.duration}` | Time spent proxying to the upstream, including writing response body to client. // `{http.reverse_proxy.upstream.duration_ms}` | Same as 'upstream.duration', but in milliseconds. // `{http.reverse_proxy.duration}` | Total time spent proxying, including selecting an upstream, retries, and writing response. // `{http.reverse_proxy.duration_ms}` | Same as 'duration', but in milliseconds. type Handler struct { // Configures the method of transport for the proxy. A transport // is what performs the actual "round trip" to the backend. // The default transport is plaintext HTTP. TransportRaw json.RawMessage `json:"transport,omitempty" caddy:"namespace=http.reverse_proxy.transport inline_key=protocol"` // A circuit breaker may be used to relieve pressure on a backend // that is beginning to exhibit symptoms of stress or latency. // By default, there is no circuit breaker. CBRaw json.RawMessage `json:"circuit_breaker,omitempty" caddy:"namespace=http.reverse_proxy.circuit_breakers inline_key=type"` // Load balancing distributes load/requests between backends. LoadBalancing *LoadBalancing `json:"load_balancing,omitempty"` // Health checks update the status of backends, whether they are // up or down. Down backends will not be proxied to. HealthChecks *HealthChecks `json:"health_checks,omitempty"` // Upstreams is the static list of backends to proxy to. Upstreams UpstreamPool `json:"upstreams,omitempty"` // A module for retrieving the list of upstreams dynamically. Dynamic // upstreams are retrieved at every iteration of the proxy loop for // each request (i.e. before every proxy attempt within every request). // Active health checks do not work on dynamic upstreams, and passive // health checks are only effective on dynamic upstreams if the proxy // server is busy enough that concurrent requests to the same backends // are continuous. Instead of health checks for dynamic upstreams, it // is recommended that the dynamic upstream module only return available // backends in the first place. DynamicUpstreamsRaw json.RawMessage `json:"dynamic_upstreams,omitempty" caddy:"namespace=http.reverse_proxy.upstreams inline_key=source"` // Adjusts how often to flush the response buffer. By default, // no periodic flushing is done. A negative value disables // response buffering, and flushes immediately after each // write to the client. This option is ignored when the upstream's // response is recognized as a streaming response, or if its // content length is -1; for such responses, writes are flushed // to the client immediately. // // Normally, a request will be canceled if the client disconnects // before the response is received from the backend. If explicitly // set to -1, client disconnection will be ignored and the request // will be completed to help facilitate low-latency streaming. FlushInterval caddy.Duration `json:"flush_interval,omitempty"` // A list of IP ranges (supports CIDR notation) from which // X-Forwarded-* header values should be trusted. By default, // no proxies are trusted, so existing values will be ignored // when setting these headers. If the proxy is trusted, then // existing values will be used when constructing the final // header values. TrustedProxies []string `json:"trusted_proxies,omitempty"` // Headers manipulates headers between Caddy and the backend. // By default, all headers are passed-thru without changes, // with the exceptions of special hop-by-hop headers. // // X-Forwarded-For, X-Forwarded-Proto and X-Forwarded-Host // are also set implicitly. Headers *headers.Handler `json:"headers,omitempty"` // DEPRECATED: Do not use; will be removed. See request_buffers instead. DeprecatedBufferRequests bool `json:"buffer_requests,omitempty"` // DEPRECATED: Do not use; will be removed. See response_buffers instead. DeprecatedBufferResponses bool `json:"buffer_responses,omitempty"` // DEPRECATED: Do not use; will be removed. See request_buffers and response_buffers instead. DeprecatedMaxBufferSize int64 `json:"max_buffer_size,omitempty"` // If nonzero, the entire request body up to this size will be read // and buffered in memory before being proxied to the backend. This // should be avoided if at all possible for performance reasons, but // could be useful if the backend is intolerant of read latency or // chunked encodings. RequestBuffers int64 `json:"request_buffers,omitempty"` // If nonzero, the entire response body up to this size will be read // and buffered in memory before being proxied to the client. This // should be avoided if at all possible for performance reasons, but // could be useful if the backend has tighter memory constraints. ResponseBuffers int64 `json:"response_buffers,omitempty"` // If nonzero, streaming requests such as WebSockets will be // forcibly closed at the end of the timeout. Default: no timeout. StreamTimeout caddy.Duration `json:"stream_timeout,omitempty"` // If nonzero, streaming requests such as WebSockets will not be // closed when the proxy config is unloaded, and instead the stream // will remain open until the delay is complete. In other words, // enabling this prevents streams from closing when Caddy's config // is reloaded. Enabling this may be a good idea to avoid a thundering // herd of reconnecting clients which had their connections closed // by the previous config closing. Default: no delay. StreamCloseDelay caddy.Duration `json:"stream_close_delay,omitempty"` // If configured, rewrites the copy of the upstream request. // Allows changing the request method and URI (path and query). // Since the rewrite is applied to the copy, it does not persist // past the reverse proxy handler. // If the method is changed to `GET` or `HEAD`, the request body // will not be copied to the backend. This allows a later request // handler -- either in a `handle_response` route, or after -- to // read the body. // By default, no rewrite is performed, and the method and URI // from the incoming request is used as-is for proxying. Rewrite *rewrite.Rewrite `json:"rewrite,omitempty"` // List of handlers and their associated matchers to evaluate // after successful roundtrips. The first handler that matches // the response from a backend will be invoked. The response // body from the backend will not be written to the client; // it is up to the handler to finish handling the response. // If passive health checks are enabled, any errors from the // handler chain will not affect the health status of the // backend. // // Three new placeholders are available in this handler chain: // - `{http.reverse_proxy.status_code}` The status code from the response // - `{http.reverse_proxy.status_text}` The status text from the response // - `{http.reverse_proxy.header.*}` The headers from the response HandleResponse []caddyhttp.ResponseHandler `json:"handle_response,omitempty"` Transport http.RoundTripper `json:"-"` CB CircuitBreaker `json:"-"` DynamicUpstreams UpstreamSource `json:"-"` // Holds the parsed CIDR ranges from TrustedProxies trustedProxies []netip.Prefix // Holds the named response matchers from the Caddyfile while adapting responseMatchers map[string]caddyhttp.ResponseMatcher // Holds the handle_response Caddyfile tokens while adapting handleResponseSegments []*caddyfile.Dispenser // Stores upgraded requests (hijacked connections) for proper cleanup connections map[io.ReadWriteCloser]openConnection connectionsCloseTimer *time.Timer connectionsMu *sync.Mutex ctx caddy.Context logger *zap.Logger events *caddyevents.App } // CaddyModule returns the Caddy module information. func (Handler) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.handlers.reverse_proxy", New: func() caddy.Module { return new(Handler) }, } } // Provision ensures that h is set up properly before use. func (h *Handler) Provision(ctx caddy.Context) error { eventAppIface, err := ctx.App("events") if err != nil { return fmt.Errorf("getting events app: %v", err) } h.events = eventAppIface.(*caddyevents.App) h.ctx = ctx h.logger = ctx.Logger() h.connections = make(map[io.ReadWriteCloser]openConnection) h.connectionsMu = new(sync.Mutex) // TODO: remove deprecated fields sometime after v2.6.4 if h.DeprecatedBufferRequests { h.logger.Warn("DEPRECATED: buffer_requests: this property will be removed soon; use request_buffers instead (and set a maximum buffer size)") } if h.DeprecatedBufferResponses { h.logger.Warn("DEPRECATED: buffer_responses: this property will be removed soon; use response_buffers instead (and set a maximum buffer size)") } if h.DeprecatedMaxBufferSize != 0 { h.logger.Warn("DEPRECATED: max_buffer_size: this property will be removed soon; use request_buffers and/or response_buffers instead (and set maximum buffer sizes)") } // warn about unsafe buffering config if h.RequestBuffers == -1 || h.ResponseBuffers == -1 { h.logger.Warn("UNLIMITED BUFFERING: buffering is enabled without any cap on buffer size, which can result in OOM crashes") } // start by loading modules if h.TransportRaw != nil { mod, err := ctx.LoadModule(h, "TransportRaw") if err != nil { return fmt.Errorf("loading transport: %v", err) } h.Transport = mod.(http.RoundTripper) } if h.LoadBalancing != nil && h.LoadBalancing.SelectionPolicyRaw != nil { mod, err := ctx.LoadModule(h.LoadBalancing, "SelectionPolicyRaw") if err != nil { return fmt.Errorf("loading load balancing selection policy: %s", err) } h.LoadBalancing.SelectionPolicy = mod.(Selector) } if h.CBRaw != nil { mod, err := ctx.LoadModule(h, "CBRaw") if err != nil { return fmt.Errorf("loading circuit breaker: %s", err) } h.CB = mod.(CircuitBreaker) } if h.DynamicUpstreamsRaw != nil { mod, err := ctx.LoadModule(h, "DynamicUpstreamsRaw") if err != nil { return fmt.Errorf("loading upstream source module: %v", err) } h.DynamicUpstreams = mod.(UpstreamSource) } // parse trusted proxy CIDRs ahead of time for _, str := range h.TrustedProxies { if strings.Contains(str, "/") { ipNet, err := netip.ParsePrefix(str) if err != nil { return fmt.Errorf("parsing CIDR expression: '%s': %v", str, err) } h.trustedProxies = append(h.trustedProxies, ipNet) } else { ipAddr, err := netip.ParseAddr(str) if err != nil { return fmt.Errorf("invalid IP address: '%s': %v", str, err) } ipNew := netip.PrefixFrom(ipAddr, ipAddr.BitLen()) h.trustedProxies = append(h.trustedProxies, ipNew) } } // ensure any embedded headers handler module gets provisioned // (see https://caddy.community/t/set-cookie-manipulation-in-reverse-proxy/7666?u=matt // for what happens if we forget to provision it) if h.Headers != nil { err := h.Headers.Provision(ctx) if err != nil { return fmt.Errorf("provisioning embedded headers handler: %v", err) } } if h.Rewrite != nil { err := h.Rewrite.Provision(ctx) if err != nil { return fmt.Errorf("provisioning rewrite: %v", err) } } // set up transport if h.Transport == nil { t := &HTTPTransport{} err := t.Provision(ctx) if err != nil { return fmt.Errorf("provisioning default transport: %v", err) } h.Transport = t } // set up load balancing if h.LoadBalancing == nil { h.LoadBalancing = new(LoadBalancing) } if h.LoadBalancing.SelectionPolicy == nil { h.LoadBalancing.SelectionPolicy = RandomSelection{} } if h.LoadBalancing.TryDuration > 0 && h.LoadBalancing.TryInterval == 0 { // a non-zero try_duration with a zero try_interval // will always spin the CPU for try_duration if the // upstream is local or low-latency; avoid that by // defaulting to a sane wait period between attempts h.LoadBalancing.TryInterval = caddy.Duration(250 * time.Millisecond) } lbMatcherSets, err := ctx.LoadModule(h.LoadBalancing, "RetryMatchRaw") if err != nil { return err } err = h.LoadBalancing.RetryMatch.FromInterface(lbMatcherSets) if err != nil { return err } // set up upstreams for _, u := range h.Upstreams { h.provisionUpstream(u) } if h.HealthChecks != nil { // set defaults on passive health checks, if necessary if h.HealthChecks.Passive != nil { h.HealthChecks.Passive.logger = h.logger.Named("health_checker.passive") if h.HealthChecks.Passive.FailDuration > 0 && h.HealthChecks.Passive.MaxFails == 0 { h.HealthChecks.Passive.MaxFails = 1 } } // if active health checks are enabled, configure them and start a worker if h.HealthChecks.Active != nil { err := h.HealthChecks.Active.Provision(ctx, h) if err != nil { return err } if h.HealthChecks.Active.IsEnabled() { go h.activeHealthChecker() } } } // set up any response routes for i, rh := range h.HandleResponse { err := rh.Provision(ctx) if err != nil { return fmt.Errorf("provisioning response handler %d: %v", i, err) } } upstreamHealthyUpdater := newMetricsUpstreamsHealthyUpdater(h) upstreamHealthyUpdater.Init() return nil } // Cleanup cleans up the resources made by h. func (h *Handler) Cleanup() error { err := h.cleanupConnections() // remove hosts from our config from the pool for _, upstream := range h.Upstreams { _, _ = hosts.Delete(upstream.String()) } return err } func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) // prepare the request for proxying; this is needed only once clonedReq, err := h.prepareRequest(r, repl) if err != nil { return caddyhttp.Error(http.StatusInternalServerError, fmt.Errorf("preparing request for upstream round-trip: %v", err)) } // we will need the original headers and Host value if // header operations are configured; this is so that each // retry can apply the modifications, because placeholders // may be used which depend on the selected upstream for // their values reqHost := clonedReq.Host reqHeader := clonedReq.Header start := time.Now() defer func() { // total proxying duration, including time spent on LB and retries repl.Set("http.reverse_proxy.duration", time.Since(start)) repl.Set("http.reverse_proxy.duration_ms", time.Since(start).Seconds()*1e3) // multiply seconds to preserve decimal (see #4666) }() // in the proxy loop, each iteration is an attempt to proxy the request, // and because we may retry some number of times, carry over the error // from previous tries because of the nuances of load balancing & retries var proxyErr error var retries int for { var done bool done, proxyErr = h.proxyLoopIteration(clonedReq, r, w, proxyErr, start, retries, repl, reqHeader, reqHost, next) if done { break } retries++ } if proxyErr != nil { return statusError(proxyErr) } return nil } // proxyLoopIteration implements an iteration of the proxy loop. Despite the enormous amount of local state // that has to be passed in, we brought this into its own method so that we could run defer more easily. // It returns true when the loop is done and should break; false otherwise. The error value returned should // be assigned to the proxyErr value for the next iteration of the loop (or the error handled after break). func (h *Handler) proxyLoopIteration(r *http.Request, origReq *http.Request, w http.ResponseWriter, proxyErr error, start time.Time, retries int, repl *caddy.Replacer, reqHeader http.Header, reqHost string, next caddyhttp.Handler, ) (bool, error) { // get the updated list of upstreams upstreams := h.Upstreams if h.DynamicUpstreams != nil { dUpstreams, err := h.DynamicUpstreams.GetUpstreams(r) if err != nil { h.logger.Error("failed getting dynamic upstreams; falling back to static upstreams", zap.Error(err)) } else { upstreams = dUpstreams for _, dUp := range dUpstreams { h.provisionUpstream(dUp) } h.logger.Debug("provisioned dynamic upstreams", zap.Int("count", len(dUpstreams))) defer func() { // these upstreams are dynamic, so they are only used for this iteration // of the proxy loop; be sure to let them go away when we're done with them for _, upstream := range dUpstreams { _, _ = hosts.Delete(upstream.String()) } }() } } // choose an available upstream upstream := h.LoadBalancing.SelectionPolicy.Select(upstreams, r, w) if upstream == nil { if proxyErr == nil { proxyErr = caddyhttp.Error(http.StatusServiceUnavailable, fmt.Errorf("no upstreams available")) } if !h.LoadBalancing.tryAgain(h.ctx, start, retries, proxyErr, r) { return true, proxyErr } return false, proxyErr } // the dial address may vary per-request if placeholders are // used, so perform those replacements here; the resulting // DialInfo struct should have valid network address syntax dialInfo, err := upstream.fillDialInfo(r) if err != nil { return true, fmt.Errorf("making dial info: %v", err) } h.logger.Debug("selected upstream", zap.String("dial", dialInfo.Address), zap.Int("total_upstreams", len(upstreams))) // attach to the request information about how to dial the upstream; // this is necessary because the information cannot be sufficiently // or satisfactorily represented in a URL caddyhttp.SetVar(r.Context(), dialInfoVarKey, dialInfo) // set placeholders with information about this upstream repl.Set("http.reverse_proxy.upstream.address", dialInfo.String()) repl.Set("http.reverse_proxy.upstream.hostport", dialInfo.Address) repl.Set("http.reverse_proxy.upstream.host", dialInfo.Host) repl.Set("http.reverse_proxy.upstream.port", dialInfo.Port) repl.Set("http.reverse_proxy.upstream.requests", upstream.Host.NumRequests()) repl.Set("http.reverse_proxy.upstream.max_requests", upstream.MaxRequests) repl.Set("http.reverse_proxy.upstream.fails", upstream.Host.Fails()) // mutate request headers according to this upstream; // because we're in a retry loop, we have to copy // headers (and the r.Host value) from the original // so that each retry is identical to the first if h.Headers != nil && h.Headers.Request != nil { r.Header = make(http.Header) copyHeader(r.Header, reqHeader) r.Host = reqHost h.Headers.Request.ApplyToRequest(r) } // proxy the request to that upstream proxyErr = h.reverseProxy(w, r, origReq, repl, dialInfo, next) if proxyErr == nil || errors.Is(proxyErr, context.Canceled) { // context.Canceled happens when the downstream client // cancels the request, which is not our failure return true, nil } // if the roundtrip was successful, don't retry the request or // ding the health status of the upstream (an error can still // occur after the roundtrip if, for example, a response handler // after the roundtrip returns an error) if succ, ok := proxyErr.(roundtripSucceeded); ok { return true, succ.error } // remember this failure (if enabled) h.countFailure(upstream) // if we've tried long enough, break if !h.LoadBalancing.tryAgain(h.ctx, start, retries, proxyErr, r) { return true, proxyErr } return false, proxyErr } // prepareRequest clones req so that it can be safely modified without // changing the original request or introducing data races. It then // modifies it so that it is ready to be proxied, except for directing // to a specific upstream. This method adjusts headers and other relevant // properties of the cloned request and should be done just once (before // proxying) regardless of proxy retries. This assumes that no mutations // of the cloned request are performed by h during or after proxying. func (h Handler) prepareRequest(req *http.Request, repl *caddy.Replacer) (*http.Request, error) { req = cloneRequest(req) // if enabled, perform rewrites on the cloned request; if // the method is GET or HEAD, prevent the request body // from being copied to the upstream if h.Rewrite != nil { changed := h.Rewrite.Rewrite(req, repl) if changed && (h.Rewrite.Method == "GET" || h.Rewrite.Method == "HEAD") { req.ContentLength = 0 req.Body = nil } } // if enabled, buffer client request; this should only be // enabled if the upstream requires it and does not work // with "slow clients" (gunicorn, etc.) - this obviously // has a perf overhead and makes the proxy at risk of // exhausting memory and more susceptible to slowloris // attacks, so it is strongly recommended to only use this // feature if absolutely required, if read timeouts are // set, and if body size is limited if h.RequestBuffers != 0 && req.Body != nil { req.Body, req.ContentLength = h.bufferedBody(req.Body, h.RequestBuffers) req.Header.Set("Content-Length", strconv.FormatInt(req.ContentLength, 10)) } if req.ContentLength == 0 { req.Body = nil // Issue golang/go#16036: nil Body for http.Transport retries } req.Close = false // if User-Agent is not set by client, then explicitly // disable it so it's not set to default value by std lib if _, ok := req.Header["User-Agent"]; !ok { req.Header.Set("User-Agent", "") } reqUpType := upgradeType(req.Header) removeConnectionHeaders(req.Header) // Remove hop-by-hop headers to the backend. Especially // important is "Connection" because we want a persistent // connection, regardless of what the client sent to us. // Issue golang/go#46313: don't skip if field is empty. for _, h := range hopHeaders { // Issue golang/go#21096: tell backend applications that care about trailer support // that we support trailers. (We do, but we don't go out of our way to // advertise that unless the incoming client request thought it was worth // mentioning.) if h == "Te" && httpguts.HeaderValuesContainsToken(req.Header["Te"], "trailers") { req.Header.Set("Te", "trailers") continue } req.Header.Del(h) } // After stripping all the hop-by-hop connection headers above, add back any // necessary for protocol upgrades, such as for websockets. if reqUpType != "" { req.Header.Set("Connection", "Upgrade") req.Header.Set("Upgrade", reqUpType) } // Set up the PROXY protocol info address := caddyhttp.GetVar(req.Context(), caddyhttp.ClientIPVarKey).(string) addrPort, err := netip.ParseAddrPort(address) if err != nil { // OK; probably didn't have a port addr, err := netip.ParseAddr(address) if err != nil { // Doesn't seem like a valid ip address at all } else { // Ok, only the port was missing addrPort = netip.AddrPortFrom(addr, 0) } } proxyProtocolInfo := ProxyProtocolInfo{AddrPort: addrPort} caddyhttp.SetVar(req.Context(), proxyProtocolInfoVarKey, proxyProtocolInfo) // Add the supported X-Forwarded-* headers err = h.addForwardedHeaders(req) if err != nil { return nil, err } return req, nil } // addForwardedHeaders adds the de-facto standard X-Forwarded-* // headers to the request before it is sent upstream. // // These headers are security sensitive, so care is taken to only // use existing values for these headers from the incoming request // if the client IP is trusted (i.e. coming from a trusted proxy // sitting in front of this server). If the request didn't have // the headers at all, then they will be added with the values // that we can glean from the request. func (h Handler) addForwardedHeaders(req *http.Request) error { // Parse the remote IP, ignore the error as non-fatal, // but the remote IP is required to continue, so we // just return early. This should probably never happen // though, unless some other module manipulated the request's // remote address and used an invalid value. clientIP, _, err := net.SplitHostPort(req.RemoteAddr) if err != nil { // Remove the `X-Forwarded-*` headers to avoid upstreams // potentially trusting a header that came from the client req.Header.Del("X-Forwarded-For") req.Header.Del("X-Forwarded-Proto") req.Header.Del("X-Forwarded-Host") return nil } // Client IP may contain a zone if IPv6, so we need // to pull that out before parsing the IP clientIP, _, _ = strings.Cut(clientIP, "%") ipAddr, err := netip.ParseAddr(clientIP) if err != nil { return fmt.Errorf("invalid IP address: '%s': %v", clientIP, err) } // Check if the client is a trusted proxy trusted := caddyhttp.GetVar(req.Context(), caddyhttp.TrustedProxyVarKey).(bool) for _, ipRange := range h.trustedProxies { if ipRange.Contains(ipAddr) { trusted = true break } } // If we aren't the first proxy, and the proxy is trusted, // retain prior X-Forwarded-For information as a comma+space // separated list and fold multiple headers into one. clientXFF := clientIP prior, ok, omit := allHeaderValues(req.Header, "X-Forwarded-For") if trusted && ok && prior != "" { clientXFF = prior + ", " + clientXFF } if !omit { req.Header.Set("X-Forwarded-For", clientXFF) } // Set X-Forwarded-Proto; many backend apps expect this, // so that they can properly craft URLs with the right // scheme to match the original request proto := "https" if req.TLS == nil { proto = "http" } prior, ok, omit = lastHeaderValue(req.Header, "X-Forwarded-Proto") if trusted && ok && prior != "" { proto = prior } if !omit { req.Header.Set("X-Forwarded-Proto", proto) } // Set X-Forwarded-Host; often this is redundant because // we pass through the request Host as-is, but in situations // where we proxy over HTTPS, the user may need to override // Host themselves, so it's helpful to send the original too. host := req.Host prior, ok, omit = lastHeaderValue(req.Header, "X-Forwarded-Host") if trusted && ok && prior != "" { host = prior } if !omit { req.Header.Set("X-Forwarded-Host", host) } return nil } // reverseProxy performs a round-trip to the given backend and processes the response with the client. // (This method is mostly the beginning of what was borrowed from the net/http/httputil package in the // Go standard library which was used as the foundation.) func (h *Handler) reverseProxy(rw http.ResponseWriter, req *http.Request, origReq *http.Request, repl *caddy.Replacer, di DialInfo, next caddyhttp.Handler) error { _ = di.Upstream.Host.countRequest(1) //nolint:errcheck defer di.Upstream.Host.countRequest(-1) // point the request to this upstream h.directRequest(req, di) server := req.Context().Value(caddyhttp.ServerCtxKey).(*caddyhttp.Server) shouldLogCredentials := server.Logs != nil && server.Logs.ShouldLogCredentials // Forward 1xx status codes, backported from https://github.com/golang/go/pull/53164 trace := &httptrace.ClientTrace{ Got1xxResponse: func(code int, header textproto.MIMEHeader) error { h := rw.Header() copyHeader(h, http.Header(header)) rw.WriteHeader(code) // Clear headers coming from the backend // (it's not automatically done by ResponseWriter.WriteHeader() for 1xx responses) for k := range header { delete(h, k) } return nil }, } req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace)) // if FlushInterval is explicitly configured to -1 (i.e. flush continuously to achieve // low-latency streaming), don't let the transport cancel the request if the client // disconnects: user probably wants us to finish sending the data to the upstream // regardless, and we should expect client disconnection in low-latency streaming // scenarios (see issue #4922) if h.FlushInterval == -1 { req = req.WithContext(ignoreClientGoneContext{req.Context()}) } // do the round-trip; emit debug log with values we know are // safe, or if there is no error, emit fuller log entry start := time.Now() res, err := h.Transport.RoundTrip(req) duration := time.Since(start) logger := h.logger.With( zap.String("upstream", di.Upstream.String()), zap.Duration("duration", duration), zap.Object("request", caddyhttp.LoggableHTTPRequest{ Request: req, ShouldLogCredentials: shouldLogCredentials, }), ) if err != nil { logger.Debug("upstream roundtrip", zap.Error(err)) return err } logger.Debug("upstream roundtrip", zap.Object("headers", caddyhttp.LoggableHTTPHeader{ Header: res.Header, ShouldLogCredentials: shouldLogCredentials, }), zap.Int("status", res.StatusCode)) // duration until upstream wrote response headers (roundtrip duration) repl.Set("http.reverse_proxy.upstream.latency", duration) repl.Set("http.reverse_proxy.upstream.latency_ms", duration.Seconds()*1e3) // multiply seconds to preserve decimal (see #4666) // update circuit breaker on current conditions if di.Upstream.cb != nil { di.Upstream.cb.RecordMetric(res.StatusCode, duration) } // perform passive health checks (if enabled) if h.HealthChecks != nil && h.HealthChecks.Passive != nil { // strike if the status code matches one that is "bad" for _, badStatus := range h.HealthChecks.Passive.UnhealthyStatus { if caddyhttp.StatusCodeMatches(res.StatusCode, badStatus) { h.countFailure(di.Upstream) } } // strike if the roundtrip took too long if h.HealthChecks.Passive.UnhealthyLatency > 0 && duration >= time.Duration(h.HealthChecks.Passive.UnhealthyLatency) { h.countFailure(di.Upstream) } } // if enabled, buffer the response body if h.ResponseBuffers != 0 { res.Body, _ = h.bufferedBody(res.Body, h.ResponseBuffers) } // see if any response handler is configured for this response from the backend for i, rh := range h.HandleResponse { if rh.Match != nil && !rh.Match.Match(res.StatusCode, res.Header) { continue } // if configured to only change the status code, // do that then continue regular proxy response if statusCodeStr := rh.StatusCode.String(); statusCodeStr != "" { statusCode, err := strconv.Atoi(repl.ReplaceAll(statusCodeStr, "")) if err != nil { return caddyhttp.Error(http.StatusInternalServerError, err) } if statusCode != 0 { res.StatusCode = statusCode } break } // otherwise, if there are any routes configured, execute those as the // actual response instead of what we got from the proxy backend if len(rh.Routes) == 0 { continue } // set up the replacer so that parts of the original response can be // used for routing decisions for field, value := range res.Header { repl.Set("http.reverse_proxy.header."+field, strings.Join(value, ",")) } repl.Set("http.reverse_proxy.status_code", res.StatusCode) repl.Set("http.reverse_proxy.status_text", res.Status) logger.Debug("handling response", zap.Int("handler", i)) // we make some data available via request context to child routes // so that they may inherit some options and functions from the // handler, and be able to copy the response. // we use the original request here, so that any routes from 'next' // see the original request rather than the proxy cloned request. hrc := &handleResponseContext{ handler: h, response: res, start: start, logger: logger, } ctx := origReq.Context() ctx = context.WithValue(ctx, proxyHandleResponseContextCtxKey, hrc) // pass the request through the response handler routes routeErr := rh.Routes.Compile(next).ServeHTTP(rw, origReq.WithContext(ctx)) // close the response body afterwards, since we don't need it anymore; // either a route had 'copy_response' which already consumed the body, // or some other terminal handler ran which doesn't need the response // body after that point (e.g. 'file_server' for X-Accel-Redirect flow), // or we fell through to subsequent handlers past this proxy // (e.g. forward auth's 2xx response flow). if !hrc.isFinalized { res.Body.Close() } // wrap any route error in roundtripSucceeded so caller knows that // the roundtrip was successful and to not retry if routeErr != nil { return roundtripSucceeded{routeErr} } // we're done handling the response, and we don't want to // fall through to the default finalize/copy behaviour return nil } // copy the response body and headers back to the upstream client return h.finalizeResponse(rw, req, res, repl, start, logger) } // finalizeResponse prepares and copies the response. func (h *Handler) finalizeResponse( rw http.ResponseWriter, req *http.Request, res *http.Response, repl *caddy.Replacer, start time.Time, logger *zap.Logger, ) error { // deal with 101 Switching Protocols responses: (WebSocket, h2c, etc) if res.StatusCode == http.StatusSwitchingProtocols { h.handleUpgradeResponse(logger, rw, req, res) return nil } removeConnectionHeaders(res.Header) for _, h := range hopHeaders { res.Header.Del(h) } // apply any response header operations if h.Headers != nil && h.Headers.Response != nil { if h.Headers.Response.Require == nil || h.Headers.Response.Require.Match(res.StatusCode, res.Header) { h.Headers.Response.ApplyTo(res.Header, repl) } } copyHeader(rw.Header(), res.Header) // The "Trailer" header isn't included in the Transport's response, // at least for *http.Transport. Build it up from Trailer. announcedTrailers := len(res.Trailer) if announcedTrailers > 0 { trailerKeys := make([]string, 0, len(res.Trailer)) for k := range res.Trailer { trailerKeys = append(trailerKeys, k) } rw.Header().Add("Trailer", strings.Join(trailerKeys, ", ")) } rw.WriteHeader(res.StatusCode) err := h.copyResponse(rw, res.Body, h.flushInterval(req, res)) res.Body.Close() // close now, instead of defer, to populate res.Trailer if err != nil { // we're streaming the response and we've already written headers, so // there's nothing an error handler can do to recover at this point; // the standard lib's proxy panics at this point, but we'll just log // the error and abort the stream here logger.Error("aborting with incomplete response", zap.Error(err)) return nil } if len(res.Trailer) > 0 { // Force chunking if we saw a response trailer. // This prevents net/http from calculating the length for short // bodies and adding a Content-Length. //nolint:bodyclose http.NewResponseController(rw).Flush() } // total duration spent proxying, including writing response body repl.Set("http.reverse_proxy.upstream.duration", time.Since(start)) repl.Set("http.reverse_proxy.upstream.duration_ms", time.Since(start).Seconds()*1e3) if len(res.Trailer) == announcedTrailers { copyHeader(rw.Header(), res.Trailer) return nil } for k, vv := range res.Trailer { k = http.TrailerPrefix + k for _, v := range vv { rw.Header().Add(k, v) } } return nil } // tryAgain takes the time that the handler was initially invoked, // the amount of retries already performed, as well as any error // currently obtained, and the request being tried, and returns // true if another attempt should be made at proxying the request. // If true is returned, it has already blocked long enough before // the next retry (i.e. no more sleeping is needed). If false is // returned, the handler should stop trying to proxy the request. func (lb LoadBalancing) tryAgain(ctx caddy.Context, start time.Time, retries int, proxyErr error, req *http.Request) bool { // no retries are configured if lb.TryDuration == 0 && lb.Retries == 0 { return false } // if we've tried long enough, break if lb.TryDuration > 0 && time.Since(start) >= time.Duration(lb.TryDuration) { return false } // if we've reached the retry limit, break if lb.Retries > 0 && retries >= lb.Retries { return false } // if the error occurred while dialing (i.e. a connection // could not even be established to the upstream), then it // should be safe to retry, since without a connection, no // HTTP request can be transmitted; but if the error is not // specifically a dialer error, we need to be careful if _, ok := proxyErr.(DialError); proxyErr != nil && !ok { // if the error occurred after a connection was established, // we have to assume the upstream received the request, and // retries need to be carefully decided, because some requests // are not idempotent if lb.RetryMatch == nil && req.Method != "GET" { // by default, don't retry requests if they aren't GET return false } if !lb.RetryMatch.AnyMatch(req) { return false } } // fast path; if the interval is zero, we don't need to wait if lb.TryInterval == 0 { return true } // otherwise, wait and try the next available host timer := time.NewTimer(time.Duration(lb.TryInterval)) select { case <-timer.C: return true case <-ctx.Done(): if !timer.Stop() { // if the timer has been stopped then read from the channel <-timer.C } return false } } // directRequest modifies only req.URL so that it points to the upstream // in the given DialInfo. It must modify ONLY the request URL. func (Handler) directRequest(req *http.Request, di DialInfo) { // we need a host, so set the upstream's host address reqHost := di.Address // if the port equates to the scheme, strip the port because // it's weird to make a request like http://example.com:80/. if (req.URL.Scheme == "http" && di.Port == "80") || (req.URL.Scheme == "https" && di.Port == "443") { reqHost = di.Host } req.URL.Host = reqHost } func (h Handler) provisionUpstream(upstream *Upstream) { // create or get the host representation for this upstream upstream.fillHost() // give it the circuit breaker, if any upstream.cb = h.CB // if the passive health checker has a non-zero UnhealthyRequestCount // but the upstream has no MaxRequests set (they are the same thing, // but the passive health checker is a default value for for upstreams // without MaxRequests), copy the value into this upstream, since the // value in the upstream (MaxRequests) is what is used during // availability checks if h.HealthChecks != nil && h.HealthChecks.Passive != nil && h.HealthChecks.Passive.UnhealthyRequestCount > 0 && upstream.MaxRequests == 0 { upstream.MaxRequests = h.HealthChecks.Passive.UnhealthyRequestCount } // upstreams need independent access to the passive // health check policy because passive health checks // run without access to h. if h.HealthChecks != nil { upstream.healthCheckPolicy = h.HealthChecks.Passive } } // bufferedBody reads originalBody into a buffer with maximum size of limit (-1 for unlimited), // then returns a reader for the buffer along with how many bytes were buffered. Always close // the return value when done with it, just like if it was the original body! If limit is 0 // (which it shouldn't be), this function returns its input; i.e. is a no-op, for safety. func (h Handler) bufferedBody(originalBody io.ReadCloser, limit int64) (io.ReadCloser, int64) { if limit == 0 { return originalBody, 0 } var written int64 buf := bufPool.Get().(*bytes.Buffer) buf.Reset() if limit > 0 { n, err := io.CopyN(buf, originalBody, limit) if err != nil || n == limit { return bodyReadCloser{ Reader: io.MultiReader(buf, originalBody), buf: buf, body: originalBody, }, n } } else { written, _ = io.Copy(buf, originalBody) } originalBody.Close() // no point in keeping it open return bodyReadCloser{ Reader: buf, buf: buf, }, written } // cloneRequest makes a semi-deep clone of origReq. // // Most of this code is borrowed from the Go stdlib reverse proxy, // but we make a shallow-ish clone the request (deep clone only // the headers and URL) so we can avoid manipulating the original // request when using it to proxy upstream. This prevents request // corruption and data races. func cloneRequest(origReq *http.Request) *http.Request { req := new(http.Request) *req = *origReq if origReq.URL != nil { newURL := new(url.URL) *newURL = *origReq.URL if origReq.URL.User != nil { newURL.User = new(url.Userinfo) *newURL.User = *origReq.URL.User } // sanitize the request URL; we expect it to not contain the // scheme and host since those should be determined by r.TLS // and r.Host respectively, but some clients may include it // in the request-line, which is technically valid in HTTP, // but breaks reverseproxy behaviour, overriding how the // dialer will behave. See #4237 for context. newURL.Scheme = "" newURL.Host = "" req.URL = newURL } if origReq.Header != nil { req.Header = origReq.Header.Clone() } if origReq.Trailer != nil { req.Trailer = origReq.Trailer.Clone() } return req } func copyHeader(dst, src http.Header) { for k, vv := range src { for _, v := range vv { dst.Add(k, v) } } } // allHeaderValues gets all values for a given header field, // joined by a comma and space if more than one is set. If the // header field is nil, then the omit is true, meaning some // earlier logic in the server wanted to prevent this header from // getting written at all. If the header is empty, then ok is // false. Callers should still check that the value is not empty // (the header field may be set but have an empty value). func allHeaderValues(h http.Header, field string) (value string, ok bool, omit bool) { values, ok := h[http.CanonicalHeaderKey(field)] if ok && values == nil { return "", true, true } if len(values) == 0 { return "", false, false } return strings.Join(values, ", "), true, false } // lastHeaderValue gets the last value for a given header field // if more than one is set. If the header field is nil, then // the omit is true, meaning some earlier logic in the server // wanted to prevent this header from getting written at all. // If the header is empty, then ok is false. Callers should // still check that the value is not empty (the header field // may be set but have an empty value). func lastHeaderValue(h http.Header, field string) (value string, ok bool, omit bool) { values, ok := h[http.CanonicalHeaderKey(field)] if ok && values == nil { return "", true, true } if len(values) == 0 { return "", false, false } return values[len(values)-1], true, false } func upgradeType(h http.Header) string { if !httpguts.HeaderValuesContainsToken(h["Connection"], "Upgrade") { return "" } return strings.ToLower(h.Get("Upgrade")) } // removeConnectionHeaders removes hop-by-hop headers listed in the "Connection" header of h. // See RFC 7230, section 6.1 func removeConnectionHeaders(h http.Header) { for _, f := range h["Connection"] { for _, sf := range strings.Split(f, ",") { if sf = textproto.TrimString(sf); sf != "" { h.Del(sf) } } } } // statusError returns an error value that has a status code. func statusError(err error) error { // errors proxying usually mean there is a problem with the upstream(s) statusCode := http.StatusBadGateway // timeout errors have a standard status code (see issue #4823) if err, ok := err.(net.Error); ok && err.Timeout() { statusCode = http.StatusGatewayTimeout } // if the client canceled the request (usually this means they closed // the connection, so they won't see any response), we can report it // as a client error (4xx) and not a server error (5xx); unfortunately // the Go standard library, at least at time of writing in late 2020, // obnoxiously wraps the exported, standard context.Canceled error with // an unexported garbage value that we have to do a substring check for: // https://github.com/golang/go/blob/6965b01ea248cabb70c3749fd218b36089a21efb/src/net/net.go#L416-L430 if errors.Is(err, context.Canceled) || strings.Contains(err.Error(), "operation was canceled") { // regrettably, there is no standard error code for "client closed connection", but // for historical reasons we can use a code that a lot of people are already using; // using 5xx is problematic for users; see #3748 statusCode = 499 } return caddyhttp.Error(statusCode, err) } // LoadBalancing has parameters related to load balancing. type LoadBalancing struct { // A selection policy is how to choose an available backend. // The default policy is random selection. SelectionPolicyRaw json.RawMessage `json:"selection_policy,omitempty" caddy:"namespace=http.reverse_proxy.selection_policies inline_key=policy"` // How many times to retry selecting available backends for each // request if the next available host is down. If try_duration is // also configured, then retries may stop early if the duration // is reached. By default, retries are disabled (zero). Retries int `json:"retries,omitempty"` // How long to try selecting available backends for each request // if the next available host is down. Clients will wait for up // to this long while the load balancer tries to find an available // upstream host. If retries is also configured, tries may stop // early if the maximum retries is reached. By default, retries // are disabled (zero duration). TryDuration caddy.Duration `json:"try_duration,omitempty"` // How long to wait between selecting the next host from the pool. // Default is 250ms if try_duration is enabled, otherwise zero. Only // relevant when a request to an upstream host fails. Be aware that // setting this to 0 with a non-zero try_duration can cause the CPU // to spin if all backends are down and latency is very low. TryInterval caddy.Duration `json:"try_interval,omitempty"` // A list of matcher sets that restricts with which requests retries are // allowed. A request must match any of the given matcher sets in order // to be retried if the connection to the upstream succeeded but the // subsequent round-trip failed. If the connection to the upstream failed, // a retry is always allowed. If unspecified, only GET requests will be // allowed to be retried. Note that a retry is done with the next available // host according to the load balancing policy. RetryMatchRaw caddyhttp.RawMatcherSets `json:"retry_match,omitempty" caddy:"namespace=http.matchers"` SelectionPolicy Selector `json:"-"` RetryMatch caddyhttp.MatcherSets `json:"-"` } // Selector selects an available upstream from the pool. type Selector interface { Select(UpstreamPool, *http.Request, http.ResponseWriter) *Upstream } // UpstreamSource gets the list of upstreams that can be used when // proxying a request. Returned upstreams will be load balanced and // health-checked. This should be a very fast function -- instant // if possible -- and the return value must be as stable as possible. // In other words, the list of upstreams should ideally not change much // across successive calls. If the list of upstreams changes or the // ordering is not stable, load balancing will suffer. This function // may be called during each retry, multiple times per request, and as // such, needs to be instantaneous. The returned slice will not be // modified. type UpstreamSource interface { GetUpstreams(*http.Request) ([]*Upstream, error) } // Hop-by-hop headers. These are removed when sent to the backend. // As of RFC 7230, hop-by-hop headers are required to appear in the // Connection header field. These are the headers defined by the // obsoleted RFC 2616 (section 13.5.1) and are used for backward // compatibility. var hopHeaders = []string{ "Alt-Svc", "Connection", "Proxy-Connection", // non-standard but still sent by libcurl and rejected by e.g. google "Keep-Alive", "Proxy-Authenticate", "Proxy-Authorization", "Te", // canonicalized version of "TE" "Trailer", // not Trailers per URL above; https://www.rfc-editor.org/errata_search.php?eid=4522 "Transfer-Encoding", "Upgrade", } // DialError is an error that specifically occurs // in a call to Dial or DialContext. type DialError struct{ error } // TLSTransport is implemented by transports // that are capable of using TLS. type TLSTransport interface { // TLSEnabled returns true if the transport // has TLS enabled, false otherwise. TLSEnabled() bool // EnableTLS enables TLS within the transport // if it is not already, using the provided // value as a basis for the TLS config. EnableTLS(base *TLSConfig) error } // roundtripSucceeded is an error type that is returned if the // roundtrip succeeded, but an error occurred after-the-fact. type roundtripSucceeded struct{ error } // bodyReadCloser is a reader that, upon closing, will return // its buffer to the pool and close the underlying body reader. type bodyReadCloser struct { io.Reader buf *bytes.Buffer body io.ReadCloser } func (brc bodyReadCloser) Close() error { bufPool.Put(brc.buf) if brc.body != nil { return brc.body.Close() } return nil } // bufPool is used for buffering requests and responses. var bufPool = sync.Pool{ New: func() any { return new(bytes.Buffer) }, } // handleResponseContext carries some contextual information about the // current proxy handling. type handleResponseContext struct { // handler is the active proxy handler instance, so that // routes like copy_response may inherit some config // options and have access to handler methods. handler *Handler // response is the actual response received from the proxy // roundtrip, to potentially be copied if a copy_response // handler is in the handle_response routes. response *http.Response // start is the time just before the proxy roundtrip was // performed, used for logging. start time.Time // logger is the prepared logger which is used to write logs // with the request, duration, and selected upstream attached. logger *zap.Logger // isFinalized is whether the response has been finalized, // i.e. copied and closed, to make sure that it doesn't // happen twice. isFinalized bool } // ignoreClientGoneContext is a special context.Context type // intended for use when doing a RoundTrip where you don't // want a client disconnection to cancel the request during // the roundtrip. // This context clears cancellation, error, and deadline methods, // but still allows values to pass through from its embedded // context. // // TODO: This can be replaced with context.WithoutCancel once // the minimum required version of Go is 1.21. type ignoreClientGoneContext struct { context.Context } func (c ignoreClientGoneContext) Deadline() (deadline time.Time, ok bool) { return } func (c ignoreClientGoneContext) Done() <-chan struct{} { return nil } func (c ignoreClientGoneContext) Err() error { return nil } // proxyHandleResponseContextCtxKey is the context key for the active proxy handler // so that handle_response routes can inherit some config options // from the proxy handler. const proxyHandleResponseContextCtxKey caddy.CtxKey = "reverse_proxy_handle_response_context" // Interface guards var ( _ caddy.Provisioner = (*Handler)(nil) _ caddy.CleanerUpper = (*Handler)(nil) _ caddyhttp.MiddlewareHandler = (*Handler)(nil) )
Go
caddy/modules/caddyhttp/reverseproxy/selectionpolicies.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package reverseproxy import ( "crypto/hmac" "crypto/sha256" "encoding/hex" "encoding/json" "fmt" "hash/fnv" weakrand "math/rand" "net" "net/http" "strconv" "strings" "sync/atomic" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func init() { caddy.RegisterModule(RandomSelection{}) caddy.RegisterModule(RandomChoiceSelection{}) caddy.RegisterModule(LeastConnSelection{}) caddy.RegisterModule(RoundRobinSelection{}) caddy.RegisterModule(WeightedRoundRobinSelection{}) caddy.RegisterModule(FirstSelection{}) caddy.RegisterModule(IPHashSelection{}) caddy.RegisterModule(ClientIPHashSelection{}) caddy.RegisterModule(URIHashSelection{}) caddy.RegisterModule(QueryHashSelection{}) caddy.RegisterModule(HeaderHashSelection{}) caddy.RegisterModule(CookieHashSelection{}) } // RandomSelection is a policy that selects // an available host at random. type RandomSelection struct{} // CaddyModule returns the Caddy module information. func (RandomSelection) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.reverse_proxy.selection_policies.random", New: func() caddy.Module { return new(RandomSelection) }, } } // Select returns an available host, if any. func (r RandomSelection) Select(pool UpstreamPool, request *http.Request, _ http.ResponseWriter) *Upstream { return selectRandomHost(pool) } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. func (r *RandomSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { if d.NextArg() { return d.ArgErr() } } return nil } // WeightedRoundRobinSelection is a policy that selects // a host based on weighted round-robin ordering. type WeightedRoundRobinSelection struct { // The weight of each upstream in order, // corresponding with the list of upstreams configured. Weights []int `json:"weights,omitempty"` index uint32 totalWeight int } // CaddyModule returns the Caddy module information. func (WeightedRoundRobinSelection) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.reverse_proxy.selection_policies.weighted_round_robin", New: func() caddy.Module { return new(WeightedRoundRobinSelection) }, } } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. func (r *WeightedRoundRobinSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { args := d.RemainingArgs() if len(args) == 0 { return d.ArgErr() } for _, weight := range args { weightInt, err := strconv.Atoi(weight) if err != nil { return d.Errf("invalid weight value '%s': %v", weight, err) } if weightInt < 1 { return d.Errf("invalid weight value '%s': weight should be non-zero and positive", weight) } r.Weights = append(r.Weights, weightInt) } } return nil } // Provision sets up r. func (r *WeightedRoundRobinSelection) Provision(ctx caddy.Context) error { for _, weight := range r.Weights { r.totalWeight += weight } return nil } // Select returns an available host, if any. func (r *WeightedRoundRobinSelection) Select(pool UpstreamPool, _ *http.Request, _ http.ResponseWriter) *Upstream { if len(pool) == 0 { return nil } if len(r.Weights) < 2 { return pool[0] } var index, totalWeight int currentWeight := int(atomic.AddUint32(&r.index, 1)) % r.totalWeight for i, weight := range r.Weights { totalWeight += weight if currentWeight < totalWeight { index = i break } } upstreams := make([]*Upstream, 0, len(r.Weights)) for _, upstream := range pool { if !upstream.Available() { continue } upstreams = append(upstreams, upstream) if len(upstreams) == cap(upstreams) { break } } if len(upstreams) == 0 { return nil } return upstreams[index%len(upstreams)] } // RandomChoiceSelection is a policy that selects // two or more available hosts at random, then // chooses the one with the least load. type RandomChoiceSelection struct { // The size of the sub-pool created from the larger upstream pool. The default value // is 2 and the maximum at selection time is the size of the upstream pool. Choose int `json:"choose,omitempty"` } // CaddyModule returns the Caddy module information. func (RandomChoiceSelection) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.reverse_proxy.selection_policies.random_choose", New: func() caddy.Module { return new(RandomChoiceSelection) }, } } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. func (r *RandomChoiceSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { if !d.NextArg() { return d.ArgErr() } chooseStr := d.Val() choose, err := strconv.Atoi(chooseStr) if err != nil { return d.Errf("invalid choice value '%s': %v", chooseStr, err) } r.Choose = choose } return nil } // Provision sets up r. func (r *RandomChoiceSelection) Provision(ctx caddy.Context) error { if r.Choose == 0 { r.Choose = 2 } return nil } // Validate ensures that r's configuration is valid. func (r RandomChoiceSelection) Validate() error { if r.Choose < 2 { return fmt.Errorf("choose must be at least 2") } return nil } // Select returns an available host, if any. func (r RandomChoiceSelection) Select(pool UpstreamPool, _ *http.Request, _ http.ResponseWriter) *Upstream { k := r.Choose if k > len(pool) { k = len(pool) } choices := make([]*Upstream, k) for i, upstream := range pool { if !upstream.Available() { continue } j := weakrand.Intn(i + 1) //nolint:gosec if j < k { choices[j] = upstream } } return leastRequests(choices) } // LeastConnSelection is a policy that selects the // host with the least active requests. If multiple // hosts have the same fewest number, one is chosen // randomly. The term "conn" or "connection" is used // in this policy name due to its similar meaning in // other software, but our load balancer actually // counts active requests rather than connections, // since these days requests are multiplexed onto // shared connections. type LeastConnSelection struct{} // CaddyModule returns the Caddy module information. func (LeastConnSelection) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.reverse_proxy.selection_policies.least_conn", New: func() caddy.Module { return new(LeastConnSelection) }, } } // Select selects the up host with the least number of connections in the // pool. If more than one host has the same least number of connections, // one of the hosts is chosen at random. func (LeastConnSelection) Select(pool UpstreamPool, _ *http.Request, _ http.ResponseWriter) *Upstream { var bestHost *Upstream var count int leastReqs := -1 for _, host := range pool { if !host.Available() { continue } numReqs := host.NumRequests() if leastReqs == -1 || numReqs < leastReqs { leastReqs = numReqs count = 0 } // among hosts with same least connections, perform a reservoir // sample: https://en.wikipedia.org/wiki/Reservoir_sampling if numReqs == leastReqs { count++ if count > 1 || (weakrand.Int()%count) == 0 { //nolint:gosec bestHost = host } } } return bestHost } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. func (r *LeastConnSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { if d.NextArg() { return d.ArgErr() } } return nil } // RoundRobinSelection is a policy that selects // a host based on round-robin ordering. type RoundRobinSelection struct { robin uint32 } // CaddyModule returns the Caddy module information. func (RoundRobinSelection) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.reverse_proxy.selection_policies.round_robin", New: func() caddy.Module { return new(RoundRobinSelection) }, } } // Select returns an available host, if any. func (r *RoundRobinSelection) Select(pool UpstreamPool, _ *http.Request, _ http.ResponseWriter) *Upstream { n := uint32(len(pool)) if n == 0 { return nil } for i := uint32(0); i < n; i++ { robin := atomic.AddUint32(&r.robin, 1) host := pool[robin%n] if host.Available() { return host } } return nil } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. func (r *RoundRobinSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { if d.NextArg() { return d.ArgErr() } } return nil } // FirstSelection is a policy that selects // the first available host. type FirstSelection struct{} // CaddyModule returns the Caddy module information. func (FirstSelection) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.reverse_proxy.selection_policies.first", New: func() caddy.Module { return new(FirstSelection) }, } } // Select returns an available host, if any. func (FirstSelection) Select(pool UpstreamPool, _ *http.Request, _ http.ResponseWriter) *Upstream { for _, host := range pool { if host.Available() { return host } } return nil } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. func (r *FirstSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { if d.NextArg() { return d.ArgErr() } } return nil } // IPHashSelection is a policy that selects a host // based on hashing the remote IP of the request. type IPHashSelection struct{} // CaddyModule returns the Caddy module information. func (IPHashSelection) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.reverse_proxy.selection_policies.ip_hash", New: func() caddy.Module { return new(IPHashSelection) }, } } // Select returns an available host, if any. func (IPHashSelection) Select(pool UpstreamPool, req *http.Request, _ http.ResponseWriter) *Upstream { clientIP, _, err := net.SplitHostPort(req.RemoteAddr) if err != nil { clientIP = req.RemoteAddr } return hostByHashing(pool, clientIP) } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. func (r *IPHashSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { if d.NextArg() { return d.ArgErr() } } return nil } // ClientIPHashSelection is a policy that selects a host // based on hashing the client IP of the request, as determined // by the HTTP app's trusted proxies settings. type ClientIPHashSelection struct{} // CaddyModule returns the Caddy module information. func (ClientIPHashSelection) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.reverse_proxy.selection_policies.client_ip_hash", New: func() caddy.Module { return new(ClientIPHashSelection) }, } } // Select returns an available host, if any. func (ClientIPHashSelection) Select(pool UpstreamPool, req *http.Request, _ http.ResponseWriter) *Upstream { address := caddyhttp.GetVar(req.Context(), caddyhttp.ClientIPVarKey).(string) clientIP, _, err := net.SplitHostPort(address) if err != nil { clientIP = address // no port } return hostByHashing(pool, clientIP) } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. func (r *ClientIPHashSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { if d.NextArg() { return d.ArgErr() } } return nil } // URIHashSelection is a policy that selects a // host by hashing the request URI. type URIHashSelection struct{} // CaddyModule returns the Caddy module information. func (URIHashSelection) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.reverse_proxy.selection_policies.uri_hash", New: func() caddy.Module { return new(URIHashSelection) }, } } // Select returns an available host, if any. func (URIHashSelection) Select(pool UpstreamPool, req *http.Request, _ http.ResponseWriter) *Upstream { return hostByHashing(pool, req.RequestURI) } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. func (r *URIHashSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { if d.NextArg() { return d.ArgErr() } } return nil } // QueryHashSelection is a policy that selects // a host based on a given request query parameter. type QueryHashSelection struct { // The query key whose value is to be hashed and used for upstream selection. Key string `json:"key,omitempty"` // The fallback policy to use if the query key is not present. Defaults to `random`. FallbackRaw json.RawMessage `json:"fallback,omitempty" caddy:"namespace=http.reverse_proxy.selection_policies inline_key=policy"` fallback Selector } // CaddyModule returns the Caddy module information. func (QueryHashSelection) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.reverse_proxy.selection_policies.query", New: func() caddy.Module { return new(QueryHashSelection) }, } } // Provision sets up the module. func (s *QueryHashSelection) Provision(ctx caddy.Context) error { if s.Key == "" { return fmt.Errorf("query key is required") } if s.FallbackRaw == nil { s.FallbackRaw = caddyconfig.JSONModuleObject(RandomSelection{}, "policy", "random", nil) } mod, err := ctx.LoadModule(s, "FallbackRaw") if err != nil { return fmt.Errorf("loading fallback selection policy: %s", err) } s.fallback = mod.(Selector) return nil } // Select returns an available host, if any. func (s QueryHashSelection) Select(pool UpstreamPool, req *http.Request, _ http.ResponseWriter) *Upstream { // Since the query may have multiple values for the same key, // we'll join them to avoid a problem where the user can control // the upstream that the request goes to by sending multiple values // for the same key, when the upstream only considers the first value. // Keep in mind that a client changing the order of the values may // affect which upstream is selected, but this is a semantically // different request, because the order of the values is significant. vals := strings.Join(req.URL.Query()[s.Key], ",") if vals == "" { return s.fallback.Select(pool, req, nil) } return hostByHashing(pool, vals) } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. func (s *QueryHashSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { if !d.NextArg() { return d.ArgErr() } s.Key = d.Val() } for nesting := d.Nesting(); d.NextBlock(nesting); { switch d.Val() { case "fallback": if !d.NextArg() { return d.ArgErr() } if s.FallbackRaw != nil { return d.Err("fallback selection policy already specified") } mod, err := loadFallbackPolicy(d) if err != nil { return err } s.FallbackRaw = mod default: return d.Errf("unrecognized option '%s'", d.Val()) } } return nil } // HeaderHashSelection is a policy that selects // a host based on a given request header. type HeaderHashSelection struct { // The HTTP header field whose value is to be hashed and used for upstream selection. Field string `json:"field,omitempty"` // The fallback policy to use if the header is not present. Defaults to `random`. FallbackRaw json.RawMessage `json:"fallback,omitempty" caddy:"namespace=http.reverse_proxy.selection_policies inline_key=policy"` fallback Selector } // CaddyModule returns the Caddy module information. func (HeaderHashSelection) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.reverse_proxy.selection_policies.header", New: func() caddy.Module { return new(HeaderHashSelection) }, } } // Provision sets up the module. func (s *HeaderHashSelection) Provision(ctx caddy.Context) error { if s.Field == "" { return fmt.Errorf("header field is required") } if s.FallbackRaw == nil { s.FallbackRaw = caddyconfig.JSONModuleObject(RandomSelection{}, "policy", "random", nil) } mod, err := ctx.LoadModule(s, "FallbackRaw") if err != nil { return fmt.Errorf("loading fallback selection policy: %s", err) } s.fallback = mod.(Selector) return nil } // Select returns an available host, if any. func (s HeaderHashSelection) Select(pool UpstreamPool, req *http.Request, _ http.ResponseWriter) *Upstream { // The Host header should be obtained from the req.Host field // since net/http removes it from the header map. if s.Field == "Host" && req.Host != "" { return hostByHashing(pool, req.Host) } val := req.Header.Get(s.Field) if val == "" { return s.fallback.Select(pool, req, nil) } return hostByHashing(pool, val) } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. func (s *HeaderHashSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { if !d.NextArg() { return d.ArgErr() } s.Field = d.Val() } for nesting := d.Nesting(); d.NextBlock(nesting); { switch d.Val() { case "fallback": if !d.NextArg() { return d.ArgErr() } if s.FallbackRaw != nil { return d.Err("fallback selection policy already specified") } mod, err := loadFallbackPolicy(d) if err != nil { return err } s.FallbackRaw = mod default: return d.Errf("unrecognized option '%s'", d.Val()) } } return nil } // CookieHashSelection is a policy that selects // a host based on a given cookie name. type CookieHashSelection struct { // The HTTP cookie name whose value is to be hashed and used for upstream selection. Name string `json:"name,omitempty"` // Secret to hash (Hmac256) chosen upstream in cookie Secret string `json:"secret,omitempty"` // The fallback policy to use if the cookie is not present. Defaults to `random`. FallbackRaw json.RawMessage `json:"fallback,omitempty" caddy:"namespace=http.reverse_proxy.selection_policies inline_key=policy"` fallback Selector } // CaddyModule returns the Caddy module information. func (CookieHashSelection) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.reverse_proxy.selection_policies.cookie", New: func() caddy.Module { return new(CookieHashSelection) }, } } // Provision sets up the module. func (s *CookieHashSelection) Provision(ctx caddy.Context) error { if s.Name == "" { s.Name = "lb" } if s.FallbackRaw == nil { s.FallbackRaw = caddyconfig.JSONModuleObject(RandomSelection{}, "policy", "random", nil) } mod, err := ctx.LoadModule(s, "FallbackRaw") if err != nil { return fmt.Errorf("loading fallback selection policy: %s", err) } s.fallback = mod.(Selector) return nil } // Select returns an available host, if any. func (s CookieHashSelection) Select(pool UpstreamPool, req *http.Request, w http.ResponseWriter) *Upstream { // selects a new Host using the fallback policy (typically random) // and write a sticky session cookie to the response. selectNewHost := func() *Upstream { upstream := s.fallback.Select(pool, req, w) if upstream == nil { return nil } sha, err := hashCookie(s.Secret, upstream.Dial) if err != nil { return upstream } http.SetCookie(w, &http.Cookie{ Name: s.Name, Value: sha, Path: "/", Secure: false, }) return upstream } cookie, err := req.Cookie(s.Name) // If there's no cookie, select a host using the fallback policy if err != nil || cookie == nil { return selectNewHost() } // If the cookie is present, loop over the available upstreams until we find a match cookieValue := cookie.Value for _, upstream := range pool { if !upstream.Available() { continue } sha, err := hashCookie(s.Secret, upstream.Dial) if err == nil && sha == cookieValue { return upstream } } // If there is no matching host, select a host using the fallback policy return selectNewHost() } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. Syntax: // // lb_policy cookie [<name> [<secret>]] { // fallback <policy> // } // // By default name is `lb` func (s *CookieHashSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { args := d.RemainingArgs() switch len(args) { case 1: case 2: s.Name = args[1] case 3: s.Name = args[1] s.Secret = args[2] default: return d.ArgErr() } for nesting := d.Nesting(); d.NextBlock(nesting); { switch d.Val() { case "fallback": if !d.NextArg() { return d.ArgErr() } if s.FallbackRaw != nil { return d.Err("fallback selection policy already specified") } mod, err := loadFallbackPolicy(d) if err != nil { return err } s.FallbackRaw = mod default: return d.Errf("unrecognized option '%s'", d.Val()) } } return nil } // hashCookie hashes (HMAC 256) some data with the secret func hashCookie(secret string, data string) (string, error) { h := hmac.New(sha256.New, []byte(secret)) _, err := h.Write([]byte(data)) if err != nil { return "", err } return hex.EncodeToString(h.Sum(nil)), nil } // selectRandomHost returns a random available host func selectRandomHost(pool []*Upstream) *Upstream { // use reservoir sampling because the number of available // hosts isn't known: https://en.wikipedia.org/wiki/Reservoir_sampling var randomHost *Upstream var count int for _, upstream := range pool { if !upstream.Available() { continue } // (n % 1 == 0) holds for all n, therefore a // upstream will always be chosen if there is at // least one available count++ if (weakrand.Int() % count) == 0 { //nolint:gosec randomHost = upstream } } return randomHost } // leastRequests returns the host with the // least number of active requests to it. // If more than one host has the same // least number of active requests, then // one of those is chosen at random. func leastRequests(upstreams []*Upstream) *Upstream { if len(upstreams) == 0 { return nil } var best []*Upstream var bestReqs int = -1 for _, upstream := range upstreams { if upstream == nil { continue } reqs := upstream.NumRequests() if reqs == 0 { return upstream } // If bestReqs was just initialized to -1 // we need to append upstream also if reqs <= bestReqs || bestReqs == -1 { bestReqs = reqs best = append(best, upstream) } } if len(best) == 0 { return nil } if len(best) == 1 { return best[0] } return best[weakrand.Intn(len(best))] //nolint:gosec } // hostByHashing returns an available host from pool based on a hashable string s. func hostByHashing(pool []*Upstream, s string) *Upstream { // Highest Random Weight (HRW, or "Rendezvous") hashing, // guarantees stability when the list of upstreams changes; // see https://medium.com/i0exception/rendezvous-hashing-8c00e2fb58b0, // https://randorithms.com/2020/12/26/rendezvous-hashing.html, // and https://en.wikipedia.org/wiki/Rendezvous_hashing. var highestHash uint32 var upstream *Upstream for _, up := range pool { if !up.Available() { continue } h := hash(up.String() + s) // important to hash key and server together if h > highestHash { highestHash = h upstream = up } } return upstream } // hash calculates a fast hash based on s. func hash(s string) uint32 { h := fnv.New32a() _, _ = h.Write([]byte(s)) return h.Sum32() } func loadFallbackPolicy(d *caddyfile.Dispenser) (json.RawMessage, error) { name := d.Val() modID := "http.reverse_proxy.selection_policies." + name unm, err := caddyfile.UnmarshalModule(d, modID) if err != nil { return nil, err } sel, ok := unm.(Selector) if !ok { return nil, d.Errf("module %s (%T) is not a reverseproxy.Selector", modID, unm) } return caddyconfig.JSONModuleObject(sel, "policy", name, nil), nil } // Interface guards var ( _ Selector = (*RandomSelection)(nil) _ Selector = (*RandomChoiceSelection)(nil) _ Selector = (*LeastConnSelection)(nil) _ Selector = (*RoundRobinSelection)(nil) _ Selector = (*WeightedRoundRobinSelection)(nil) _ Selector = (*FirstSelection)(nil) _ Selector = (*IPHashSelection)(nil) _ Selector = (*ClientIPHashSelection)(nil) _ Selector = (*URIHashSelection)(nil) _ Selector = (*QueryHashSelection)(nil) _ Selector = (*HeaderHashSelection)(nil) _ Selector = (*CookieHashSelection)(nil) _ caddy.Validator = (*RandomChoiceSelection)(nil) _ caddy.Provisioner = (*RandomChoiceSelection)(nil) _ caddy.Provisioner = (*WeightedRoundRobinSelection)(nil) _ caddyfile.Unmarshaler = (*RandomChoiceSelection)(nil) _ caddyfile.Unmarshaler = (*WeightedRoundRobinSelection)(nil) )
Go
caddy/modules/caddyhttp/reverseproxy/selectionpolicies_test.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package reverseproxy import ( "context" "net/http" "net/http/httptest" "testing" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func testPool() UpstreamPool { return UpstreamPool{ {Host: new(Host), Dial: "0.0.0.1"}, {Host: new(Host), Dial: "0.0.0.2"}, {Host: new(Host), Dial: "0.0.0.3"}, } } func TestRoundRobinPolicy(t *testing.T) { pool := testPool() rrPolicy := RoundRobinSelection{} req, _ := http.NewRequest("GET", "/", nil) h := rrPolicy.Select(pool, req, nil) // First selected host is 1, because counter starts at 0 // and increments before host is selected if h != pool[1] { t.Error("Expected first round robin host to be second host in the pool.") } h = rrPolicy.Select(pool, req, nil) if h != pool[2] { t.Error("Expected second round robin host to be third host in the pool.") } h = rrPolicy.Select(pool, req, nil) if h != pool[0] { t.Error("Expected third round robin host to be first host in the pool.") } // mark host as down pool[1].setHealthy(false) h = rrPolicy.Select(pool, req, nil) if h != pool[2] { t.Error("Expected to skip down host.") } // mark host as up pool[1].setHealthy(true) h = rrPolicy.Select(pool, req, nil) if h == pool[2] { t.Error("Expected to balance evenly among healthy hosts") } // mark host as full pool[1].countRequest(1) pool[1].MaxRequests = 1 h = rrPolicy.Select(pool, req, nil) if h != pool[2] { t.Error("Expected to skip full host.") } } func TestWeightedRoundRobinPolicy(t *testing.T) { pool := testPool() wrrPolicy := WeightedRoundRobinSelection{ Weights: []int{3, 2, 1}, totalWeight: 6, } req, _ := http.NewRequest("GET", "/", nil) h := wrrPolicy.Select(pool, req, nil) if h != pool[0] { t.Error("Expected first weighted round robin host to be first host in the pool.") } h = wrrPolicy.Select(pool, req, nil) if h != pool[0] { t.Error("Expected second weighted round robin host to be first host in the pool.") } // Third selected host is 1, because counter starts at 0 // and increments before host is selected h = wrrPolicy.Select(pool, req, nil) if h != pool[1] { t.Error("Expected third weighted round robin host to be second host in the pool.") } h = wrrPolicy.Select(pool, req, nil) if h != pool[1] { t.Error("Expected fourth weighted round robin host to be second host in the pool.") } h = wrrPolicy.Select(pool, req, nil) if h != pool[2] { t.Error("Expected fifth weighted round robin host to be third host in the pool.") } h = wrrPolicy.Select(pool, req, nil) if h != pool[0] { t.Error("Expected sixth weighted round robin host to be first host in the pool.") } // mark host as down pool[0].setHealthy(false) h = wrrPolicy.Select(pool, req, nil) if h != pool[1] { t.Error("Expected to skip down host.") } // mark host as up pool[0].setHealthy(true) h = wrrPolicy.Select(pool, req, nil) if h != pool[0] { t.Error("Expected to select first host on availablity.") } // mark host as full pool[1].countRequest(1) pool[1].MaxRequests = 1 h = wrrPolicy.Select(pool, req, nil) if h != pool[2] { t.Error("Expected to skip full host.") } } func TestLeastConnPolicy(t *testing.T) { pool := testPool() lcPolicy := LeastConnSelection{} req, _ := http.NewRequest("GET", "/", nil) pool[0].countRequest(10) pool[1].countRequest(10) h := lcPolicy.Select(pool, req, nil) if h != pool[2] { t.Error("Expected least connection host to be third host.") } pool[2].countRequest(100) h = lcPolicy.Select(pool, req, nil) if h != pool[0] && h != pool[1] { t.Error("Expected least connection host to be first or second host.") } } func TestIPHashPolicy(t *testing.T) { pool := testPool() ipHash := IPHashSelection{} req, _ := http.NewRequest("GET", "/", nil) // We should be able to predict where every request is routed. req.RemoteAddr = "172.0.0.1:80" h := ipHash.Select(pool, req, nil) if h != pool[1] { t.Error("Expected ip hash policy host to be the second host.") } req.RemoteAddr = "172.0.0.2:80" h = ipHash.Select(pool, req, nil) if h != pool[1] { t.Error("Expected ip hash policy host to be the second host.") } req.RemoteAddr = "172.0.0.3:80" h = ipHash.Select(pool, req, nil) if h != pool[1] { t.Error("Expected ip hash policy host to be the second host.") } req.RemoteAddr = "172.0.0.4:80" h = ipHash.Select(pool, req, nil) if h != pool[1] { t.Error("Expected ip hash policy host to be the second host.") } // we should get the same results without a port req.RemoteAddr = "172.0.0.1" h = ipHash.Select(pool, req, nil) if h != pool[1] { t.Error("Expected ip hash policy host to be the second host.") } req.RemoteAddr = "172.0.0.2" h = ipHash.Select(pool, req, nil) if h != pool[1] { t.Error("Expected ip hash policy host to be the second host.") } req.RemoteAddr = "172.0.0.3" h = ipHash.Select(pool, req, nil) if h != pool[1] { t.Error("Expected ip hash policy host to be the second host.") } req.RemoteAddr = "172.0.0.4" h = ipHash.Select(pool, req, nil) if h != pool[1] { t.Error("Expected ip hash policy host to be the second host.") } // we should get a healthy host if the original host is unhealthy and a // healthy host is available req.RemoteAddr = "172.0.0.4" pool[1].setHealthy(false) h = ipHash.Select(pool, req, nil) if h != pool[0] { t.Error("Expected ip hash policy host to be the first host.") } req.RemoteAddr = "172.0.0.2" h = ipHash.Select(pool, req, nil) if h != pool[0] { t.Error("Expected ip hash policy host to be the first host.") } pool[1].setHealthy(true) req.RemoteAddr = "172.0.0.3" pool[2].setHealthy(false) h = ipHash.Select(pool, req, nil) if h != pool[1] { t.Error("Expected ip hash policy host to be the second host.") } req.RemoteAddr = "172.0.0.4" h = ipHash.Select(pool, req, nil) if h != pool[1] { t.Error("Expected ip hash policy host to be the second host.") } // We should be able to resize the host pool and still be able to predict // where a req will be routed with the same IP's used above pool = UpstreamPool{ {Host: new(Host), Dial: "0.0.0.2"}, {Host: new(Host), Dial: "0.0.0.3"}, } req.RemoteAddr = "172.0.0.1:80" h = ipHash.Select(pool, req, nil) if h != pool[0] { t.Error("Expected ip hash policy host to be the first host.") } req.RemoteAddr = "172.0.0.2:80" h = ipHash.Select(pool, req, nil) if h != pool[0] { t.Error("Expected ip hash policy host to be the first host.") } req.RemoteAddr = "172.0.0.3:80" h = ipHash.Select(pool, req, nil) if h != pool[0] { t.Error("Expected ip hash policy host to be the first host.") } req.RemoteAddr = "172.0.0.4:80" h = ipHash.Select(pool, req, nil) if h != pool[0] { t.Error("Expected ip hash policy host to be the first host.") } // We should get nil when there are no healthy hosts pool[0].setHealthy(false) pool[1].setHealthy(false) h = ipHash.Select(pool, req, nil) if h != nil { t.Error("Expected ip hash policy host to be nil.") } // Reproduce #4135 pool = UpstreamPool{ {Host: new(Host)}, {Host: new(Host)}, {Host: new(Host)}, {Host: new(Host)}, {Host: new(Host)}, {Host: new(Host)}, {Host: new(Host)}, {Host: new(Host)}, {Host: new(Host)}, } pool[0].setHealthy(false) pool[1].setHealthy(false) pool[2].setHealthy(false) pool[3].setHealthy(false) pool[4].setHealthy(false) pool[5].setHealthy(false) pool[6].setHealthy(false) pool[7].setHealthy(false) pool[8].setHealthy(true) // We should get a result back when there is one healthy host left. h = ipHash.Select(pool, req, nil) if h == nil { // If it is nil, it means we missed a host even though one is available t.Error("Expected ip hash policy host to not be nil, but it is nil.") } } func TestClientIPHashPolicy(t *testing.T) { pool := testPool() ipHash := ClientIPHashSelection{} req, _ := http.NewRequest("GET", "/", nil) req = req.WithContext(context.WithValue(req.Context(), caddyhttp.VarsCtxKey, make(map[string]any))) // We should be able to predict where every request is routed. caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.1:80") h := ipHash.Select(pool, req, nil) if h != pool[1] { t.Error("Expected ip hash policy host to be the second host.") } caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.2:80") h = ipHash.Select(pool, req, nil) if h != pool[1] { t.Error("Expected ip hash policy host to be the second host.") } caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.3:80") h = ipHash.Select(pool, req, nil) if h != pool[1] { t.Error("Expected ip hash policy host to be the second host.") } caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.4:80") h = ipHash.Select(pool, req, nil) if h != pool[1] { t.Error("Expected ip hash policy host to be the second host.") } // we should get the same results without a port caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.1") h = ipHash.Select(pool, req, nil) if h != pool[1] { t.Error("Expected ip hash policy host to be the second host.") } caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.2") h = ipHash.Select(pool, req, nil) if h != pool[1] { t.Error("Expected ip hash policy host to be the second host.") } caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.3") h = ipHash.Select(pool, req, nil) if h != pool[1] { t.Error("Expected ip hash policy host to be the second host.") } caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.4") h = ipHash.Select(pool, req, nil) if h != pool[1] { t.Error("Expected ip hash policy host to be the second host.") } // we should get a healthy host if the original host is unhealthy and a // healthy host is available caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.4") pool[1].setHealthy(false) h = ipHash.Select(pool, req, nil) if h != pool[0] { t.Error("Expected ip hash policy host to be the first host.") } caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.2") h = ipHash.Select(pool, req, nil) if h != pool[0] { t.Error("Expected ip hash policy host to be the first host.") } pool[1].setHealthy(true) caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.3") pool[2].setHealthy(false) h = ipHash.Select(pool, req, nil) if h != pool[1] { t.Error("Expected ip hash policy host to be the second host.") } caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.4") h = ipHash.Select(pool, req, nil) if h != pool[1] { t.Error("Expected ip hash policy host to be the second host.") } // We should be able to resize the host pool and still be able to predict // where a req will be routed with the same IP's used above pool = UpstreamPool{ {Host: new(Host), Dial: "0.0.0.2"}, {Host: new(Host), Dial: "0.0.0.3"}, } caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.1:80") h = ipHash.Select(pool, req, nil) if h != pool[0] { t.Error("Expected ip hash policy host to be the first host.") } caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.2:80") h = ipHash.Select(pool, req, nil) if h != pool[0] { t.Error("Expected ip hash policy host to be the first host.") } caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.3:80") h = ipHash.Select(pool, req, nil) if h != pool[0] { t.Error("Expected ip hash policy host to be the first host.") } caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.4:80") h = ipHash.Select(pool, req, nil) if h != pool[0] { t.Error("Expected ip hash policy host to be the first host.") } // We should get nil when there are no healthy hosts pool[0].setHealthy(false) pool[1].setHealthy(false) h = ipHash.Select(pool, req, nil) if h != nil { t.Error("Expected ip hash policy host to be nil.") } // Reproduce #4135 pool = UpstreamPool{ {Host: new(Host)}, {Host: new(Host)}, {Host: new(Host)}, {Host: new(Host)}, {Host: new(Host)}, {Host: new(Host)}, {Host: new(Host)}, {Host: new(Host)}, {Host: new(Host)}, } pool[0].setHealthy(false) pool[1].setHealthy(false) pool[2].setHealthy(false) pool[3].setHealthy(false) pool[4].setHealthy(false) pool[5].setHealthy(false) pool[6].setHealthy(false) pool[7].setHealthy(false) pool[8].setHealthy(true) // We should get a result back when there is one healthy host left. h = ipHash.Select(pool, req, nil) if h == nil { // If it is nil, it means we missed a host even though one is available t.Error("Expected ip hash policy host to not be nil, but it is nil.") } } func TestFirstPolicy(t *testing.T) { pool := testPool() firstPolicy := FirstSelection{} req := httptest.NewRequest(http.MethodGet, "/", nil) h := firstPolicy.Select(pool, req, nil) if h != pool[0] { t.Error("Expected first policy host to be the first host.") } pool[0].setHealthy(false) h = firstPolicy.Select(pool, req, nil) if h != pool[1] { t.Error("Expected first policy host to be the second host.") } } func TestQueryHashPolicy(t *testing.T) { ctx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()}) defer cancel() queryPolicy := QueryHashSelection{Key: "foo"} if err := queryPolicy.Provision(ctx); err != nil { t.Errorf("Provision error: %v", err) t.FailNow() } pool := testPool() request := httptest.NewRequest(http.MethodGet, "/?foo=1", nil) h := queryPolicy.Select(pool, request, nil) if h != pool[0] { t.Error("Expected query policy host to be the first host.") } request = httptest.NewRequest(http.MethodGet, "/?foo=100000", nil) h = queryPolicy.Select(pool, request, nil) if h != pool[0] { t.Error("Expected query policy host to be the first host.") } request = httptest.NewRequest(http.MethodGet, "/?foo=1", nil) pool[0].setHealthy(false) h = queryPolicy.Select(pool, request, nil) if h != pool[1] { t.Error("Expected query policy host to be the second host.") } request = httptest.NewRequest(http.MethodGet, "/?foo=100000", nil) h = queryPolicy.Select(pool, request, nil) if h != pool[2] { t.Error("Expected query policy host to be the third host.") } // We should be able to resize the host pool and still be able to predict // where a request will be routed with the same query used above pool = UpstreamPool{ {Host: new(Host)}, {Host: new(Host)}, } request = httptest.NewRequest(http.MethodGet, "/?foo=1", nil) h = queryPolicy.Select(pool, request, nil) if h != pool[0] { t.Error("Expected query policy host to be the first host.") } pool[0].setHealthy(false) h = queryPolicy.Select(pool, request, nil) if h != pool[1] { t.Error("Expected query policy host to be the second host.") } request = httptest.NewRequest(http.MethodGet, "/?foo=4", nil) h = queryPolicy.Select(pool, request, nil) if h != pool[1] { t.Error("Expected query policy host to be the second host.") } pool[0].setHealthy(false) pool[1].setHealthy(false) h = queryPolicy.Select(pool, request, nil) if h != nil { t.Error("Expected query policy policy host to be nil.") } request = httptest.NewRequest(http.MethodGet, "/?foo=aa11&foo=bb22", nil) pool = testPool() h = queryPolicy.Select(pool, request, nil) if h != pool[0] { t.Error("Expected query policy host to be the first host.") } } func TestURIHashPolicy(t *testing.T) { pool := testPool() uriPolicy := URIHashSelection{} request := httptest.NewRequest(http.MethodGet, "/test", nil) h := uriPolicy.Select(pool, request, nil) if h != pool[1] { t.Error("Expected uri policy host to be the second host.") } pool[2].setHealthy(false) h = uriPolicy.Select(pool, request, nil) if h != pool[1] { t.Error("Expected uri policy host to be the second host.") } request = httptest.NewRequest(http.MethodGet, "/test_2", nil) h = uriPolicy.Select(pool, request, nil) if h != pool[0] { t.Error("Expected uri policy host to be the first host.") } // We should be able to resize the host pool and still be able to predict // where a request will be routed with the same URI's used above pool = UpstreamPool{ {Host: new(Host)}, {Host: new(Host)}, } request = httptest.NewRequest(http.MethodGet, "/test", nil) h = uriPolicy.Select(pool, request, nil) if h != pool[0] { t.Error("Expected uri policy host to be the first host.") } pool[0].setHealthy(false) h = uriPolicy.Select(pool, request, nil) if h != pool[1] { t.Error("Expected uri policy host to be the first host.") } request = httptest.NewRequest(http.MethodGet, "/test_2", nil) h = uriPolicy.Select(pool, request, nil) if h != pool[1] { t.Error("Expected uri policy host to be the second host.") } pool[0].setHealthy(false) pool[1].setHealthy(false) h = uriPolicy.Select(pool, request, nil) if h != nil { t.Error("Expected uri policy policy host to be nil.") } } func TestLeastRequests(t *testing.T) { pool := testPool() pool[0].Dial = "localhost:8080" pool[1].Dial = "localhost:8081" pool[2].Dial = "localhost:8082" pool[0].setHealthy(true) pool[1].setHealthy(true) pool[2].setHealthy(true) pool[0].countRequest(10) pool[1].countRequest(20) pool[2].countRequest(30) result := leastRequests(pool) if result == nil { t.Error("Least request should not return nil") } if result != pool[0] { t.Error("Least request should return pool[0]") } } func TestRandomChoicePolicy(t *testing.T) { pool := testPool() pool[0].Dial = "localhost:8080" pool[1].Dial = "localhost:8081" pool[2].Dial = "localhost:8082" pool[0].setHealthy(false) pool[1].setHealthy(true) pool[2].setHealthy(true) pool[0].countRequest(10) pool[1].countRequest(20) pool[2].countRequest(30) request := httptest.NewRequest(http.MethodGet, "/test", nil) randomChoicePolicy := RandomChoiceSelection{Choose: 2} h := randomChoicePolicy.Select(pool, request, nil) if h == nil { t.Error("RandomChoicePolicy should not return nil") } if h == pool[0] { t.Error("RandomChoicePolicy should not choose pool[0]") } } func TestCookieHashPolicy(t *testing.T) { ctx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()}) defer cancel() cookieHashPolicy := CookieHashSelection{} if err := cookieHashPolicy.Provision(ctx); err != nil { t.Errorf("Provision error: %v", err) t.FailNow() } pool := testPool() pool[0].Dial = "localhost:8080" pool[1].Dial = "localhost:8081" pool[2].Dial = "localhost:8082" pool[0].setHealthy(true) pool[1].setHealthy(false) pool[2].setHealthy(false) request := httptest.NewRequest(http.MethodGet, "/test", nil) w := httptest.NewRecorder() h := cookieHashPolicy.Select(pool, request, w) cookieServer1 := w.Result().Cookies()[0] if cookieServer1 == nil { t.Fatal("cookieHashPolicy should set a cookie") } if cookieServer1.Name != "lb" { t.Error("cookieHashPolicy should set a cookie with name lb") } if h != pool[0] { t.Error("Expected cookieHashPolicy host to be the first only available host.") } pool[1].setHealthy(true) pool[2].setHealthy(true) request = httptest.NewRequest(http.MethodGet, "/test", nil) w = httptest.NewRecorder() request.AddCookie(cookieServer1) h = cookieHashPolicy.Select(pool, request, w) if h != pool[0] { t.Error("Expected cookieHashPolicy host to stick to the first host (matching cookie).") } s := w.Result().Cookies() if len(s) != 0 { t.Error("Expected cookieHashPolicy to not set a new cookie.") } pool[0].setHealthy(false) request = httptest.NewRequest(http.MethodGet, "/test", nil) w = httptest.NewRecorder() request.AddCookie(cookieServer1) h = cookieHashPolicy.Select(pool, request, w) if h == pool[0] { t.Error("Expected cookieHashPolicy to select a new host.") } if w.Result().Cookies() == nil { t.Error("Expected cookieHashPolicy to set a new cookie.") } } func TestCookieHashPolicyWithFirstFallback(t *testing.T) { ctx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()}) defer cancel() cookieHashPolicy := CookieHashSelection{ FallbackRaw: caddyconfig.JSONModuleObject(FirstSelection{}, "policy", "first", nil), } if err := cookieHashPolicy.Provision(ctx); err != nil { t.Errorf("Provision error: %v", err) t.FailNow() } pool := testPool() pool[0].Dial = "localhost:8080" pool[1].Dial = "localhost:8081" pool[2].Dial = "localhost:8082" pool[0].setHealthy(true) pool[1].setHealthy(true) pool[2].setHealthy(true) request := httptest.NewRequest(http.MethodGet, "/test", nil) w := httptest.NewRecorder() h := cookieHashPolicy.Select(pool, request, w) cookieServer1 := w.Result().Cookies()[0] if cookieServer1 == nil { t.Fatal("cookieHashPolicy should set a cookie") } if cookieServer1.Name != "lb" { t.Error("cookieHashPolicy should set a cookie with name lb") } if h != pool[0] { t.Errorf("Expected cookieHashPolicy host to be the first only available host, got %s", h) } request = httptest.NewRequest(http.MethodGet, "/test", nil) w = httptest.NewRecorder() request.AddCookie(cookieServer1) h = cookieHashPolicy.Select(pool, request, w) if h != pool[0] { t.Errorf("Expected cookieHashPolicy host to stick to the first host (matching cookie), got %s", h) } s := w.Result().Cookies() if len(s) != 0 { t.Error("Expected cookieHashPolicy to not set a new cookie.") } pool[0].setHealthy(false) request = httptest.NewRequest(http.MethodGet, "/test", nil) w = httptest.NewRecorder() request.AddCookie(cookieServer1) h = cookieHashPolicy.Select(pool, request, w) if h != pool[1] { t.Errorf("Expected cookieHashPolicy to select the next first available host, got %s", h) } if w.Result().Cookies() == nil { t.Error("Expected cookieHashPolicy to set a new cookie.") } }
Go
caddy/modules/caddyhttp/reverseproxy/streaming.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Most of the code in this file was initially borrowed from the Go // standard library and modified; It had this copyright notice: // Copyright 2011 The Go Authors package reverseproxy import ( "context" "errors" "fmt" "io" weakrand "math/rand" "mime" "net/http" "sync" "time" "unsafe" "go.uber.org/zap" "golang.org/x/net/http/httpguts" ) func (h *Handler) handleUpgradeResponse(logger *zap.Logger, rw http.ResponseWriter, req *http.Request, res *http.Response) { reqUpType := upgradeType(req.Header) resUpType := upgradeType(res.Header) // Taken from https://github.com/golang/go/commit/5c489514bc5e61ad9b5b07bd7d8ec65d66a0512a // We know reqUpType is ASCII, it's checked by the caller. if !asciiIsPrint(resUpType) { logger.Debug("backend tried to switch to invalid protocol", zap.String("backend_upgrade", resUpType)) return } if !asciiEqualFold(reqUpType, resUpType) { logger.Debug("backend tried to switch to unexpected protocol via Upgrade header", zap.String("backend_upgrade", resUpType), zap.String("requested_upgrade", reqUpType)) return } backConn, ok := res.Body.(io.ReadWriteCloser) if !ok { logger.Error("internal error: 101 switching protocols response with non-writable body") return } // write header first, response headers should not be counted in size // like the rest of handler chain. copyHeader(rw.Header(), res.Header) rw.WriteHeader(res.StatusCode) logger.Debug("upgrading connection") //nolint:bodyclose conn, brw, hijackErr := http.NewResponseController(rw).Hijack() if errors.Is(hijackErr, http.ErrNotSupported) { h.logger.Sugar().Errorf("can't switch protocols using non-Hijacker ResponseWriter type %T", rw) return } if hijackErr != nil { h.logger.Error("hijack failed on protocol switch", zap.Error(hijackErr)) return } // adopted from https://github.com/golang/go/commit/8bcf2834afdf6a1f7937390903a41518715ef6f5 backConnCloseCh := make(chan struct{}) go func() { // Ensure that the cancelation of a request closes the backend. // See issue https://golang.org/issue/35559. select { case <-req.Context().Done(): case <-backConnCloseCh: } backConn.Close() }() defer close(backConnCloseCh) start := time.Now() defer func() { conn.Close() logger.Debug("connection closed", zap.Duration("duration", time.Since(start))) }() if err := brw.Flush(); err != nil { logger.Debug("response flush", zap.Error(err)) return } // Ensure the hijacked client connection, and the new connection established // with the backend, are both closed in the event of a server shutdown. This // is done by registering them. We also try to gracefully close connections // we recognize as websockets. // We need to make sure the client connection messages (i.e. to upstream) // are masked, so we need to know whether the connection is considered the // server or the client side of the proxy. gracefulClose := func(conn io.ReadWriteCloser, isClient bool) func() error { if isWebsocket(req) { return func() error { return writeCloseControl(conn, isClient) } } return nil } deleteFrontConn := h.registerConnection(conn, gracefulClose(conn, false)) deleteBackConn := h.registerConnection(backConn, gracefulClose(backConn, true)) defer deleteFrontConn() defer deleteBackConn() spc := switchProtocolCopier{user: conn, backend: backConn} // setup the timeout if requested var timeoutc <-chan time.Time if h.StreamTimeout > 0 { timer := time.NewTimer(time.Duration(h.StreamTimeout)) defer timer.Stop() timeoutc = timer.C } errc := make(chan error, 1) go spc.copyToBackend(errc) go spc.copyFromBackend(errc) select { case err := <-errc: logger.Debug("streaming error", zap.Error(err)) case time := <-timeoutc: logger.Debug("stream timed out", zap.Time("timeout", time)) } } // flushInterval returns the p.FlushInterval value, conditionally // overriding its value for a specific request/response. func (h Handler) flushInterval(req *http.Request, res *http.Response) time.Duration { resCTHeader := res.Header.Get("Content-Type") resCT, _, err := mime.ParseMediaType(resCTHeader) // For Server-Sent Events responses, flush immediately. // The MIME type is defined in https://www.w3.org/TR/eventsource/#text-event-stream if err == nil && resCT == "text/event-stream" { return -1 // negative means immediately } // We might have the case of streaming for which Content-Length might be unset. if res.ContentLength == -1 { return -1 } // for h2 and h2c upstream streaming data to client (issues #3556 and #3606) if h.isBidirectionalStream(req, res) { return -1 } return time.Duration(h.FlushInterval) } // isBidirectionalStream returns whether we should work in bi-directional stream mode. // // See https://github.com/caddyserver/caddy/pull/3620 for discussion of nuances. func (h Handler) isBidirectionalStream(req *http.Request, res *http.Response) bool { // We have to check the encoding here; only flush headers with identity encoding. // Non-identity encoding might combine with "encode" directive, and in that case, // if body size larger than enc.MinLength, upper level encode handle might have // Content-Encoding header to write. // (see https://github.com/caddyserver/caddy/issues/3606 for use case) ae := req.Header.Get("Accept-Encoding") return req.ProtoMajor == 2 && res.ProtoMajor == 2 && res.ContentLength == -1 && (ae == "identity" || ae == "") } func (h Handler) copyResponse(dst http.ResponseWriter, src io.Reader, flushInterval time.Duration) error { var w io.Writer = dst if flushInterval != 0 { mlw := &maxLatencyWriter{ dst: dst, //nolint:bodyclose flush: http.NewResponseController(dst).Flush, latency: flushInterval, } defer mlw.stop() // set up initial timer so headers get flushed even if body writes are delayed mlw.flushPending = true mlw.t = time.AfterFunc(flushInterval, mlw.delayedFlush) w = mlw } buf := streamingBufPool.Get().(*[]byte) defer streamingBufPool.Put(buf) _, err := h.copyBuffer(w, src, *buf) return err } // copyBuffer returns any write errors or non-EOF read errors, and the amount // of bytes written. func (h Handler) copyBuffer(dst io.Writer, src io.Reader, buf []byte) (int64, error) { if len(buf) == 0 { buf = make([]byte, defaultBufferSize) } var written int64 for { nr, rerr := src.Read(buf) if rerr != nil && rerr != io.EOF && rerr != context.Canceled { // TODO: this could be useful to know (indeed, it revealed an error in our // fastcgi PoC earlier; but it's this single error report here that necessitates // a function separate from io.CopyBuffer, since io.CopyBuffer does not distinguish // between read or write errors; in a reverse proxy situation, write errors are not // something we need to report to the client, but read errors are a problem on our // end for sure. so we need to decide what we want.) // p.logf("copyBuffer: ReverseProxy read error during body copy: %v", rerr) h.logger.Error("reading from backend", zap.Error(rerr)) } if nr > 0 { nw, werr := dst.Write(buf[:nr]) if nw > 0 { written += int64(nw) } if werr != nil { return written, fmt.Errorf("writing: %w", werr) } if nr != nw { return written, io.ErrShortWrite } } if rerr != nil { if rerr == io.EOF { return written, nil } return written, fmt.Errorf("reading: %w", rerr) } } } // registerConnection holds onto conn so it can be closed in the event // of a server shutdown. This is useful because hijacked connections or // connections dialed to backends don't close when server is shut down. // The caller should call the returned delete() function when the // connection is done to remove it from memory. func (h *Handler) registerConnection(conn io.ReadWriteCloser, gracefulClose func() error) (del func()) { h.connectionsMu.Lock() h.connections[conn] = openConnection{conn, gracefulClose} h.connectionsMu.Unlock() return func() { h.connectionsMu.Lock() delete(h.connections, conn) // if there is no connection left before the connections close timer fires if len(h.connections) == 0 && h.connectionsCloseTimer != nil { // we release the timer that holds the reference to Handler if (*h.connectionsCloseTimer).Stop() { h.logger.Debug("stopped streaming connections close timer - all connections are already closed") } h.connectionsCloseTimer = nil } h.connectionsMu.Unlock() } } // closeConnections immediately closes all hijacked connections (both to client and backend). func (h *Handler) closeConnections() error { var err error h.connectionsMu.Lock() defer h.connectionsMu.Unlock() for _, oc := range h.connections { if oc.gracefulClose != nil { // this is potentially blocking while we have the lock on the connections // map, but that should be OK since the server has in theory shut down // and we are no longer using the connections map gracefulErr := oc.gracefulClose() if gracefulErr != nil && err == nil { err = gracefulErr } } closeErr := oc.conn.Close() if closeErr != nil && err == nil { err = closeErr } } return err } // cleanupConnections closes hijacked connections. // Depending on the value of StreamCloseDelay it does that either immediately // or sets up a timer that will do that later. func (h *Handler) cleanupConnections() error { if h.StreamCloseDelay == 0 { return h.closeConnections() } h.connectionsMu.Lock() defer h.connectionsMu.Unlock() // the handler is shut down, no new connection can appear, // so we can skip setting up the timer when there are no connections if len(h.connections) > 0 { delay := time.Duration(h.StreamCloseDelay) h.connectionsCloseTimer = time.AfterFunc(delay, func() { h.logger.Debug("closing streaming connections after delay", zap.Duration("delay", delay)) err := h.closeConnections() if err != nil { h.logger.Error("failed to closed connections after delay", zap.Error(err), zap.Duration("delay", delay)) } }) } return nil } // writeCloseControl sends a best-effort Close control message to the given // WebSocket connection. Thanks to @pascaldekloe who provided inspiration // from his simple implementation of this I was able to learn from at: // github.com/pascaldekloe/websocket. Further work for handling masking // taken from github.com/gorilla/websocket. func writeCloseControl(conn io.Writer, isClient bool) error { // Sources: // https://github.com/pascaldekloe/websocket/blob/32050af67a5d/websocket.go#L119 // https://github.com/gorilla/websocket/blob/v1.5.0/conn.go#L413 // For now, we're not using a reason. We might later, though. // The code handling the reason is left in var reason string // max 123 bytes (control frame payload limit is 125; status code takes 2) const closeMessage = 8 const finalBit = 1 << 7 // Frame header byte 0 bits from Section 5.2 of RFC 6455 const maskBit = 1 << 7 // Frame header byte 1 bits from Section 5.2 of RFC 6455 const goingAwayUpper uint8 = 1001 >> 8 const goingAwayLower uint8 = 1001 & 0xff b0 := byte(closeMessage) | finalBit b1 := byte(len(reason) + 2) if isClient { b1 |= maskBit } buf := make([]byte, 0, 127) buf = append(buf, b0, b1) msgLength := 4 + len(reason) // Both branches below append the "going away" code and reason appendMessage := func(buf []byte) []byte { buf = append(buf, goingAwayUpper, goingAwayLower) buf = append(buf, []byte(reason)...) return buf } // When we're the client, we need to mask the message as per // https://www.rfc-editor.org/rfc/rfc6455#section-5.3 if isClient { key := newMaskKey() buf = append(buf, key[:]...) msgLength += len(key) buf = appendMessage(buf) maskBytes(key, 0, buf[2+len(key):]) } else { buf = appendMessage(buf) } // simply best-effort, but return error for logging purposes // TODO: we might need to ensure we are the exclusive writer by this point (io.Copy is stopped)? _, err := conn.Write(buf[:msgLength]) return err } // Copied from https://github.com/gorilla/websocket/blob/v1.5.0/mask.go func maskBytes(key [4]byte, pos int, b []byte) int { // Mask one byte at a time for small buffers. if len(b) < 2*wordSize { for i := range b { b[i] ^= key[pos&3] pos++ } return pos & 3 } // Mask one byte at a time to word boundary. if n := int(uintptr(unsafe.Pointer(&b[0]))) % wordSize; n != 0 { n = wordSize - n for i := range b[:n] { b[i] ^= key[pos&3] pos++ } b = b[n:] } // Create aligned word size key. var k [wordSize]byte for i := range k { k[i] = key[(pos+i)&3] } kw := *(*uintptr)(unsafe.Pointer(&k)) // Mask one word at a time. n := (len(b) / wordSize) * wordSize for i := 0; i < n; i += wordSize { *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&b[0])) + uintptr(i))) ^= kw } // Mask one byte at a time for remaining bytes. b = b[n:] for i := range b { b[i] ^= key[pos&3] pos++ } return pos & 3 } // Copied from https://github.com/gorilla/websocket/blob/v1.5.0/conn.go#L184 func newMaskKey() [4]byte { n := weakrand.Uint32() return [4]byte{byte(n), byte(n >> 8), byte(n >> 16), byte(n >> 24)} } // isWebsocket returns true if r looks to be an upgrade request for WebSockets. // It is a fairly naive check. func isWebsocket(r *http.Request) bool { return httpguts.HeaderValuesContainsToken(r.Header["Connection"], "upgrade") && httpguts.HeaderValuesContainsToken(r.Header["Upgrade"], "websocket") } // openConnection maps an open connection to // an optional function for graceful close. type openConnection struct { conn io.ReadWriteCloser gracefulClose func() error } type maxLatencyWriter struct { dst io.Writer flush func() error latency time.Duration // non-zero; negative means to flush immediately mu sync.Mutex // protects t, flushPending, and dst.Flush t *time.Timer flushPending bool } func (m *maxLatencyWriter) Write(p []byte) (n int, err error) { m.mu.Lock() defer m.mu.Unlock() n, err = m.dst.Write(p) if m.latency < 0 { //nolint:errcheck m.flush() return } if m.flushPending { return } if m.t == nil { m.t = time.AfterFunc(m.latency, m.delayedFlush) } else { m.t.Reset(m.latency) } m.flushPending = true return } func (m *maxLatencyWriter) delayedFlush() { m.mu.Lock() defer m.mu.Unlock() if !m.flushPending { // if stop was called but AfterFunc already started this goroutine return } //nolint:errcheck m.flush() m.flushPending = false } func (m *maxLatencyWriter) stop() { m.mu.Lock() defer m.mu.Unlock() m.flushPending = false if m.t != nil { m.t.Stop() } } // switchProtocolCopier exists so goroutines proxying data back and // forth have nice names in stacks. type switchProtocolCopier struct { user, backend io.ReadWriteCloser } func (c switchProtocolCopier) copyFromBackend(errc chan<- error) { _, err := io.Copy(c.user, c.backend) errc <- err } func (c switchProtocolCopier) copyToBackend(errc chan<- error) { _, err := io.Copy(c.backend, c.user) errc <- err } var streamingBufPool = sync.Pool{ New: func() any { // The Pool's New function should generally only return pointer // types, since a pointer can be put into the return interface // value without an allocation // - (from the package docs) b := make([]byte, defaultBufferSize) return &b }, } const ( defaultBufferSize = 32 * 1024 wordSize = int(unsafe.Sizeof(uintptr(0))) )
Go
caddy/modules/caddyhttp/reverseproxy/streaming_test.go
package reverseproxy import ( "bytes" "net/http/httptest" "strings" "testing" ) func TestHandlerCopyResponse(t *testing.T) { h := Handler{} testdata := []string{ "", strings.Repeat("a", defaultBufferSize), strings.Repeat("123456789 123456789 123456789 12", 3000), } dst := bytes.NewBuffer(nil) recorder := httptest.NewRecorder() recorder.Body = dst for _, d := range testdata { src := bytes.NewBuffer([]byte(d)) dst.Reset() err := h.copyResponse(recorder, src, 0) if err != nil { t.Errorf("failed with error: %v", err) } out := dst.String() if out != d { t.Errorf("bad read: got %q", out) } } }
Go
caddy/modules/caddyhttp/reverseproxy/upstreams.go
package reverseproxy import ( "context" "encoding/json" "fmt" weakrand "math/rand" "net" "net/http" "strconv" "sync" "time" "go.uber.org/zap" "github.com/caddyserver/caddy/v2" ) func init() { caddy.RegisterModule(SRVUpstreams{}) caddy.RegisterModule(AUpstreams{}) caddy.RegisterModule(MultiUpstreams{}) } // SRVUpstreams provides upstreams from SRV lookups. // The lookup DNS name can be configured either by // its individual parts (that is, specifying the // service, protocol, and name separately) to form // the standard "_service._proto.name" domain, or // the domain can be specified directly in name by // leaving service and proto empty. See RFC 2782. // // Lookups are cached and refreshed at the configured // refresh interval. // // Returned upstreams are sorted by priority and weight. type SRVUpstreams struct { // The service label. Service string `json:"service,omitempty"` // The protocol label; either tcp or udp. Proto string `json:"proto,omitempty"` // The name label; or, if service and proto are // empty, the entire domain name to look up. Name string `json:"name,omitempty"` // The interval at which to refresh the SRV lookup. // Results are cached between lookups. Default: 1m Refresh caddy.Duration `json:"refresh,omitempty"` // Configures the DNS resolver used to resolve the // SRV address to SRV records. Resolver *UpstreamResolver `json:"resolver,omitempty"` // If Resolver is configured, how long to wait before // timing out trying to connect to the DNS server. DialTimeout caddy.Duration `json:"dial_timeout,omitempty"` // If Resolver is configured, how long to wait before // spawning an RFC 6555 Fast Fallback connection. // A negative value disables this. FallbackDelay caddy.Duration `json:"dial_fallback_delay,omitempty"` resolver *net.Resolver logger *zap.Logger } // CaddyModule returns the Caddy module information. func (SRVUpstreams) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.reverse_proxy.upstreams.srv", New: func() caddy.Module { return new(SRVUpstreams) }, } } func (su *SRVUpstreams) Provision(ctx caddy.Context) error { su.logger = ctx.Logger() if su.Refresh == 0 { su.Refresh = caddy.Duration(time.Minute) } if su.Resolver != nil { err := su.Resolver.ParseAddresses() if err != nil { return err } d := &net.Dialer{ Timeout: time.Duration(su.DialTimeout), FallbackDelay: time.Duration(su.FallbackDelay), } su.resolver = &net.Resolver{ PreferGo: true, Dial: func(ctx context.Context, _, _ string) (net.Conn, error) { //nolint:gosec addr := su.Resolver.netAddrs[weakrand.Intn(len(su.Resolver.netAddrs))] return d.DialContext(ctx, addr.Network, addr.JoinHostPort(0)) }, } } if su.resolver == nil { su.resolver = net.DefaultResolver } return nil } func (su SRVUpstreams) GetUpstreams(r *http.Request) ([]*Upstream, error) { suAddr, service, proto, name := su.expandedAddr(r) // first, use a cheap read-lock to return a cached result quickly srvsMu.RLock() cached := srvs[suAddr] srvsMu.RUnlock() if cached.isFresh() { return allNew(cached.upstreams), nil } // otherwise, obtain a write-lock to update the cached value srvsMu.Lock() defer srvsMu.Unlock() // check to see if it's still stale, since we're now in a different // lock from when we first checked freshness; another goroutine might // have refreshed it in the meantime before we re-obtained our lock cached = srvs[suAddr] if cached.isFresh() { return allNew(cached.upstreams), nil } su.logger.Debug("refreshing SRV upstreams", zap.String("service", service), zap.String("proto", proto), zap.String("name", name)) _, records, err := su.resolver.LookupSRV(r.Context(), service, proto, name) if err != nil { // From LookupSRV docs: "If the response contains invalid names, those records are filtered // out and an error will be returned alongside the remaining results, if any." Thus, we // only return an error if no records were also returned. if len(records) == 0 { return nil, err } su.logger.Warn("SRV records filtered", zap.Error(err)) } upstreams := make([]Upstream, len(records)) for i, rec := range records { su.logger.Debug("discovered SRV record", zap.String("target", rec.Target), zap.Uint16("port", rec.Port), zap.Uint16("priority", rec.Priority), zap.Uint16("weight", rec.Weight)) addr := net.JoinHostPort(rec.Target, strconv.Itoa(int(rec.Port))) upstreams[i] = Upstream{Dial: addr} } // before adding a new one to the cache (as opposed to replacing stale one), make room if cache is full if cached.freshness.IsZero() && len(srvs) >= 100 { for randomKey := range srvs { delete(srvs, randomKey) break } } srvs[suAddr] = srvLookup{ srvUpstreams: su, freshness: time.Now(), upstreams: upstreams, } return allNew(upstreams), nil } func (su SRVUpstreams) String() string { if su.Service == "" && su.Proto == "" { return su.Name } return su.formattedAddr(su.Service, su.Proto, su.Name) } // expandedAddr expands placeholders in the configured SRV domain labels. // The return values are: addr, the RFC 2782 representation of the SRV domain; // service, the service; proto, the protocol; and name, the name. // If su.Service and su.Proto are empty, name will be returned as addr instead. func (su SRVUpstreams) expandedAddr(r *http.Request) (addr, service, proto, name string) { repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) name = repl.ReplaceAll(su.Name, "") if su.Service == "" && su.Proto == "" { addr = name return } service = repl.ReplaceAll(su.Service, "") proto = repl.ReplaceAll(su.Proto, "") addr = su.formattedAddr(service, proto, name) return } // formattedAddr the RFC 2782 representation of the SRV domain, in // the form "_service._proto.name". func (SRVUpstreams) formattedAddr(service, proto, name string) string { return fmt.Sprintf("_%s._%s.%s", service, proto, name) } type srvLookup struct { srvUpstreams SRVUpstreams freshness time.Time upstreams []Upstream } func (sl srvLookup) isFresh() bool { return time.Since(sl.freshness) < time.Duration(sl.srvUpstreams.Refresh) } type IPVersions struct { IPv4 *bool `json:"ipv4,omitempty"` IPv6 *bool `json:"ipv6,omitempty"` } // AUpstreams provides upstreams from A/AAAA lookups. // Results are cached and refreshed at the configured // refresh interval. type AUpstreams struct { // The domain name to look up. Name string `json:"name,omitempty"` // The port to use with the upstreams. Default: 80 Port string `json:"port,omitempty"` // The interval at which to refresh the A lookup. // Results are cached between lookups. Default: 1m Refresh caddy.Duration `json:"refresh,omitempty"` // Configures the DNS resolver used to resolve the // domain name to A records. Resolver *UpstreamResolver `json:"resolver,omitempty"` // If Resolver is configured, how long to wait before // timing out trying to connect to the DNS server. DialTimeout caddy.Duration `json:"dial_timeout,omitempty"` // If Resolver is configured, how long to wait before // spawning an RFC 6555 Fast Fallback connection. // A negative value disables this. FallbackDelay caddy.Duration `json:"dial_fallback_delay,omitempty"` // The IP versions to resolve for. By default, both // "ipv4" and "ipv6" will be enabled, which // correspond to A and AAAA records respectively. Versions *IPVersions `json:"versions,omitempty"` resolver *net.Resolver } // CaddyModule returns the Caddy module information. func (AUpstreams) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.reverse_proxy.upstreams.a", New: func() caddy.Module { return new(AUpstreams) }, } } func (au *AUpstreams) Provision(_ caddy.Context) error { if au.Refresh == 0 { au.Refresh = caddy.Duration(time.Minute) } if au.Port == "" { au.Port = "80" } if au.Resolver != nil { err := au.Resolver.ParseAddresses() if err != nil { return err } d := &net.Dialer{ Timeout: time.Duration(au.DialTimeout), FallbackDelay: time.Duration(au.FallbackDelay), } au.resolver = &net.Resolver{ PreferGo: true, Dial: func(ctx context.Context, _, _ string) (net.Conn, error) { //nolint:gosec addr := au.Resolver.netAddrs[weakrand.Intn(len(au.Resolver.netAddrs))] return d.DialContext(ctx, addr.Network, addr.JoinHostPort(0)) }, } } if au.resolver == nil { au.resolver = net.DefaultResolver } return nil } func (au AUpstreams) GetUpstreams(r *http.Request) ([]*Upstream, error) { repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) resolveIpv4 := au.Versions.IPv4 == nil || *au.Versions.IPv4 resolveIpv6 := au.Versions.IPv6 == nil || *au.Versions.IPv6 // Map ipVersion early, so we can use it as part of the cache-key. // This should be fairly inexpensive and comes and the upside of // allowing the same dynamic upstream (name + port combination) // to be used multiple times with different ip versions. // // It also forced a cache-miss if a previously cached dynamic // upstream changes its ip version, e.g. after a config reload, // while keeping the cache-invalidation as simple as it currently is. var ipVersion string switch { case resolveIpv4 && !resolveIpv6: ipVersion = "ip4" case !resolveIpv4 && resolveIpv6: ipVersion = "ip6" default: ipVersion = "ip" } auStr := repl.ReplaceAll(au.String()+ipVersion, "") // first, use a cheap read-lock to return a cached result quickly aAaaaMu.RLock() cached := aAaaa[auStr] aAaaaMu.RUnlock() if cached.isFresh() { return allNew(cached.upstreams), nil } // otherwise, obtain a write-lock to update the cached value aAaaaMu.Lock() defer aAaaaMu.Unlock() // check to see if it's still stale, since we're now in a different // lock from when we first checked freshness; another goroutine might // have refreshed it in the meantime before we re-obtained our lock cached = aAaaa[auStr] if cached.isFresh() { return allNew(cached.upstreams), nil } name := repl.ReplaceAll(au.Name, "") port := repl.ReplaceAll(au.Port, "") ips, err := au.resolver.LookupIP(r.Context(), ipVersion, name) if err != nil { return nil, err } upstreams := make([]Upstream, len(ips)) for i, ip := range ips { upstreams[i] = Upstream{ Dial: net.JoinHostPort(ip.String(), port), } } // before adding a new one to the cache (as opposed to replacing stale one), make room if cache is full if cached.freshness.IsZero() && len(aAaaa) >= 100 { for randomKey := range aAaaa { delete(aAaaa, randomKey) break } } aAaaa[auStr] = aLookup{ aUpstreams: au, freshness: time.Now(), upstreams: upstreams, } return allNew(upstreams), nil } func (au AUpstreams) String() string { return net.JoinHostPort(au.Name, au.Port) } type aLookup struct { aUpstreams AUpstreams freshness time.Time upstreams []Upstream } func (al aLookup) isFresh() bool { return time.Since(al.freshness) < time.Duration(al.aUpstreams.Refresh) } // MultiUpstreams is a single dynamic upstream source that // aggregates the results of multiple dynamic upstream sources. // All configured sources will be queried in order, with their // results appended to the end of the list. Errors returned // from individual sources will be logged and the next source // will continue to be invoked. // // This module makes it easy to implement redundant cluster // failovers, especially in conjunction with the `first` load // balancing policy: if the first source returns an error or // no upstreams, the second source's upstreams will be used // naturally. type MultiUpstreams struct { // The list of upstream source modules to get upstreams from. // They will be queried in order, with their results appended // in the order they are returned. SourcesRaw []json.RawMessage `json:"sources,omitempty" caddy:"namespace=http.reverse_proxy.upstreams inline_key=source"` sources []UpstreamSource logger *zap.Logger } // CaddyModule returns the Caddy module information. func (MultiUpstreams) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.reverse_proxy.upstreams.multi", New: func() caddy.Module { return new(MultiUpstreams) }, } } func (mu *MultiUpstreams) Provision(ctx caddy.Context) error { mu.logger = ctx.Logger() if mu.SourcesRaw != nil { mod, err := ctx.LoadModule(mu, "SourcesRaw") if err != nil { return fmt.Errorf("loading upstream source modules: %v", err) } for _, src := range mod.([]any) { mu.sources = append(mu.sources, src.(UpstreamSource)) } } return nil } func (mu MultiUpstreams) GetUpstreams(r *http.Request) ([]*Upstream, error) { var upstreams []*Upstream for i, src := range mu.sources { select { case <-r.Context().Done(): return upstreams, context.Canceled default: } up, err := src.GetUpstreams(r) if err != nil { mu.logger.Error("upstream source returned error", zap.Int("source_idx", i), zap.Error(err)) } else if len(up) == 0 { mu.logger.Warn("upstream source returned 0 upstreams", zap.Int("source_idx", i)) } else { upstreams = append(upstreams, up...) } } return upstreams, nil } // UpstreamResolver holds the set of addresses of DNS resolvers of // upstream addresses type UpstreamResolver struct { // The addresses of DNS resolvers to use when looking up the addresses of proxy upstreams. // It accepts [network addresses](/docs/conventions#network-addresses) // with port range of only 1. If the host is an IP address, it will be dialed directly to resolve the upstream server. // If the host is not an IP address, the addresses are resolved using the [name resolution convention](https://golang.org/pkg/net/#hdr-Name_Resolution) of the Go standard library. // If the array contains more than 1 resolver address, one is chosen at random. Addresses []string `json:"addresses,omitempty"` netAddrs []caddy.NetworkAddress } // ParseAddresses parses all the configured network addresses // and ensures they're ready to be used. func (u *UpstreamResolver) ParseAddresses() error { for _, v := range u.Addresses { addr, err := caddy.ParseNetworkAddressWithDefaults(v, "udp", 53) if err != nil { return err } if addr.PortRangeSize() != 1 { return fmt.Errorf("resolver address must have exactly one address; cannot call %v", addr) } u.netAddrs = append(u.netAddrs, addr) } return nil } func allNew(upstreams []Upstream) []*Upstream { results := make([]*Upstream, len(upstreams)) for i := range upstreams { results[i] = &Upstream{Dial: upstreams[i].Dial} } return results } var ( srvs = make(map[string]srvLookup) srvsMu sync.RWMutex aAaaa = make(map[string]aLookup) aAaaaMu sync.RWMutex ) // Interface guards var ( _ caddy.Provisioner = (*SRVUpstreams)(nil) _ UpstreamSource = (*SRVUpstreams)(nil) _ caddy.Provisioner = (*AUpstreams)(nil) _ UpstreamSource = (*AUpstreams)(nil) )
Go
caddy/modules/caddyhttp/reverseproxy/fastcgi/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 fastcgi import ( "encoding/json" "net/http" "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" "github.com/caddyserver/caddy/v2/modules/caddyhttp/fileserver" "github.com/caddyserver/caddy/v2/modules/caddyhttp/reverseproxy" "github.com/caddyserver/caddy/v2/modules/caddyhttp/rewrite" ) func init() { httpcaddyfile.RegisterDirective("php_fastcgi", parsePHPFastCGI) } // UnmarshalCaddyfile deserializes Caddyfile tokens into h. // // transport fastcgi { // root <path> // split <at> // env <key> <value> // resolve_root_symlink // dial_timeout <duration> // read_timeout <duration> // write_timeout <duration> // capture_stderr // } func (t *Transport) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { for d.NextBlock(0) { switch d.Val() { case "root": if !d.NextArg() { return d.ArgErr() } t.Root = d.Val() case "split": t.SplitPath = d.RemainingArgs() if len(t.SplitPath) == 0 { return d.ArgErr() } case "env": args := d.RemainingArgs() if len(args) != 2 { return d.ArgErr() } if t.EnvVars == nil { t.EnvVars = make(map[string]string) } t.EnvVars[args[0]] = args[1] case "resolve_root_symlink": if d.NextArg() { return d.ArgErr() } t.ResolveRootSymlink = true case "dial_timeout": if !d.NextArg() { return d.ArgErr() } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("bad timeout value %s: %v", d.Val(), err) } t.DialTimeout = caddy.Duration(dur) case "read_timeout": if !d.NextArg() { return d.ArgErr() } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("bad timeout value %s: %v", d.Val(), err) } t.ReadTimeout = caddy.Duration(dur) case "write_timeout": if !d.NextArg() { return d.ArgErr() } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("bad timeout value %s: %v", d.Val(), err) } t.WriteTimeout = caddy.Duration(dur) case "capture_stderr": if d.NextArg() { return d.ArgErr() } t.CaptureStderr = true default: return d.Errf("unrecognized subdirective %s", d.Val()) } } } return nil } // parsePHPFastCGI parses the php_fastcgi directive, which has the same syntax // as the reverse_proxy directive (in fact, the reverse_proxy's directive // Unmarshaler is invoked by this function) but the resulting proxy is specially // configured for most™️ PHP apps over FastCGI. A line such as this: // // php_fastcgi localhost:7777 // // is equivalent to a route consisting of: // // # Add trailing slash for directory requests // @canonicalPath { // file {path}/index.php // not path */ // } // redir @canonicalPath {path}/ 308 // // # If the requested file does not exist, try index files // @indexFiles file { // try_files {path} {path}/index.php index.php // split_path .php // } // rewrite @indexFiles {http.matchers.file.relative} // // # Proxy PHP files to the FastCGI responder // @phpFiles path *.php // reverse_proxy @phpFiles localhost:7777 { // transport fastcgi { // split .php // } // } // // Thus, this directive produces multiple handlers, each with a different // matcher because multiple consecutive handlers are necessary to support // the common PHP use case. If this "common" config is not compatible // with a user's PHP requirements, they can use a manual approach based // on the example above to configure it precisely as they need. // // If a matcher is specified by the user, for example: // // php_fastcgi /subpath localhost:7777 // // then the resulting handlers are wrapped in a subroute that uses the // user's matcher as a prerequisite to enter the subroute. In other // words, the directive's matcher is necessary, but not sufficient. func parsePHPFastCGI(h httpcaddyfile.Helper) ([]httpcaddyfile.ConfigValue, error) { if !h.Next() { return nil, h.ArgErr() } // set up the transport for FastCGI, and specifically PHP fcgiTransport := Transport{} // set up the set of file extensions allowed to execute PHP code extensions := []string{".php"} // set the default index file for the try_files rewrites indexFile := "index.php" // set up for explicitly overriding try_files tryFiles := []string{} // if the user specified a matcher token, use that // matcher in a route that wraps both of our routes; // either way, strip the matcher token and pass // the remaining tokens to the unmarshaler so that // we can gain the rest of the reverse_proxy syntax userMatcherSet, err := h.ExtractMatcherSet() if err != nil { return nil, err } // make a new dispenser from the remaining tokens so that we // can reset the dispenser back to this point for the // reverse_proxy unmarshaler to read from it as well dispenser := h.NewFromNextSegment() // read the subdirectives that we allow as overrides to // the php_fastcgi shortcut // NOTE: we delete the tokens as we go so that the reverse_proxy // unmarshal doesn't see these subdirectives which it cannot handle for dispenser.Next() { for dispenser.NextBlock(0) { // ignore any sub-subdirectives that might // have the same name somewhere within // the reverse_proxy passthrough tokens if dispenser.Nesting() != 1 { continue } // parse the php_fastcgi subdirectives switch dispenser.Val() { case "root": if !dispenser.NextArg() { return nil, dispenser.ArgErr() } fcgiTransport.Root = dispenser.Val() dispenser.DeleteN(2) case "split": extensions = dispenser.RemainingArgs() dispenser.DeleteN(len(extensions) + 1) if len(extensions) == 0 { return nil, dispenser.ArgErr() } case "env": args := dispenser.RemainingArgs() dispenser.DeleteN(len(args) + 1) if len(args) != 2 { return nil, dispenser.ArgErr() } if fcgiTransport.EnvVars == nil { fcgiTransport.EnvVars = make(map[string]string) } fcgiTransport.EnvVars[args[0]] = args[1] case "index": args := dispenser.RemainingArgs() dispenser.DeleteN(len(args) + 1) if len(args) != 1 { return nil, dispenser.ArgErr() } indexFile = args[0] case "try_files": args := dispenser.RemainingArgs() dispenser.DeleteN(len(args) + 1) if len(args) < 1 { return nil, dispenser.ArgErr() } tryFiles = args case "resolve_root_symlink": args := dispenser.RemainingArgs() dispenser.DeleteN(len(args) + 1) fcgiTransport.ResolveRootSymlink = true case "dial_timeout": if !dispenser.NextArg() { return nil, dispenser.ArgErr() } dur, err := caddy.ParseDuration(dispenser.Val()) if err != nil { return nil, dispenser.Errf("bad timeout value %s: %v", dispenser.Val(), err) } fcgiTransport.DialTimeout = caddy.Duration(dur) dispenser.DeleteN(2) case "read_timeout": if !dispenser.NextArg() { return nil, dispenser.ArgErr() } dur, err := caddy.ParseDuration(dispenser.Val()) if err != nil { return nil, dispenser.Errf("bad timeout value %s: %v", dispenser.Val(), err) } fcgiTransport.ReadTimeout = caddy.Duration(dur) dispenser.DeleteN(2) case "write_timeout": if !dispenser.NextArg() { return nil, dispenser.ArgErr() } dur, err := caddy.ParseDuration(dispenser.Val()) if err != nil { return nil, dispenser.Errf("bad timeout value %s: %v", dispenser.Val(), err) } fcgiTransport.WriteTimeout = caddy.Duration(dur) dispenser.DeleteN(2) case "capture_stderr": args := dispenser.RemainingArgs() dispenser.DeleteN(len(args) + 1) fcgiTransport.CaptureStderr = true } } } // reset the dispenser after we're done so that the reverse_proxy // unmarshaler can read it from the start dispenser.Reset() // set up a route list that we'll append to routes := caddyhttp.RouteList{} // set the list of allowed path segments on which to split fcgiTransport.SplitPath = extensions // if the index is turned off, we skip the redirect and try_files if indexFile != "off" { // route to redirect to canonical path if index PHP file redirMatcherSet := caddy.ModuleMap{ "file": h.JSON(fileserver.MatchFile{ TryFiles: []string{"{http.request.uri.path}/" + indexFile}, }), "not": h.JSON(caddyhttp.MatchNot{ MatcherSetsRaw: []caddy.ModuleMap{ { "path": h.JSON(caddyhttp.MatchPath{"*/"}), }, }, }), } redirHandler := caddyhttp.StaticResponse{ StatusCode: caddyhttp.WeakString(strconv.Itoa(http.StatusPermanentRedirect)), Headers: http.Header{"Location": []string{"{http.request.orig_uri.path}/"}}, } redirRoute := caddyhttp.Route{ MatcherSetsRaw: []caddy.ModuleMap{redirMatcherSet}, HandlersRaw: []json.RawMessage{caddyconfig.JSONModuleObject(redirHandler, "handler", "static_response", nil)}, } // if tryFiles wasn't overridden, use a reasonable default if len(tryFiles) == 0 { tryFiles = []string{"{http.request.uri.path}", "{http.request.uri.path}/" + indexFile, indexFile} } // route to rewrite to PHP index file rewriteMatcherSet := caddy.ModuleMap{ "file": h.JSON(fileserver.MatchFile{ TryFiles: tryFiles, SplitPath: extensions, }), } rewriteHandler := rewrite.Rewrite{ URI: "{http.matchers.file.relative}", } rewriteRoute := caddyhttp.Route{ MatcherSetsRaw: []caddy.ModuleMap{rewriteMatcherSet}, HandlersRaw: []json.RawMessage{caddyconfig.JSONModuleObject(rewriteHandler, "handler", "rewrite", nil)}, } routes = append(routes, redirRoute, rewriteRoute) } // route to actually reverse proxy requests to PHP files; // match only requests that are for PHP files pathList := []string{} for _, ext := range extensions { pathList = append(pathList, "*"+ext) } rpMatcherSet := caddy.ModuleMap{ "path": h.JSON(pathList), } // create the reverse proxy handler which uses our FastCGI transport rpHandler := &reverseproxy.Handler{ TransportRaw: caddyconfig.JSONModuleObject(fcgiTransport, "protocol", "fastcgi", nil), } // the rest of the config is specified by the user // using the reverse_proxy directive syntax dispenser.Next() // consume the directive name err = rpHandler.UnmarshalCaddyfile(dispenser) if err != nil { return nil, err } err = rpHandler.FinalizeUnmarshalCaddyfile(h) if err != nil { return nil, err } // create the final reverse proxy route which is // conditional on matching PHP files rpRoute := caddyhttp.Route{ MatcherSetsRaw: []caddy.ModuleMap{rpMatcherSet}, HandlersRaw: []json.RawMessage{caddyconfig.JSONModuleObject(rpHandler, "handler", "reverse_proxy", nil)}, } subroute := caddyhttp.Subroute{ Routes: append(routes, rpRoute), } // the user's matcher is a prerequisite for ours, so // wrap ours in a subroute and return that if userMatcherSet != nil { return []httpcaddyfile.ConfigValue{ { Class: "route", Value: caddyhttp.Route{ MatcherSetsRaw: []caddy.ModuleMap{userMatcherSet}, HandlersRaw: []json.RawMessage{caddyconfig.JSONModuleObject(subroute, "handler", "subroute", nil)}, }, }, }, nil } // otherwise, return the literal subroute instead of // individual routes, to ensure they stay together and // are treated as a single unit, without necessarily // creating an actual subroute in the output return []httpcaddyfile.ConfigValue{ { Class: "route", Value: subroute, }, }, nil }
Go
caddy/modules/caddyhttp/reverseproxy/fastcgi/client.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Forked Jan. 2015 from http://bitbucket.org/PinIdea/fcgi_client // (which is forked from https://code.google.com/p/go-fastcgi-client/). // This fork contains several fixes and improvements by Matt Holt and // other contributors to the Caddy project. // Copyright 2012 Junqing Tan <ivan@mysqlab.net> and The Go Authors // Use of this source code is governed by a BSD-style // Part of source code is from Go fcgi package package fastcgi import ( "bufio" "bytes" "io" "mime/multipart" "net" "net/http" "net/http/httputil" "net/textproto" "net/url" "os" "path/filepath" "strconv" "strings" "time" "go.uber.org/zap" ) // FCGIListenSockFileno describes listen socket file number. const FCGIListenSockFileno uint8 = 0 // FCGIHeaderLen describes header length. const FCGIHeaderLen uint8 = 8 // Version1 describes the version. const Version1 uint8 = 1 // FCGINullRequestID describes the null request ID. const FCGINullRequestID uint8 = 0 // FCGIKeepConn describes keep connection mode. const FCGIKeepConn uint8 = 1 const ( // BeginRequest is the begin request flag. BeginRequest uint8 = iota + 1 // AbortRequest is the abort request flag. AbortRequest // EndRequest is the end request flag. EndRequest // Params is the parameters flag. Params // Stdin is the standard input flag. Stdin // Stdout is the standard output flag. Stdout // Stderr is the standard error flag. Stderr // Data is the data flag. Data // GetValues is the get values flag. GetValues // GetValuesResult is the get values result flag. GetValuesResult // UnknownType is the unknown type flag. UnknownType // MaxType is the maximum type flag. MaxType = UnknownType ) const ( // Responder is the responder flag. Responder uint8 = iota + 1 // Authorizer is the authorizer flag. Authorizer // Filter is the filter flag. Filter ) const ( // RequestComplete is the completed request flag. RequestComplete uint8 = iota // CantMultiplexConns is the multiplexed connections flag. CantMultiplexConns // Overloaded is the overloaded flag. Overloaded // UnknownRole is the unknown role flag. UnknownRole ) const ( // MaxConns is the maximum connections flag. MaxConns string = "MAX_CONNS" // MaxRequests is the maximum requests flag. MaxRequests string = "MAX_REQS" // MultiplexConns is the multiplex connections flag. MultiplexConns string = "MPXS_CONNS" ) const ( maxWrite = 65500 // 65530 may work, but for compatibility maxPad = 255 ) // for padding so we don't have to allocate all the time // not synchronized because we don't care what the contents are var pad [maxPad]byte // client implements a FastCGI client, which is a standard for // interfacing external applications with Web servers. type client struct { rwc net.Conn // keepAlive bool // TODO: implement reqID uint16 stderr bool logger *zap.Logger } // Do made the request and returns a io.Reader that translates the data read // from fcgi responder out of fcgi packet before returning it. func (c *client) Do(p map[string]string, req io.Reader) (r io.Reader, err error) { writer := &streamWriter{c: c} writer.buf = bufPool.Get().(*bytes.Buffer) writer.buf.Reset() defer bufPool.Put(writer.buf) err = writer.writeBeginRequest(uint16(Responder), 0) if err != nil { return } writer.recType = Params err = writer.writePairs(p) if err != nil { return } writer.recType = Stdin if req != nil { _, err = io.Copy(writer, req) if err != nil { return nil, err } } err = writer.FlushStream() if err != nil { return nil, err } r = &streamReader{c: c} return } // clientCloser is a io.ReadCloser. It wraps a io.Reader with a Closer // that closes the client connection. type clientCloser struct { rwc net.Conn r *streamReader io.Reader status int logger *zap.Logger } func (f clientCloser) Close() error { stderr := f.r.stderr.Bytes() if len(stderr) == 0 { return f.rwc.Close() } if f.status >= 400 { f.logger.Error("stderr", zap.ByteString("body", stderr)) } else { f.logger.Warn("stderr", zap.ByteString("body", stderr)) } return f.rwc.Close() } // Request returns a HTTP Response with Header and Body // from fcgi responder func (c *client) Request(p map[string]string, req io.Reader) (resp *http.Response, err error) { r, err := c.Do(p, req) if err != nil { return } rb := bufio.NewReader(r) tp := textproto.NewReader(rb) resp = new(http.Response) // Parse the response headers. mimeHeader, err := tp.ReadMIMEHeader() if err != nil && err != io.EOF { return } resp.Header = http.Header(mimeHeader) if resp.Header.Get("Status") != "" { statusNumber, statusInfo, statusIsCut := strings.Cut(resp.Header.Get("Status"), " ") resp.StatusCode, err = strconv.Atoi(statusNumber) if err != nil { return } if statusIsCut { resp.Status = statusInfo } } else { resp.StatusCode = http.StatusOK } // TODO: fixTransferEncoding ? resp.TransferEncoding = resp.Header["Transfer-Encoding"] resp.ContentLength, _ = strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 64) // wrap the response body in our closer closer := clientCloser{ rwc: c.rwc, r: r.(*streamReader), Reader: rb, status: resp.StatusCode, logger: noopLogger, } if chunked(resp.TransferEncoding) { closer.Reader = httputil.NewChunkedReader(rb) } if c.stderr { closer.logger = c.logger } resp.Body = closer return } // Get issues a GET request to the fcgi responder. func (c *client) Get(p map[string]string, body io.Reader, l int64) (resp *http.Response, err error) { p["REQUEST_METHOD"] = "GET" p["CONTENT_LENGTH"] = strconv.FormatInt(l, 10) return c.Request(p, body) } // Head issues a HEAD request to the fcgi responder. func (c *client) Head(p map[string]string) (resp *http.Response, err error) { p["REQUEST_METHOD"] = "HEAD" p["CONTENT_LENGTH"] = "0" return c.Request(p, nil) } // Options issues an OPTIONS request to the fcgi responder. func (c *client) Options(p map[string]string) (resp *http.Response, err error) { p["REQUEST_METHOD"] = "OPTIONS" p["CONTENT_LENGTH"] = "0" return c.Request(p, nil) } // Post issues a POST request to the fcgi responder. with request body // in the format that bodyType specified func (c *client) Post(p map[string]string, method string, bodyType string, body io.Reader, l int64) (resp *http.Response, err error) { if p == nil { p = make(map[string]string) } p["REQUEST_METHOD"] = strings.ToUpper(method) if len(p["REQUEST_METHOD"]) == 0 || p["REQUEST_METHOD"] == "GET" { p["REQUEST_METHOD"] = "POST" } p["CONTENT_LENGTH"] = strconv.FormatInt(l, 10) if len(bodyType) > 0 { p["CONTENT_TYPE"] = bodyType } else { p["CONTENT_TYPE"] = "application/x-www-form-urlencoded" } return c.Request(p, body) } // PostForm issues a POST to the fcgi responder, with form // as a string key to a list values (url.Values) func (c *client) PostForm(p map[string]string, data url.Values) (resp *http.Response, err error) { body := bytes.NewReader([]byte(data.Encode())) return c.Post(p, "POST", "application/x-www-form-urlencoded", body, int64(body.Len())) } // PostFile issues a POST to the fcgi responder in multipart(RFC 2046) standard, // with form as a string key to a list values (url.Values), // and/or with file as a string key to a list file path. func (c *client) PostFile(p map[string]string, data url.Values, file map[string]string) (resp *http.Response, err error) { buf := &bytes.Buffer{} writer := multipart.NewWriter(buf) bodyType := writer.FormDataContentType() for key, val := range data { for _, v0 := range val { err = writer.WriteField(key, v0) if err != nil { return } } } for key, val := range file { fd, e := os.Open(val) if e != nil { return nil, e } defer fd.Close() part, e := writer.CreateFormFile(key, filepath.Base(val)) if e != nil { return nil, e } _, err = io.Copy(part, fd) if err != nil { return } } err = writer.Close() if err != nil { return } return c.Post(p, "POST", bodyType, buf, int64(buf.Len())) } // SetReadTimeout sets the read timeout for future calls that read from the // fcgi responder. A zero value for t means no timeout will be set. func (c *client) SetReadTimeout(t time.Duration) error { if t != 0 { return c.rwc.SetReadDeadline(time.Now().Add(t)) } return nil } // SetWriteTimeout sets the write timeout for future calls that send data to // the fcgi responder. A zero value for t means no timeout will be set. func (c *client) SetWriteTimeout(t time.Duration) error { if t != 0 { return c.rwc.SetWriteDeadline(time.Now().Add(t)) } return nil } // Checks whether chunked is part of the encodings stack func chunked(te []string) bool { return len(te) > 0 && te[0] == "chunked" }
Go
caddy/modules/caddyhttp/reverseproxy/fastcgi/client_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. // NOTE: These tests were adapted from the original // repository from which this package was forked. // The tests are slow (~10s) and in dire need of rewriting. // As such, the tests have been disabled to speed up // automated builds until they can be properly written. package fastcgi import ( "bytes" "crypto/md5" "encoding/binary" "fmt" "io" "log" "math/rand" "net" "net/http" "net/http/fcgi" "net/url" "os" "path/filepath" "strconv" "strings" "testing" "time" ) // test fcgi protocol includes: // Get, Post, Post in multipart/form-data, and Post with files // each key should be the md5 of the value or the file uploaded // specify remote fcgi responder ip:port to test with php // test failed if the remote fcgi(script) failed md5 verification // and output "FAILED" in response const ( scriptFile = "/tank/www/fcgic_test.php" //ipPort = "remote-php-serv:59000" ipPort = "127.0.0.1:59000" ) var globalt *testing.T type FastCGIServer struct{} func (s FastCGIServer) ServeHTTP(resp http.ResponseWriter, req *http.Request) { if err := req.ParseMultipartForm(100000000); err != nil { log.Printf("[ERROR] failed to parse: %v", err) } stat := "PASSED" fmt.Fprintln(resp, "-") fileNum := 0 { length := 0 for k0, v0 := range req.Form { h := md5.New() _, _ = io.WriteString(h, v0[0]) _md5 := fmt.Sprintf("%x", h.Sum(nil)) length += len(k0) length += len(v0[0]) // echo error when key != _md5(val) if _md5 != k0 { fmt.Fprintln(resp, "server:err ", _md5, k0) stat = "FAILED" } } if req.MultipartForm != nil { fileNum = len(req.MultipartForm.File) for kn, fns := range req.MultipartForm.File { //fmt.Fprintln(resp, "server:filekey ", kn ) length += len(kn) for _, f := range fns { fd, err := f.Open() if err != nil { log.Println("server:", err) return } h := md5.New() l0, err := io.Copy(h, fd) if err != nil { log.Println(err) return } length += int(l0) defer fd.Close() md5 := fmt.Sprintf("%x", h.Sum(nil)) //fmt.Fprintln(resp, "server:filemd5 ", md5 ) if kn != md5 { fmt.Fprintln(resp, "server:err ", md5, kn) stat = "FAILED" } //fmt.Fprintln(resp, "server:filename ", f.Filename ) } } } fmt.Fprintln(resp, "server:got data length", length) } fmt.Fprintln(resp, "-"+stat+"-POST(", len(req.Form), ")-FILE(", fileNum, ")--") } func sendFcgi(reqType int, fcgiParams map[string]string, data []byte, posts map[string]string, files map[string]string) (content []byte) { conn, err := net.Dial("tcp", ipPort) if err != nil { log.Println("err:", err) return } fcgi := client{rwc: conn, reqID: 1} length := 0 var resp *http.Response switch reqType { case 0: if len(data) > 0 { length = len(data) rd := bytes.NewReader(data) resp, err = fcgi.Post(fcgiParams, "", "", rd, int64(rd.Len())) } else if len(posts) > 0 { values := url.Values{} for k, v := range posts { values.Set(k, v) length += len(k) + 2 + len(v) } resp, err = fcgi.PostForm(fcgiParams, values) } else { rd := bytes.NewReader(data) resp, err = fcgi.Get(fcgiParams, rd, int64(rd.Len())) } default: values := url.Values{} for k, v := range posts { values.Set(k, v) length += len(k) + 2 + len(v) } for k, v := range files { fi, _ := os.Lstat(v) length += len(k) + int(fi.Size()) } resp, err = fcgi.PostFile(fcgiParams, values, files) } if err != nil { log.Println("err:", err) return } defer resp.Body.Close() content, _ = io.ReadAll(resp.Body) log.Println("c: send data length ≈", length, string(content)) conn.Close() time.Sleep(250 * time.Millisecond) if bytes.Contains(content, []byte("FAILED")) { globalt.Error("Server return failed message") } return } func generateRandFile(size int) (p string, m string) { p = filepath.Join(os.TempDir(), "fcgict"+strconv.Itoa(rand.Int())) // open output file fo, err := os.Create(p) if err != nil { panic(err) } // close fo on exit and check for its returned error defer func() { if err := fo.Close(); err != nil { panic(err) } }() h := md5.New() for i := 0; i < size/16; i++ { buf := make([]byte, 16) binary.PutVarint(buf, rand.Int63()) if _, err := fo.Write(buf); err != nil { log.Printf("[ERROR] failed to write buffer: %v\n", err) } if _, err := h.Write(buf); err != nil { log.Printf("[ERROR] failed to write buffer: %v\n", err) } } m = fmt.Sprintf("%x", h.Sum(nil)) return } func DisabledTest(t *testing.T) { // TODO: test chunked reader globalt = t rand.Seed(time.Now().UTC().UnixNano()) // server go func() { listener, err := net.Listen("tcp", ipPort) if err != nil { log.Println("listener creation failed: ", err) } srv := new(FastCGIServer) if err := fcgi.Serve(listener, srv); err != nil { log.Print("[ERROR] failed to start server: ", err) } }() time.Sleep(250 * time.Millisecond) // init fcgiParams := make(map[string]string) fcgiParams["REQUEST_METHOD"] = "GET" fcgiParams["SERVER_PROTOCOL"] = "HTTP/1.1" //fcgi_params["GATEWAY_INTERFACE"] = "CGI/1.1" fcgiParams["SCRIPT_FILENAME"] = scriptFile // simple GET log.Println("test:", "get") sendFcgi(0, fcgiParams, nil, nil, nil) // simple post data log.Println("test:", "post") sendFcgi(0, fcgiParams, []byte("c4ca4238a0b923820dcc509a6f75849b=1&7b8b965ad4bca0e41ab51de7b31363a1=n"), nil, nil) log.Println("test:", "post data (more than 60KB)") data := "" for i := 0x00; i < 0xff; i++ { v0 := strings.Repeat(fmt.Sprint(i), 256) h := md5.New() _, _ = io.WriteString(h, v0) k0 := fmt.Sprintf("%x", h.Sum(nil)) data += k0 + "=" + url.QueryEscape(v0) + "&" } sendFcgi(0, fcgiParams, []byte(data), nil, nil) log.Println("test:", "post form (use url.Values)") p0 := make(map[string]string, 1) p0["c4ca4238a0b923820dcc509a6f75849b"] = "1" p0["7b8b965ad4bca0e41ab51de7b31363a1"] = "n" sendFcgi(1, fcgiParams, nil, p0, nil) log.Println("test:", "post forms (256 keys, more than 1MB)") p1 := make(map[string]string, 1) for i := 0x00; i < 0xff; i++ { v0 := strings.Repeat(fmt.Sprint(i), 4096) h := md5.New() _, _ = io.WriteString(h, v0) k0 := fmt.Sprintf("%x", h.Sum(nil)) p1[k0] = v0 } sendFcgi(1, fcgiParams, nil, p1, nil) log.Println("test:", "post file (1 file, 500KB)) ") f0 := make(map[string]string, 1) path0, m0 := generateRandFile(500000) f0[m0] = path0 sendFcgi(1, fcgiParams, nil, p1, f0) log.Println("test:", "post multiple files (2 files, 5M each) and forms (256 keys, more than 1MB data") path1, m1 := generateRandFile(5000000) f0[m1] = path1 sendFcgi(1, fcgiParams, nil, p1, f0) log.Println("test:", "post only files (2 files, 5M each)") sendFcgi(1, fcgiParams, nil, nil, f0) log.Println("test:", "post only 1 file") delete(f0, "m0") sendFcgi(1, fcgiParams, nil, nil, f0) if err := os.Remove(path0); err != nil { log.Println("[ERROR] failed to remove path: ", err) } if err := os.Remove(path1); err != nil { log.Println("[ERROR] failed to remove path: ", err) } }
Go
caddy/modules/caddyhttp/reverseproxy/fastcgi/fastcgi.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package fastcgi import ( "crypto/tls" "fmt" "net" "net/http" "path/filepath" "strconv" "strings" "time" "go.uber.org/zap" "go.uber.org/zap/zapcore" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" "github.com/caddyserver/caddy/v2/modules/caddyhttp/reverseproxy" "github.com/caddyserver/caddy/v2/modules/caddytls" ) var noopLogger = zap.NewNop() func init() { caddy.RegisterModule(Transport{}) } // Transport facilitates FastCGI communication. type Transport struct { // Use this directory as the fastcgi root directory. Defaults to the root // directory of the parent virtual host. Root string `json:"root,omitempty"` // The path in the URL will be split into two, with the first piece ending // with the value of SplitPath. The first piece will be assumed as the // actual resource (CGI script) name, and the second piece will be set to // PATH_INFO for the CGI script to use. // // Future enhancements should be careful to avoid CVE-2019-11043, // which can be mitigated with use of a try_files-like behavior // that 404s if the fastcgi path info is not found. SplitPath []string `json:"split_path,omitempty"` // Path declared as root directory will be resolved to its absolute value // after the evaluation of any symbolic links. // Due to the nature of PHP opcache, root directory path is cached: when // using a symlinked directory as root this could generate errors when // symlink is changed without php-fpm being restarted; enabling this // directive will set $_SERVER['DOCUMENT_ROOT'] to the real directory path. ResolveRootSymlink bool `json:"resolve_root_symlink,omitempty"` // Extra environment variables. EnvVars map[string]string `json:"env,omitempty"` // The duration used to set a deadline when connecting to an upstream. Default: `3s`. DialTimeout caddy.Duration `json:"dial_timeout,omitempty"` // The duration used to set a deadline when reading from the FastCGI server. ReadTimeout caddy.Duration `json:"read_timeout,omitempty"` // The duration used to set a deadline when sending to the FastCGI server. WriteTimeout caddy.Duration `json:"write_timeout,omitempty"` // Capture and log any messages sent by the upstream on stderr. Logs at WARN // level by default. If the response has a 4xx or 5xx status ERROR level will // be used instead. CaptureStderr bool `json:"capture_stderr,omitempty"` serverSoftware string logger *zap.Logger } // CaddyModule returns the Caddy module information. func (Transport) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.reverse_proxy.transport.fastcgi", New: func() caddy.Module { return new(Transport) }, } } // Provision sets up t. func (t *Transport) Provision(ctx caddy.Context) error { t.logger = ctx.Logger() if t.Root == "" { t.Root = "{http.vars.root}" } version, _ := caddy.Version() t.serverSoftware = "Caddy/" + version // Set a relatively short default dial timeout. // This is helpful to make load-balancer retries more speedy. if t.DialTimeout == 0 { t.DialTimeout = caddy.Duration(3 * time.Second) } return nil } // RoundTrip implements http.RoundTripper. func (t Transport) RoundTrip(r *http.Request) (*http.Response, error) { server := r.Context().Value(caddyhttp.ServerCtxKey).(*caddyhttp.Server) // Disallow null bytes in the request path, because // PHP upstreams may do bad things, like execute a // non-PHP file as PHP code. See #4574 if strings.Contains(r.URL.Path, "\x00") { return nil, caddyhttp.Error(http.StatusBadRequest, fmt.Errorf("invalid request path")) } env, err := t.buildEnv(r) if err != nil { return nil, fmt.Errorf("building environment: %v", err) } ctx := r.Context() // extract dial information from request (should have been embedded by the reverse proxy) network, address := "tcp", r.URL.Host if dialInfo, ok := reverseproxy.GetDialInfo(ctx); ok { network = dialInfo.Network address = dialInfo.Address } logCreds := server.Logs != nil && server.Logs.ShouldLogCredentials loggableReq := caddyhttp.LoggableHTTPRequest{ Request: r, ShouldLogCredentials: logCreds, } loggableEnv := loggableEnv{vars: env, logCredentials: logCreds} logger := t.logger.With( zap.Object("request", loggableReq), zap.Object("env", loggableEnv), ) logger.Debug("roundtrip", zap.String("dial", address), zap.Object("env", loggableEnv), zap.Object("request", loggableReq)) // connect to the backend dialer := net.Dialer{Timeout: time.Duration(t.DialTimeout)} conn, err := dialer.DialContext(ctx, network, address) if err != nil { return nil, fmt.Errorf("dialing backend: %v", err) } defer func() { // conn will be closed with the response body unless there's an error if err != nil { conn.Close() } }() // create the client that will facilitate the protocol client := client{ rwc: conn, reqID: 1, logger: logger, stderr: t.CaptureStderr, } // read/write timeouts if err = client.SetReadTimeout(time.Duration(t.ReadTimeout)); err != nil { return nil, fmt.Errorf("setting read timeout: %v", err) } if err = client.SetWriteTimeout(time.Duration(t.WriteTimeout)); err != nil { return nil, fmt.Errorf("setting write timeout: %v", err) } contentLength := r.ContentLength if contentLength == 0 { contentLength, _ = strconv.ParseInt(r.Header.Get("Content-Length"), 10, 64) } var resp *http.Response switch r.Method { case http.MethodHead: resp, err = client.Head(env) case http.MethodGet: resp, err = client.Get(env, r.Body, contentLength) case http.MethodOptions: resp, err = client.Options(env) default: resp, err = client.Post(env, r.Method, r.Header.Get("Content-Type"), r.Body, contentLength) } if err != nil { return nil, err } return resp, nil } // buildEnv returns a set of CGI environment variables for the request. func (t Transport) buildEnv(r *http.Request) (envVars, error) { repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) var env envVars // Separate remote IP and port; more lenient than net.SplitHostPort var ip, port string if idx := strings.LastIndex(r.RemoteAddr, ":"); idx > -1 { ip = r.RemoteAddr[:idx] port = r.RemoteAddr[idx+1:] } else { ip = r.RemoteAddr } // Remove [] from IPv6 addresses ip = strings.Replace(ip, "[", "", 1) ip = strings.Replace(ip, "]", "", 1) // make sure file root is absolute root, err := filepath.Abs(repl.ReplaceAll(t.Root, ".")) if err != nil { return nil, err } if t.ResolveRootSymlink { root, err = filepath.EvalSymlinks(root) if err != nil { return nil, err } } fpath := r.URL.Path scriptName := fpath docURI := fpath // split "actual path" from "path info" if configured var pathInfo string if splitPos := t.splitPos(fpath); splitPos > -1 { docURI = fpath[:splitPos] pathInfo = fpath[splitPos:] // Strip PATH_INFO from SCRIPT_NAME scriptName = strings.TrimSuffix(scriptName, pathInfo) } // Try to grab the path remainder from a file matcher // if we didn't get a split result here. // See https://github.com/caddyserver/caddy/issues/3718 if pathInfo == "" { pathInfo, _ = repl.GetString("http.matchers.file.remainder") } // SCRIPT_FILENAME is the absolute path of SCRIPT_NAME scriptFilename := caddyhttp.SanitizedPathJoin(root, scriptName) // Ensure the SCRIPT_NAME has a leading slash for compliance with RFC3875 // Info: https://tools.ietf.org/html/rfc3875#section-4.1.13 if scriptName != "" && !strings.HasPrefix(scriptName, "/") { scriptName = "/" + scriptName } // Get the request URL from context. The context stores the original URL in case // it was changed by a middleware such as rewrite. By default, we pass the // original URI in as the value of REQUEST_URI (the user can overwrite this // if desired). Most PHP apps seem to want the original URI. Besides, this is // how nginx defaults: http://stackoverflow.com/a/12485156/1048862 origReq := r.Context().Value(caddyhttp.OriginalRequestCtxKey).(http.Request) requestScheme := "http" if r.TLS != nil { requestScheme = "https" } reqHost, reqPort, err := net.SplitHostPort(r.Host) if err != nil { // whatever, just assume there was no port reqHost = r.Host } authUser, _ := repl.GetString("http.auth.user.id") // Some variables are unused but cleared explicitly to prevent // the parent environment from interfering. env = envVars{ // Variables defined in CGI 1.1 spec "AUTH_TYPE": "", // Not used "CONTENT_LENGTH": r.Header.Get("Content-Length"), "CONTENT_TYPE": r.Header.Get("Content-Type"), "GATEWAY_INTERFACE": "CGI/1.1", "PATH_INFO": pathInfo, "QUERY_STRING": r.URL.RawQuery, "REMOTE_ADDR": ip, "REMOTE_HOST": ip, // For speed, remote host lookups disabled "REMOTE_PORT": port, "REMOTE_IDENT": "", // Not used "REMOTE_USER": authUser, "REQUEST_METHOD": r.Method, "REQUEST_SCHEME": requestScheme, "SERVER_NAME": reqHost, "SERVER_PROTOCOL": r.Proto, "SERVER_SOFTWARE": t.serverSoftware, // Other variables "DOCUMENT_ROOT": root, "DOCUMENT_URI": docURI, "HTTP_HOST": r.Host, // added here, since not always part of headers "REQUEST_URI": origReq.URL.RequestURI(), "SCRIPT_FILENAME": scriptFilename, "SCRIPT_NAME": scriptName, } // compliance with the CGI specification requires that // PATH_TRANSLATED should only exist if PATH_INFO is defined. // Info: https://www.ietf.org/rfc/rfc3875 Page 14 if env["PATH_INFO"] != "" { env["PATH_TRANSLATED"] = caddyhttp.SanitizedPathJoin(root, pathInfo) // Info: http://www.oreilly.com/openbook/cgi/ch02_04.html } // compliance with the CGI specification requires that // the SERVER_PORT variable MUST be set to the TCP/IP port number on which this request is received from the client // even if the port is the default port for the scheme and could otherwise be omitted from a URI. // https://tools.ietf.org/html/rfc3875#section-4.1.15 if reqPort != "" { env["SERVER_PORT"] = reqPort } else if requestScheme == "http" { env["SERVER_PORT"] = "80" } else if requestScheme == "https" { env["SERVER_PORT"] = "443" } // Some web apps rely on knowing HTTPS or not if r.TLS != nil { env["HTTPS"] = "on" // and pass the protocol details in a manner compatible with apache's mod_ssl // (which is why these have a SSL_ prefix and not TLS_). v, ok := tlsProtocolStrings[r.TLS.Version] if ok { env["SSL_PROTOCOL"] = v } // and pass the cipher suite in a manner compatible with apache's mod_ssl for _, cs := range caddytls.SupportedCipherSuites() { if cs.ID == r.TLS.CipherSuite { env["SSL_CIPHER"] = cs.Name break } } } // Add env variables from config (with support for placeholders in values) for key, value := range t.EnvVars { env[key] = repl.ReplaceAll(value, "") } // Add all HTTP headers to env variables for field, val := range r.Header { header := strings.ToUpper(field) header = headerNameReplacer.Replace(header) env["HTTP_"+header] = strings.Join(val, ", ") } return env, nil } // splitPos returns the index where path should // be split based on t.SplitPath. func (t Transport) splitPos(path string) int { // TODO: from v1... // if httpserver.CaseSensitivePath { // return strings.Index(path, r.SplitPath) // } if len(t.SplitPath) == 0 { return 0 } lowerPath := strings.ToLower(path) for _, split := range t.SplitPath { if idx := strings.Index(lowerPath, strings.ToLower(split)); idx > -1 { return idx + len(split) } } return -1 } type envVars map[string]string // loggableEnv is a simple type to allow for speeding up zap log encoding. type loggableEnv struct { vars envVars logCredentials bool } func (env loggableEnv) MarshalLogObject(enc zapcore.ObjectEncoder) error { for k, v := range env.vars { if !env.logCredentials { switch strings.ToLower(k) { case "http_cookie", "http_set_cookie", "http_authorization", "http_proxy_authorization": v = "" } } enc.AddString(k, v) } return nil } // Map of supported protocols to Apache ssl_mod format // Note that these are slightly different from SupportedProtocols in caddytls/config.go var tlsProtocolStrings = map[uint16]string{ tls.VersionTLS10: "TLSv1", tls.VersionTLS11: "TLSv1.1", tls.VersionTLS12: "TLSv1.2", tls.VersionTLS13: "TLSv1.3", } var headerNameReplacer = strings.NewReplacer(" ", "_", "-", "_") // Interface guards var ( _ zapcore.ObjectMarshaler = (*loggableEnv)(nil) _ caddy.Provisioner = (*Transport)(nil) _ http.RoundTripper = (*Transport)(nil) )
Go
caddy/modules/caddyhttp/reverseproxy/fastcgi/header.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package fastcgi type header struct { Version uint8 Type uint8 ID uint16 ContentLength uint16 PaddingLength uint8 Reserved uint8 } func (h *header) init(recType uint8, reqID uint16, contentLength int) { h.Version = 1 h.Type = recType h.ID = reqID h.ContentLength = uint16(contentLength) h.PaddingLength = uint8(-contentLength & 7) }
Go
caddy/modules/caddyhttp/reverseproxy/fastcgi/pool.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package fastcgi import ( "bytes" "sync" ) var bufPool = sync.Pool{ New: func() any { return new(bytes.Buffer) }, }
Go
caddy/modules/caddyhttp/reverseproxy/fastcgi/reader.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package fastcgi import ( "bytes" "io" ) type streamReader struct { c *client rec record stderr bytes.Buffer } func (w *streamReader) Read(p []byte) (n int, err error) { for !w.rec.hasMore() { err = w.rec.fill(w.c.rwc) if err != nil { return 0, err } // standard error output if w.rec.h.Type == Stderr { if _, err = io.Copy(&w.stderr, &w.rec); err != nil { return 0, err } } } return w.rec.Read(p) }
Go
caddy/modules/caddyhttp/reverseproxy/fastcgi/record.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package fastcgi import ( "encoding/binary" "errors" "io" ) type record struct { h header lr io.LimitedReader padding int64 } func (rec *record) fill(r io.Reader) (err error) { rec.lr.N = rec.padding rec.lr.R = r if _, err = io.Copy(io.Discard, rec); err != nil { return } if err = binary.Read(r, binary.BigEndian, &rec.h); err != nil { return } if rec.h.Version != 1 { err = errors.New("fcgi: invalid header version") return } if rec.h.Type == EndRequest { err = io.EOF return } rec.lr.N = int64(rec.h.ContentLength) rec.padding = int64(rec.h.PaddingLength) return } func (rec *record) Read(p []byte) (n int, err error) { return rec.lr.Read(p) } func (rec *record) hasMore() bool { return rec.lr.N > 0 }
Go
caddy/modules/caddyhttp/reverseproxy/fastcgi/writer.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package fastcgi import ( "bytes" "encoding/binary" ) // streamWriter abstracts out the separation of a stream into discrete records. // It only writes maxWrite bytes at a time. type streamWriter struct { c *client h header buf *bytes.Buffer recType uint8 } func (w *streamWriter) writeRecord(recType uint8, content []byte) (err error) { w.h.init(recType, w.c.reqID, len(content)) w.buf.Write(pad[:8]) w.writeHeader() w.buf.Write(content) w.buf.Write(pad[:w.h.PaddingLength]) _, err = w.buf.WriteTo(w.c.rwc) return err } func (w *streamWriter) writeBeginRequest(role uint16, flags uint8) error { b := [8]byte{byte(role >> 8), byte(role), flags} return w.writeRecord(BeginRequest, b[:]) } func (w *streamWriter) Write(p []byte) (int, error) { // init header if w.buf.Len() < 8 { w.buf.Write(pad[:8]) } nn := 0 for len(p) > 0 { n := len(p) nl := maxWrite + 8 - w.buf.Len() if n > nl { n = nl w.buf.Write(p[:n]) if err := w.Flush(); err != nil { return nn, err } // reset headers w.buf.Write(pad[:8]) } else { w.buf.Write(p[:n]) } nn += n p = p[n:] } return nn, nil } func (w *streamWriter) endStream() error { // send empty record to close the stream return w.writeRecord(w.recType, nil) } func (w *streamWriter) writePairs(pairs map[string]string) error { b := make([]byte, 8) nn := 0 // init headers w.buf.Write(b) for k, v := range pairs { m := 8 + len(k) + len(v) if m > maxWrite { // param data size exceed 65535 bytes" vl := maxWrite - 8 - len(k) v = v[:vl] } n := encodeSize(b, uint32(len(k))) n += encodeSize(b[n:], uint32(len(v))) m = n + len(k) + len(v) if (nn + m) > maxWrite { if err := w.Flush(); err != nil { return err } // reset headers w.buf.Write(b) nn = 0 } nn += m w.buf.Write(b[:n]) w.buf.WriteString(k) w.buf.WriteString(v) } return w.FlushStream() } func encodeSize(b []byte, size uint32) int { if size > 127 { size |= 1 << 31 binary.BigEndian.PutUint32(b, size) return 4 } b[0] = byte(size) return 1 } // writeHeader populate header wire data in buf, it abuses buffer.Bytes() modification func (w *streamWriter) writeHeader() { h := w.buf.Bytes()[:8] h[0] = w.h.Version h[1] = w.h.Type binary.BigEndian.PutUint16(h[2:4], w.h.ID) binary.BigEndian.PutUint16(h[4:6], w.h.ContentLength) h[6] = w.h.PaddingLength h[7] = w.h.Reserved } // Flush write buffer data to the underlying connection, it assumes header data is the first 8 bytes of buf func (w *streamWriter) Flush() error { w.h.init(w.recType, w.c.reqID, w.buf.Len()-8) w.writeHeader() w.buf.Write(pad[:w.h.PaddingLength]) _, err := w.buf.WriteTo(w.c.rwc) return err } // FlushStream flush data then end current stream func (w *streamWriter) FlushStream() error { if err := w.Flush(); err != nil { return err } return w.endStream() }
Go
caddy/modules/caddyhttp/reverseproxy/forwardauth/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 forwardauth import ( "encoding/json" "net/http" "strings" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" "github.com/caddyserver/caddy/v2/modules/caddyhttp/headers" "github.com/caddyserver/caddy/v2/modules/caddyhttp/reverseproxy" "github.com/caddyserver/caddy/v2/modules/caddyhttp/rewrite" ) func init() { httpcaddyfile.RegisterDirective("forward_auth", parseCaddyfile) } // parseCaddyfile parses the forward_auth directive, which has the same syntax // as the reverse_proxy directive (in fact, the reverse_proxy's directive // Unmarshaler is invoked by this function) but the resulting proxy is specially // configured for most™️ auth gateways that support forward auth. The typical // config which looks something like this: // // forward_auth auth-gateway:9091 { // uri /authenticate?redirect=https://auth.example.com // copy_headers Remote-User Remote-Email // } // // is equivalent to a reverse_proxy directive like this: // // reverse_proxy auth-gateway:9091 { // method GET // rewrite /authenticate?redirect=https://auth.example.com // // header_up X-Forwarded-Method {method} // header_up X-Forwarded-Uri {uri} // // @good status 2xx // handle_response @good { // request_header { // Remote-User {http.reverse_proxy.header.Remote-User} // Remote-Email {http.reverse_proxy.header.Remote-Email} // } // } // } func parseCaddyfile(h httpcaddyfile.Helper) ([]httpcaddyfile.ConfigValue, error) { if !h.Next() { return nil, h.ArgErr() } // if the user specified a matcher token, use that // matcher in a route that wraps both of our routes; // either way, strip the matcher token and pass // the remaining tokens to the unmarshaler so that // we can gain the rest of the reverse_proxy syntax userMatcherSet, err := h.ExtractMatcherSet() if err != nil { return nil, err } // make a new dispenser from the remaining tokens so that we // can reset the dispenser back to this point for the // reverse_proxy unmarshaler to read from it as well dispenser := h.NewFromNextSegment() // create the reverse proxy handler rpHandler := &reverseproxy.Handler{ // set up defaults for header_up; reverse_proxy already deals with // adding the other three X-Forwarded-* headers, but for this flow, // we want to also send along the incoming method and URI since this // request will have a rewritten URI and method. Headers: &headers.Handler{ Request: &headers.HeaderOps{ Set: http.Header{ "X-Forwarded-Method": []string{"{http.request.method}"}, "X-Forwarded-Uri": []string{"{http.request.uri}"}, }, }, }, // we always rewrite the method to GET, which implicitly // turns off sending the incoming request's body, which // allows later middleware handlers to consume it Rewrite: &rewrite.Rewrite{ Method: "GET", }, HandleResponse: []caddyhttp.ResponseHandler{}, } // collect the headers to copy from the auth response // onto the original request, so they can get passed // through to a backend app headersToCopy := make(map[string]string) // read the subdirectives for configuring the forward_auth shortcut // NOTE: we delete the tokens as we go so that the reverse_proxy // unmarshal doesn't see these subdirectives which it cannot handle for dispenser.Next() { for dispenser.NextBlock(0) { // ignore any sub-subdirectives that might // have the same name somewhere within // the reverse_proxy passthrough tokens if dispenser.Nesting() != 1 { continue } // parse the forward_auth subdirectives switch dispenser.Val() { case "uri": if !dispenser.NextArg() { return nil, dispenser.ArgErr() } rpHandler.Rewrite.URI = dispenser.Val() dispenser.DeleteN(2) case "copy_headers": args := dispenser.RemainingArgs() hadBlock := false for nesting := dispenser.Nesting(); dispenser.NextBlock(nesting); { hadBlock = true args = append(args, dispenser.Val()) } // directive name + args dispenser.DeleteN(len(args) + 1) if hadBlock { // opening & closing brace dispenser.DeleteN(2) } for _, headerField := range args { if strings.Contains(headerField, ">") { parts := strings.Split(headerField, ">") headersToCopy[parts[0]] = parts[1] } else { headersToCopy[headerField] = headerField } } if len(headersToCopy) == 0 { return nil, dispenser.ArgErr() } } } } // reset the dispenser after we're done so that the reverse_proxy // unmarshaler can read it from the start dispenser.Reset() // the auth target URI must not be empty if rpHandler.Rewrite.URI == "" { return nil, dispenser.Errf("the 'uri' subdirective is required") } // set up handler for good responses; when a response // has 2xx status, then we will copy some headers from // the response onto the original request, and allow // handling to continue down the middleware chain, // by _not_ executing a terminal handler. goodResponseHandler := caddyhttp.ResponseHandler{ Match: &caddyhttp.ResponseMatcher{ StatusCode: []int{2}, }, Routes: []caddyhttp.Route{}, } handler := &headers.Handler{ Request: &headers.HeaderOps{ Set: http.Header{}, }, } // the list of headers to copy may be empty, but that's okay; we // need at least one handler in the routes for the response handling // logic in reverse_proxy to not skip this entry as empty. for from, to := range headersToCopy { handler.Request.Set.Set(to, "{http.reverse_proxy.header."+http.CanonicalHeaderKey(from)+"}") } goodResponseHandler.Routes = append( goodResponseHandler.Routes, caddyhttp.Route{ HandlersRaw: []json.RawMessage{caddyconfig.JSONModuleObject( handler, "handler", "headers", nil, )}, }, ) // note that when a response has any other status than 2xx, then we // use the reverse proxy's default behaviour of copying the response // back to the client, so we don't need to explicitly add a response // handler specifically for that behaviour; we do need the 2xx handler // though, to make handling fall through to handlers deeper in the chain. rpHandler.HandleResponse = append(rpHandler.HandleResponse, goodResponseHandler) // the rest of the config is specified by the user // using the reverse_proxy directive syntax dispenser.Next() // consume the directive name err = rpHandler.UnmarshalCaddyfile(dispenser) if err != nil { return nil, err } err = rpHandler.FinalizeUnmarshalCaddyfile(h) if err != nil { return nil, err } // create the final reverse proxy route rpRoute := caddyhttp.Route{ HandlersRaw: []json.RawMessage{caddyconfig.JSONModuleObject( rpHandler, "handler", "reverse_proxy", nil, )}, } // apply the user's matcher if any if userMatcherSet != nil { rpRoute.MatcherSetsRaw = []caddy.ModuleMap{userMatcherSet} } return []httpcaddyfile.ConfigValue{ { Class: "route", Value: rpRoute, }, }, nil }
Go
caddy/modules/caddyhttp/rewrite/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 rewrite import ( "encoding/json" "strconv" "strings" "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("rewrite", parseCaddyfileRewrite) httpcaddyfile.RegisterHandlerDirective("method", parseCaddyfileMethod) httpcaddyfile.RegisterHandlerDirective("uri", parseCaddyfileURI) httpcaddyfile.RegisterDirective("handle_path", parseCaddyfileHandlePath) } // parseCaddyfileRewrite sets up a basic rewrite handler from Caddyfile tokens. Syntax: // // rewrite [<matcher>] <to> // // Only URI components which are given in <to> will be set in the resulting URI. // See the docs for the rewrite handler for more information. func parseCaddyfileRewrite(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) { var rewr Rewrite for h.Next() { if !h.NextArg() { return nil, h.ArgErr() } rewr.URI = h.Val() if h.NextArg() { return nil, h.ArgErr() } } return rewr, nil } // parseCaddyfileMethod sets up a basic method rewrite handler from Caddyfile tokens. Syntax: // // method [<matcher>] <method> func parseCaddyfileMethod(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) { var rewr Rewrite for h.Next() { if !h.NextArg() { return nil, h.ArgErr() } rewr.Method = h.Val() if h.NextArg() { return nil, h.ArgErr() } } return rewr, nil } // parseCaddyfileURI sets up a handler for manipulating (but not "rewriting") the // URI from Caddyfile tokens. Syntax: // // uri [<matcher>] strip_prefix|strip_suffix|replace|path_regexp <target> [<replacement> [<limit>]] // // If strip_prefix or strip_suffix are used, then <target> will be stripped // only if it is the beginning or the end, respectively, of the URI path. If // replace is used, then <target> will be replaced with <replacement> across // the whole URI, up to <limit> times (or unlimited if unspecified). If // path_regexp is used, then regular expression replacements will be performed // on the path portion of the URI (and a limit cannot be set). func parseCaddyfileURI(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) { var rewr Rewrite for h.Next() { args := h.RemainingArgs() if len(args) < 2 { return nil, h.ArgErr() } switch args[0] { case "strip_prefix": if len(args) > 2 { return nil, h.ArgErr() } rewr.StripPathPrefix = args[1] if !strings.HasPrefix(rewr.StripPathPrefix, "/") { rewr.StripPathPrefix = "/" + rewr.StripPathPrefix } case "strip_suffix": if len(args) > 2 { return nil, h.ArgErr() } rewr.StripPathSuffix = args[1] case "replace": var find, replace, lim string switch len(args) { case 4: lim = args[3] fallthrough case 3: find = args[1] replace = args[2] default: return nil, h.ArgErr() } var limInt int if lim != "" { var err error limInt, err = strconv.Atoi(lim) if err != nil { return nil, h.Errf("limit must be an integer; invalid: %v", err) } } rewr.URISubstring = append(rewr.URISubstring, substrReplacer{ Find: find, Replace: replace, Limit: limInt, }) case "path_regexp": if len(args) != 3 { return nil, h.ArgErr() } find, replace := args[1], args[2] rewr.PathRegexp = append(rewr.PathRegexp, &regexReplacer{ Find: find, Replace: replace, }) default: return nil, h.Errf("unrecognized URI manipulation '%s'", args[0]) } } return rewr, nil } // parseCaddyfileHandlePath parses the handle_path directive. Syntax: // // handle_path [<matcher>] { // <directives...> // } // // Only path matchers (with a `/` prefix) are supported as this is a shortcut // for the handle directive with a strip_prefix rewrite. func parseCaddyfileHandlePath(h httpcaddyfile.Helper) ([]httpcaddyfile.ConfigValue, error) { if !h.Next() { return nil, h.ArgErr() } if !h.NextArg() { return nil, h.ArgErr() } // read the prefix to strip path := h.Val() if !strings.HasPrefix(path, "/") { return nil, h.Errf("path matcher must begin with '/', got %s", path) } // we only want to strip what comes before the '/' if // the user specified it (e.g. /api/* should only strip /api) var stripPath string if strings.HasSuffix(path, "/*") { stripPath = path[:len(path)-2] } else if strings.HasSuffix(path, "*") { stripPath = path[:len(path)-1] } else { stripPath = path } // the ParseSegmentAsSubroute function expects the cursor // to be at the token just before the block opening, // so we need to rewind because we already read past it h.Reset() h.Next() // parse the block contents as a subroute handler handler, err := httpcaddyfile.ParseSegmentAsSubroute(h) if err != nil { return nil, err } subroute, ok := handler.(*caddyhttp.Subroute) if !ok { return nil, h.Errf("segment was not parsed as a subroute") } // make a matcher on the path and everything below it pathMatcher := caddy.ModuleMap{ "path": h.JSON(caddyhttp.MatchPath{path}), } // build a route with a rewrite handler to strip the path prefix route := caddyhttp.Route{ HandlersRaw: []json.RawMessage{ caddyconfig.JSONModuleObject(Rewrite{ StripPathPrefix: stripPath, }, "handler", "rewrite", nil), }, } // prepend the route to the subroute subroute.Routes = append([]caddyhttp.Route{route}, subroute.Routes...) // build and return a route from the subroute return h.NewRoute(pathMatcher, subroute), nil }
Go
caddy/modules/caddyhttp/rewrite/rewrite.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 rewrite import ( "fmt" "net/http" "net/url" "regexp" "strconv" "strings" "go.uber.org/zap" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func init() { caddy.RegisterModule(Rewrite{}) } // Rewrite is a middleware which can rewrite/mutate HTTP requests. // // The Method and URI properties are "setters" (the request URI // will be overwritten with the given values). Other properties are // "modifiers" (they modify existing values in a differentiable // way). It is atypical to combine the use of setters and // modifiers in a single rewrite. // // To ensure consistent behavior, prefix and suffix stripping is // performed in the URL-decoded (unescaped, normalized) space by // default except for the specific bytes where an escape sequence // is used in the prefix or suffix pattern. // // For all modifiers, paths are cleaned before being modified so that // multiple, consecutive slashes are collapsed into a single slash, // and dot elements are resolved and removed. In the special case // of a prefix, suffix, or substring containing "//" (repeated slashes), // slashes will not be merged while cleaning the path so that // the rewrite can be interpreted literally. type Rewrite struct { // Changes the request's HTTP verb. Method string `json:"method,omitempty"` // Changes the request's URI, which consists of path and query string. // Only components of the URI that are specified will be changed. // For example, a value of "/foo.html" or "foo.html" will only change // the path and will preserve any existing query string. Similarly, a // value of "?a=b" will only change the query string and will not affect // the path. Both can also be changed: "/foo?a=b" - this sets both the // path and query string at the same time. // // You can also use placeholders. For example, to preserve the existing // query string, you might use: "?{http.request.uri.query}&a=b". Any // key-value pairs you add to the query string will not overwrite // existing values (individual pairs are append-only). // // To clear the query string, explicitly set an empty one: "?" URI string `json:"uri,omitempty"` // Strips the given prefix from the beginning of the URI path. // The prefix should be written in normalized (unescaped) form, // but if an escaping (`%xx`) is used, the path will be required // to have that same escape at that position in order to match. StripPathPrefix string `json:"strip_path_prefix,omitempty"` // Strips the given suffix from the end of the URI path. // The suffix should be written in normalized (unescaped) form, // but if an escaping (`%xx`) is used, the path will be required // to have that same escape at that position in order to match. StripPathSuffix string `json:"strip_path_suffix,omitempty"` // Performs substring replacements on the URI. URISubstring []substrReplacer `json:"uri_substring,omitempty"` // Performs regular expression replacements on the URI path. PathRegexp []*regexReplacer `json:"path_regexp,omitempty"` logger *zap.Logger } // CaddyModule returns the Caddy module information. func (Rewrite) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.handlers.rewrite", New: func() caddy.Module { return new(Rewrite) }, } } // Provision sets up rewr. func (rewr *Rewrite) Provision(ctx caddy.Context) error { rewr.logger = ctx.Logger() for i, rep := range rewr.PathRegexp { if rep.Find == "" { return fmt.Errorf("path_regexp find cannot be empty") } re, err := regexp.Compile(rep.Find) if err != nil { return fmt.Errorf("compiling regular expression %d: %v", i, err) } rep.re = re } return nil } func (rewr Rewrite) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) logger := rewr.logger.With( zap.Object("request", caddyhttp.LoggableHTTPRequest{Request: r}), ) changed := rewr.Rewrite(r, repl) if changed { logger.Debug("rewrote request", zap.String("method", r.Method), zap.String("uri", r.RequestURI), ) } return next.ServeHTTP(w, r) } // rewrite performs the rewrites on r using repl, which should // have been obtained from r, but is passed in for efficiency. // It returns true if any changes were made to r. func (rewr Rewrite) Rewrite(r *http.Request, repl *caddy.Replacer) bool { oldMethod := r.Method oldURI := r.RequestURI // method if rewr.Method != "" { r.Method = strings.ToUpper(repl.ReplaceAll(rewr.Method, "")) } // uri (path, query string and... fragment, because why not) if uri := rewr.URI; uri != "" { // find the bounds of each part of the URI that exist pathStart, qsStart, fragStart := -1, -1, -1 pathEnd, qsEnd := -1, -1 loop: for i, ch := range uri { switch { case ch == '?' && qsStart < 0: pathEnd, qsStart = i, i+1 case ch == '#' && fragStart < 0: // everything after fragment is fragment (very clear in RFC 3986 section 4.2) if qsStart < 0 { pathEnd = i } else { qsEnd = i } fragStart = i + 1 break loop case pathStart < 0 && qsStart < 0: pathStart = i } } if pathStart >= 0 && pathEnd < 0 { pathEnd = len(uri) } if qsStart >= 0 && qsEnd < 0 { qsEnd = len(uri) } // isolate the three main components of the URI var path, query, frag string if pathStart > -1 { path = uri[pathStart:pathEnd] } if qsStart > -1 { query = uri[qsStart:qsEnd] } if fragStart > -1 { frag = uri[fragStart:] } // build components which are specified, and store them // in a temporary variable so that they all read the // same version of the URI var newPath, newQuery, newFrag string if path != "" { // replace the `path` placeholder to escaped path pathPlaceholder := "{http.request.uri.path}" if strings.Contains(path, pathPlaceholder) { path = strings.ReplaceAll(path, pathPlaceholder, r.URL.EscapedPath()) } newPath = repl.ReplaceAll(path, "") } // before continuing, we need to check if a query string // snuck into the path component during replacements if before, after, found := strings.Cut(newPath, "?"); found { // recompute; new path contains a query string var injectedQuery string newPath, injectedQuery = before, after // don't overwrite explicitly-configured query string if query == "" { query = injectedQuery } } if query != "" { newQuery = buildQueryString(query, repl) } if frag != "" { newFrag = repl.ReplaceAll(frag, "") } // update the URI with the new components // only after building them if pathStart >= 0 { if path, err := url.PathUnescape(newPath); err != nil { r.URL.Path = newPath } else { r.URL.Path = path } } if qsStart >= 0 { r.URL.RawQuery = newQuery } if fragStart >= 0 { r.URL.Fragment = newFrag } } // strip path prefix or suffix if rewr.StripPathPrefix != "" { prefix := repl.ReplaceAll(rewr.StripPathPrefix, "") mergeSlashes := !strings.Contains(prefix, "//") changePath(r, func(escapedPath string) string { escapedPath = caddyhttp.CleanPath(escapedPath, mergeSlashes) return trimPathPrefix(escapedPath, prefix) }) } if rewr.StripPathSuffix != "" { suffix := repl.ReplaceAll(rewr.StripPathSuffix, "") mergeSlashes := !strings.Contains(suffix, "//") changePath(r, func(escapedPath string) string { escapedPath = caddyhttp.CleanPath(escapedPath, mergeSlashes) return reverse(trimPathPrefix(reverse(escapedPath), reverse(suffix))) }) } // substring replacements in URI for _, rep := range rewr.URISubstring { rep.do(r, repl) } // regular expression replacements on the path for _, rep := range rewr.PathRegexp { rep.do(r, repl) } // update the encoded copy of the URI r.RequestURI = r.URL.RequestURI() // return true if anything changed return r.Method != oldMethod || r.RequestURI != oldURI } // buildQueryString takes an input query string and // performs replacements on each component, returning // the resulting query string. This function appends // duplicate keys rather than replaces. func buildQueryString(qs string, repl *caddy.Replacer) string { var sb strings.Builder // first component must be key, which is the same // as if we just wrote a value in previous iteration wroteVal := true for len(qs) > 0 { // determine the end of this component, which will be at // the next equal sign or ampersand, whichever comes first nextEq, nextAmp := strings.Index(qs, "="), strings.Index(qs, "&") ampIsNext := nextAmp >= 0 && (nextAmp < nextEq || nextEq < 0) end := len(qs) // assume no delimiter remains... if ampIsNext { end = nextAmp // ...unless ampersand is first... } else if nextEq >= 0 && (nextEq < nextAmp || nextAmp < 0) { end = nextEq // ...or unless equal is first. } // consume the component and write the result comp := qs[:end] comp, _ = repl.ReplaceFunc(comp, func(name string, val any) (any, error) { if name == "http.request.uri.query" && wroteVal { return val, nil // already escaped } var valStr string switch v := val.(type) { case string: valStr = v case fmt.Stringer: valStr = v.String() case int: valStr = strconv.Itoa(v) default: valStr = fmt.Sprintf("%+v", v) } return url.QueryEscape(valStr), nil }) if end < len(qs) { end++ // consume delimiter } qs = qs[end:] // if previous iteration wrote a value, // that means we are writing a key if wroteVal { if sb.Len() > 0 && len(comp) > 0 { sb.WriteRune('&') } } else { sb.WriteRune('=') } sb.WriteString(comp) // remember for the next iteration that we just wrote a value, // which means the next iteration MUST write a key wroteVal = ampIsNext } return sb.String() } // trimPathPrefix is like strings.TrimPrefix, but customized for advanced URI // path prefix matching. The string prefix will be trimmed from the beginning // of escapedPath if escapedPath starts with prefix. Rather than a naive 1:1 // comparison of each byte to determine if escapedPath starts with prefix, // both strings are iterated in lock-step, and if prefix has a '%' encoding // at a particular position, escapedPath must also have the same encoding // representation for that character. In other words, if the prefix string // uses the escaped form for a character, escapedPath must literally use the // same escape at that position. Otherwise, all character comparisons are // performed in normalized/unescaped space. func trimPathPrefix(escapedPath, prefix string) string { var iPath, iPrefix int for { if iPath >= len(escapedPath) || iPrefix >= len(prefix) { break } prefixCh := prefix[iPrefix] ch := string(escapedPath[iPath]) if ch == "%" && prefixCh != '%' && len(escapedPath) >= iPath+3 { var err error ch, err = url.PathUnescape(escapedPath[iPath : iPath+3]) if err != nil { // should be impossible unless EscapedPath() is returning invalid values! return escapedPath } iPath += 2 } // prefix comparisons are case-insensitive to consistency with // path matcher, which is case-insensitive for good reasons if !strings.EqualFold(ch, string(prefixCh)) { return escapedPath } iPath++ iPrefix++ } // if we iterated through the entire prefix, we found it, so trim it if iPath >= len(prefix) { return escapedPath[iPath:] } // otherwise we did not find the prefix return escapedPath } func reverse(s string) string { r := []rune(s) for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { r[i], r[j] = r[j], r[i] } return string(r) } // substrReplacer describes either a simple and fast substring replacement. type substrReplacer struct { // A substring to find. Supports placeholders. Find string `json:"find,omitempty"` // The substring to replace with. Supports placeholders. Replace string `json:"replace,omitempty"` // Maximum number of replacements per string. // Set to <= 0 for no limit (default). Limit int `json:"limit,omitempty"` } // do performs the substring replacement on r. func (rep substrReplacer) do(r *http.Request, repl *caddy.Replacer) { if rep.Find == "" { return } lim := rep.Limit if lim == 0 { lim = -1 } find := repl.ReplaceAll(rep.Find, "") replace := repl.ReplaceAll(rep.Replace, "") mergeSlashes := !strings.Contains(rep.Find, "//") changePath(r, func(pathOrRawPath string) string { return strings.Replace(caddyhttp.CleanPath(pathOrRawPath, mergeSlashes), find, replace, lim) }) r.URL.RawQuery = strings.Replace(r.URL.RawQuery, find, replace, lim) } // regexReplacer describes a replacement using a regular expression. type regexReplacer struct { // The regular expression to find. Find string `json:"find,omitempty"` // The substring to replace with. Supports placeholders and // regular expression capture groups. Replace string `json:"replace,omitempty"` re *regexp.Regexp } func (rep regexReplacer) do(r *http.Request, repl *caddy.Replacer) { if rep.Find == "" || rep.re == nil { return } replace := repl.ReplaceAll(rep.Replace, "") changePath(r, func(pathOrRawPath string) string { return rep.re.ReplaceAllString(pathOrRawPath, replace) }) } func changePath(req *http.Request, newVal func(pathOrRawPath string) string) { req.URL.RawPath = newVal(req.URL.EscapedPath()) if p, err := url.PathUnescape(req.URL.RawPath); err == nil && p != "" { req.URL.Path = p } else { req.URL.Path = newVal(req.URL.Path) } // RawPath is only set if it's different from the normalized Path (std lib) if req.URL.RawPath == req.URL.Path { req.URL.RawPath = "" } } // Interface guard var _ caddyhttp.MiddlewareHandler = (*Rewrite)(nil)
Go
caddy/modules/caddyhttp/rewrite/rewrite_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 rewrite import ( "net/http" "regexp" "testing" "github.com/caddyserver/caddy/v2" ) func TestRewrite(t *testing.T) { repl := caddy.NewReplacer() for i, tc := range []struct { input, expect *http.Request rule Rewrite }{ { input: newRequest(t, "GET", "/"), expect: newRequest(t, "GET", "/"), }, { rule: Rewrite{Method: "GET", URI: "/"}, input: newRequest(t, "GET", "/"), expect: newRequest(t, "GET", "/"), }, { rule: Rewrite{Method: "POST"}, input: newRequest(t, "GET", "/"), expect: newRequest(t, "POST", "/"), }, { rule: Rewrite{URI: "/foo"}, input: newRequest(t, "GET", "/"), expect: newRequest(t, "GET", "/foo"), }, { rule: Rewrite{URI: "/foo"}, input: newRequest(t, "GET", "/bar"), expect: newRequest(t, "GET", "/foo"), }, { rule: Rewrite{URI: "foo"}, input: newRequest(t, "GET", "/"), expect: newRequest(t, "GET", "foo"), }, { rule: Rewrite{URI: "{http.request.uri}"}, input: newRequest(t, "GET", "/bar%3Fbaz?c=d"), expect: newRequest(t, "GET", "/bar%3Fbaz?c=d"), }, { rule: Rewrite{URI: "{http.request.uri.path}"}, input: newRequest(t, "GET", "/bar%3Fbaz"), expect: newRequest(t, "GET", "/bar%3Fbaz"), }, { rule: Rewrite{URI: "/foo{http.request.uri.path}"}, input: newRequest(t, "GET", "/bar"), expect: newRequest(t, "GET", "/foo/bar"), }, { rule: Rewrite{URI: "/index.php?p={http.request.uri.path}"}, input: newRequest(t, "GET", "/foo/bar"), expect: newRequest(t, "GET", "/index.php?p=%2Ffoo%2Fbar"), }, { rule: Rewrite{URI: "?a=b&{http.request.uri.query}"}, input: newRequest(t, "GET", "/"), expect: newRequest(t, "GET", "/?a=b"), }, { rule: Rewrite{URI: "/?c=d"}, input: newRequest(t, "GET", "/"), expect: newRequest(t, "GET", "/?c=d"), }, { rule: Rewrite{URI: "/?c=d"}, input: newRequest(t, "GET", "/?a=b"), expect: newRequest(t, "GET", "/?c=d"), }, { rule: Rewrite{URI: "?c=d"}, input: newRequest(t, "GET", "/foo"), expect: newRequest(t, "GET", "/foo?c=d"), }, { rule: Rewrite{URI: "/?c=d"}, input: newRequest(t, "GET", "/foo"), expect: newRequest(t, "GET", "/?c=d"), }, { rule: Rewrite{URI: "/?{http.request.uri.query}&c=d"}, input: newRequest(t, "GET", "/"), expect: newRequest(t, "GET", "/?c=d"), }, { rule: Rewrite{URI: "/foo?{http.request.uri.query}&c=d"}, input: newRequest(t, "GET", "/"), expect: newRequest(t, "GET", "/foo?c=d"), }, { rule: Rewrite{URI: "?{http.request.uri.query}&c=d"}, input: newRequest(t, "GET", "/foo"), expect: newRequest(t, "GET", "/foo?c=d"), }, { rule: Rewrite{URI: "{http.request.uri.path}?{http.request.uri.query}&c=d"}, input: newRequest(t, "GET", "/foo"), expect: newRequest(t, "GET", "/foo?c=d"), }, { rule: Rewrite{URI: "{http.request.uri.path}?{http.request.uri.query}&c=d"}, input: newRequest(t, "GET", "/foo"), expect: newRequest(t, "GET", "/foo?c=d"), }, { rule: Rewrite{URI: "/index.php?{http.request.uri.query}&c=d"}, input: newRequest(t, "GET", "/foo"), expect: newRequest(t, "GET", "/index.php?c=d"), }, { rule: Rewrite{URI: "?a=b&c=d"}, input: newRequest(t, "GET", "/foo"), expect: newRequest(t, "GET", "/foo?a=b&c=d"), }, { rule: Rewrite{URI: "/index.php?{http.request.uri.query}&c=d"}, input: newRequest(t, "GET", "/?a=b"), expect: newRequest(t, "GET", "/index.php?a=b&c=d"), }, { rule: Rewrite{URI: "/index.php?c=d&{http.request.uri.query}"}, input: newRequest(t, "GET", "/?a=b"), expect: newRequest(t, "GET", "/index.php?c=d&a=b"), }, { rule: Rewrite{URI: "/index.php?{http.request.uri.query}&p={http.request.uri.path}"}, input: newRequest(t, "GET", "/foo/bar?a=b"), expect: newRequest(t, "GET", "/index.php?a=b&p=%2Ffoo%2Fbar"), }, { rule: Rewrite{URI: "{http.request.uri.path}?"}, input: newRequest(t, "GET", "/foo/bar?a=b&c=d"), expect: newRequest(t, "GET", "/foo/bar"), }, { rule: Rewrite{URI: "?qs={http.request.uri.query}"}, input: newRequest(t, "GET", "/foo?a=b&c=d"), expect: newRequest(t, "GET", "/foo?qs=a%3Db%26c%3Dd"), }, { rule: Rewrite{URI: "/foo?{http.request.uri.query}#frag"}, input: newRequest(t, "GET", "/foo/bar?a=b"), expect: newRequest(t, "GET", "/foo?a=b#frag"), }, { rule: Rewrite{URI: "/foo{http.request.uri}"}, input: newRequest(t, "GET", "/bar?a=b"), expect: newRequest(t, "GET", "/foo/bar?a=b"), }, { rule: Rewrite{URI: "/foo{http.request.uri}"}, input: newRequest(t, "GET", "/bar"), expect: newRequest(t, "GET", "/foo/bar"), }, { rule: Rewrite{URI: "/foo{http.request.uri}?c=d"}, input: newRequest(t, "GET", "/bar?a=b"), expect: newRequest(t, "GET", "/foo/bar?c=d"), }, { rule: Rewrite{URI: "/foo{http.request.uri}?{http.request.uri.query}&c=d"}, input: newRequest(t, "GET", "/bar?a=b"), expect: newRequest(t, "GET", "/foo/bar?a=b&c=d"), }, { rule: Rewrite{URI: "{http.request.uri}"}, input: newRequest(t, "GET", "/bar?a=b"), expect: newRequest(t, "GET", "/bar?a=b"), }, { rule: Rewrite{URI: "{http.request.uri.path}bar?c=d"}, input: newRequest(t, "GET", "/foo/?a=b"), expect: newRequest(t, "GET", "/foo/bar?c=d"), }, { rule: Rewrite{URI: "/i{http.request.uri}"}, input: newRequest(t, "GET", "/%C2%B7%E2%88%B5.png"), expect: newRequest(t, "GET", "/i/%C2%B7%E2%88%B5.png"), }, { rule: Rewrite{URI: "/i{http.request.uri}"}, input: newRequest(t, "GET", "/·∵.png?a=b"), expect: newRequest(t, "GET", "/i/%C2%B7%E2%88%B5.png?a=b"), }, { rule: Rewrite{URI: "/i{http.request.uri}"}, input: newRequest(t, "GET", "/%C2%B7%E2%88%B5.png?a=b"), expect: newRequest(t, "GET", "/i/%C2%B7%E2%88%B5.png?a=b"), }, { rule: Rewrite{URI: "/bar#?"}, input: newRequest(t, "GET", "/foo#fragFirst?c=d"), // not a valid query string (is part of fragment) expect: newRequest(t, "GET", "/bar#?"), // I think this is right? but who knows; std lib drops fragment when parsing }, { rule: Rewrite{URI: "/bar"}, input: newRequest(t, "GET", "/foo#fragFirst?c=d"), expect: newRequest(t, "GET", "/bar#fragFirst?c=d"), }, { rule: Rewrite{StripPathPrefix: "/prefix"}, input: newRequest(t, "GET", "/foo/bar"), expect: newRequest(t, "GET", "/foo/bar"), }, { rule: Rewrite{StripPathPrefix: "/prefix"}, input: newRequest(t, "GET", "/prefix/foo/bar"), expect: newRequest(t, "GET", "/foo/bar"), }, { rule: Rewrite{StripPathPrefix: "/prefix"}, input: newRequest(t, "GET", "/prefix"), expect: newRequest(t, "GET", ""), }, { rule: Rewrite{StripPathPrefix: "/prefix"}, input: newRequest(t, "GET", "/"), expect: newRequest(t, "GET", "/"), }, { rule: Rewrite{StripPathPrefix: "/prefix"}, input: newRequest(t, "GET", "/prefix/foo%2Fbar"), expect: newRequest(t, "GET", "/foo%2Fbar"), }, { rule: Rewrite{StripPathPrefix: "/prefix"}, input: newRequest(t, "GET", "/foo/prefix/bar"), expect: newRequest(t, "GET", "/foo/prefix/bar"), }, { rule: Rewrite{StripPathPrefix: "//prefix"}, // scheme and host needed for URL parser to succeed in setting up test input: newRequest(t, "GET", "http://host//prefix/foo/bar"), expect: newRequest(t, "GET", "http://host/foo/bar"), }, { rule: Rewrite{StripPathPrefix: "//prefix"}, input: newRequest(t, "GET", "/prefix/foo/bar"), expect: newRequest(t, "GET", "/prefix/foo/bar"), }, { rule: Rewrite{StripPathPrefix: "/a%2Fb/c"}, input: newRequest(t, "GET", "/a%2Fb/c/d"), expect: newRequest(t, "GET", "/d"), }, { rule: Rewrite{StripPathPrefix: "/a%2Fb/c"}, input: newRequest(t, "GET", "/a%2fb/c/d"), expect: newRequest(t, "GET", "/d"), }, { rule: Rewrite{StripPathPrefix: "/a/b/c"}, input: newRequest(t, "GET", "/a%2Fb/c/d"), expect: newRequest(t, "GET", "/d"), }, { rule: Rewrite{StripPathPrefix: "/a%2Fb/c"}, input: newRequest(t, "GET", "/a/b/c/d"), expect: newRequest(t, "GET", "/a/b/c/d"), }, { rule: Rewrite{StripPathPrefix: "//a%2Fb/c"}, input: newRequest(t, "GET", "/a/b/c/d"), expect: newRequest(t, "GET", "/a/b/c/d"), }, { rule: Rewrite{StripPathSuffix: "/suffix"}, input: newRequest(t, "GET", "/foo/bar"), expect: newRequest(t, "GET", "/foo/bar"), }, { rule: Rewrite{StripPathSuffix: "suffix"}, input: newRequest(t, "GET", "/foo/bar/suffix"), expect: newRequest(t, "GET", "/foo/bar/"), }, { rule: Rewrite{StripPathSuffix: "suffix"}, input: newRequest(t, "GET", "/foo%2Fbar/suffix"), expect: newRequest(t, "GET", "/foo%2Fbar/"), }, { rule: Rewrite{StripPathSuffix: "%2fsuffix"}, input: newRequest(t, "GET", "/foo%2Fbar%2fsuffix"), expect: newRequest(t, "GET", "/foo%2Fbar"), }, { rule: Rewrite{StripPathSuffix: "/suffix"}, input: newRequest(t, "GET", "/foo/suffix/bar"), expect: newRequest(t, "GET", "/foo/suffix/bar"), }, { rule: Rewrite{URISubstring: []substrReplacer{{Find: "findme", Replace: "replaced"}}}, input: newRequest(t, "GET", "/foo/bar"), expect: newRequest(t, "GET", "/foo/bar"), }, { rule: Rewrite{URISubstring: []substrReplacer{{Find: "findme", Replace: "replaced"}}}, input: newRequest(t, "GET", "/foo/findme/bar"), expect: newRequest(t, "GET", "/foo/replaced/bar"), }, { rule: Rewrite{URISubstring: []substrReplacer{{Find: "findme", Replace: "replaced"}}}, input: newRequest(t, "GET", "/foo/findme%2Fbar"), expect: newRequest(t, "GET", "/foo/replaced%2Fbar"), }, { rule: Rewrite{PathRegexp: []*regexReplacer{{Find: "/{2,}", Replace: "/"}}}, input: newRequest(t, "GET", "/foo//bar///baz?a=b//c"), expect: newRequest(t, "GET", "/foo/bar/baz?a=b//c"), }, } { // copy the original input just enough so that we can // compare it after the rewrite to see if it changed urlCopy := *tc.input.URL originalInput := &http.Request{ Method: tc.input.Method, RequestURI: tc.input.RequestURI, URL: &urlCopy, } // populate the replacer just enough for our tests repl.Set("http.request.uri", tc.input.RequestURI) repl.Set("http.request.uri.path", tc.input.URL.Path) repl.Set("http.request.uri.query", tc.input.URL.RawQuery) // we can't directly call Provision() without a valid caddy.Context // (TODO: fix that) so here we ad-hoc compile the regex for _, rep := range tc.rule.PathRegexp { re, err := regexp.Compile(rep.Find) if err != nil { t.Fatal(err) } rep.re = re } changed := tc.rule.Rewrite(tc.input, repl) if expected, actual := !reqEqual(originalInput, tc.input), changed; expected != actual { t.Errorf("Test %d: Expected changed=%t but was %t", i, expected, actual) } if expected, actual := tc.expect.Method, tc.input.Method; expected != actual { t.Errorf("Test %d: Expected Method='%s' but got '%s'", i, expected, actual) } if expected, actual := tc.expect.RequestURI, tc.input.RequestURI; expected != actual { t.Errorf("Test %d: Expected RequestURI='%s' but got '%s'", i, expected, actual) } if expected, actual := tc.expect.URL.String(), tc.input.URL.String(); expected != actual { t.Errorf("Test %d: Expected URL='%s' but got '%s'", i, expected, actual) } if expected, actual := tc.expect.URL.RequestURI(), tc.input.URL.RequestURI(); expected != actual { t.Errorf("Test %d: Expected URL.RequestURI()='%s' but got '%s'", i, expected, actual) } if expected, actual := tc.expect.URL.Fragment, tc.input.URL.Fragment; expected != actual { t.Errorf("Test %d: Expected URL.Fragment='%s' but got '%s'", i, expected, actual) } } } func newRequest(t *testing.T, method, uri string) *http.Request { req, err := http.NewRequest(method, uri, nil) if err != nil { t.Fatalf("error creating request: %v", err) } req.RequestURI = req.URL.RequestURI() // simulate incoming request return req } // reqEqual if r1 and r2 are equal enough for our purposes. func reqEqual(r1, r2 *http.Request) bool { if r1.Method != r2.Method { return false } if r1.RequestURI != r2.RequestURI { return false } if (r1.URL == nil && r2.URL != nil) || (r1.URL != nil && r2.URL == nil) { return false } if r1.URL == nil && r2.URL == nil { return true } return r1.URL.Scheme == r2.URL.Scheme && r1.URL.Host == r2.URL.Host && r1.URL.Path == r2.URL.Path && r1.URL.RawPath == r2.URL.RawPath && r1.URL.RawQuery == r2.URL.RawQuery && r1.URL.Fragment == r2.URL.Fragment }
Go
caddy/modules/caddyhttp/standard/imports.go
package standard import ( // standard Caddy HTTP app modules _ "github.com/caddyserver/caddy/v2/modules/caddyhttp" _ "github.com/caddyserver/caddy/v2/modules/caddyhttp/caddyauth" _ "github.com/caddyserver/caddy/v2/modules/caddyhttp/encode" _ "github.com/caddyserver/caddy/v2/modules/caddyhttp/encode/brotli" _ "github.com/caddyserver/caddy/v2/modules/caddyhttp/encode/gzip" _ "github.com/caddyserver/caddy/v2/modules/caddyhttp/encode/zstd" _ "github.com/caddyserver/caddy/v2/modules/caddyhttp/fileserver" _ "github.com/caddyserver/caddy/v2/modules/caddyhttp/headers" _ "github.com/caddyserver/caddy/v2/modules/caddyhttp/map" _ "github.com/caddyserver/caddy/v2/modules/caddyhttp/proxyprotocol" _ "github.com/caddyserver/caddy/v2/modules/caddyhttp/push" _ "github.com/caddyserver/caddy/v2/modules/caddyhttp/requestbody" _ "github.com/caddyserver/caddy/v2/modules/caddyhttp/reverseproxy" _ "github.com/caddyserver/caddy/v2/modules/caddyhttp/reverseproxy/fastcgi" _ "github.com/caddyserver/caddy/v2/modules/caddyhttp/reverseproxy/forwardauth" _ "github.com/caddyserver/caddy/v2/modules/caddyhttp/rewrite" _ "github.com/caddyserver/caddy/v2/modules/caddyhttp/templates" _ "github.com/caddyserver/caddy/v2/modules/caddyhttp/tracing" )
Go
caddy/modules/caddyhttp/templates/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 templates import ( "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func init() { httpcaddyfile.RegisterHandlerDirective("templates", parseCaddyfile) } // parseCaddyfile sets up the handler from Caddyfile tokens. Syntax: // // templates [<matcher>] { // mime <types...> // between <open_delim> <close_delim> // root <path> // } func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) { t := new(Templates) for h.Next() { for h.NextBlock(0) { switch h.Val() { case "mime": t.MIMETypes = h.RemainingArgs() if len(t.MIMETypes) == 0 { return nil, h.ArgErr() } case "between": t.Delimiters = h.RemainingArgs() if len(t.Delimiters) != 2 { return nil, h.ArgErr() } case "root": if !h.Args(&t.FileRoot) { return nil, h.ArgErr() } } } } return t, nil }
Go
caddy/modules/caddyhttp/templates/frontmatter.go
package templates import ( "encoding/json" "fmt" "strings" "unicode" "github.com/BurntSushi/toml" "gopkg.in/yaml.v3" ) func extractFrontMatter(input string) (map[string]any, string, error) { // get the bounds of the first non-empty line var firstLineStart, firstLineEnd int lineEmpty := true for i, b := range input { if b == '\n' { firstLineStart = firstLineEnd if firstLineStart > 0 { firstLineStart++ // skip newline character } firstLineEnd = i if !lineEmpty { break } continue } lineEmpty = lineEmpty && unicode.IsSpace(b) } firstLine := input[firstLineStart:firstLineEnd] // ensure residue windows carriage return byte is removed firstLine = strings.TrimSpace(firstLine) // see what kind of front matter there is, if any var closingFence []string var fmParser func([]byte) (map[string]any, error) for _, fmType := range supportedFrontMatterTypes { if firstLine == fmType.FenceOpen { closingFence = fmType.FenceClose fmParser = fmType.ParseFunc } } if fmParser == nil { // no recognized front matter; whole document is body return nil, input, nil } // find end of front matter var fmEndFence string fmEndFenceStart := -1 for _, fence := range closingFence { index := strings.Index(input[firstLineEnd:], "\n"+fence) if index >= 0 { fmEndFenceStart = index fmEndFence = fence break } } if fmEndFenceStart < 0 { return nil, "", fmt.Errorf("unterminated front matter") } fmEndFenceStart += firstLineEnd + 1 // add 1 to account for newline // extract and parse front matter frontMatter := input[firstLineEnd:fmEndFenceStart] fm, err := fmParser([]byte(frontMatter)) if err != nil { return nil, "", err } // the rest is the body body := input[fmEndFenceStart+len(fmEndFence):] return fm, body, nil } func yamlFrontMatter(input []byte) (map[string]any, error) { m := make(map[string]any) err := yaml.Unmarshal(input, &m) return m, err } func tomlFrontMatter(input []byte) (map[string]any, error) { m := make(map[string]any) err := toml.Unmarshal(input, &m) return m, err } func jsonFrontMatter(input []byte) (map[string]any, error) { input = append([]byte{'{'}, input...) input = append(input, '}') m := make(map[string]any) err := json.Unmarshal(input, &m) return m, err } type parsedMarkdownDoc struct { Meta map[string]any `json:"meta,omitempty"` Body string `json:"body,omitempty"` } type frontMatterType struct { FenceOpen string FenceClose []string ParseFunc func(input []byte) (map[string]any, error) } var supportedFrontMatterTypes = []frontMatterType{ { FenceOpen: "---", FenceClose: []string{"---", "..."}, ParseFunc: yamlFrontMatter, }, { FenceOpen: "+++", FenceClose: []string{"+++"}, ParseFunc: tomlFrontMatter, }, { FenceOpen: "{", FenceClose: []string{"}"}, ParseFunc: jsonFrontMatter, }, }
Go
caddy/modules/caddyhttp/templates/frontmatter_fuzz.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 gofuzz package templates func FuzzExtractFrontMatter(data []byte) int { _, _, err := extractFrontMatter(string(data)) if err != nil { return 0 } return 1 }
Go
caddy/modules/caddyhttp/templates/templates.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 templates import ( "bytes" "errors" "fmt" "net/http" "strconv" "strings" "text/template" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func init() { caddy.RegisterModule(Templates{}) } // Templates is a middleware which executes response bodies as Go templates. // The syntax is documented in the Go standard library's // [text/template package](https://golang.org/pkg/text/template/). // // ⚠️ Template functions/actions are still experimental, so they are subject to change. // // Custom template functions can be registered by creating a plugin module under the `http.handlers.templates.functions.*` namespace that implements the `CustomFunctions` interface. // // [All Sprig functions](https://masterminds.github.io/sprig/) are supported. // // In addition to the standard functions and the Sprig library, Caddy adds // extra functions and data that are available to a template: // // ##### `.Args` // // A slice of arguments passed to this page/context, for example as the result of a `include`. // // ``` // {{index .Args 0}} // first argument // ``` // // ##### `.Cookie` // // Gets the value of a cookie by name. // // ``` // {{.Cookie "cookiename"}} // ``` // // ##### `env` // // Gets an environment variable. // // ``` // {{env "VAR_NAME"}} // ``` // // ##### `placeholder` // // Gets an [placeholder variable](/docs/conventions#placeholders). // The braces (`{}`) have to be omitted. // // ``` // {{placeholder "http.request.uri.path"}} // {{placeholder "http.error.status_code"}} // ``` // // ##### `.Host` // // Returns the hostname portion (no port) of the Host header of the HTTP request. // // ``` // {{.Host}} // ``` // // ##### `httpInclude` // // Includes the contents of another file, and renders it in-place, // by making a virtual HTTP request (also known as a sub-request). // The URI path must exist on the same virtual server because the // request does not use sockets; instead, the request is crafted in // memory and the handler is invoked directly for increased efficiency. // // ``` // {{httpInclude "/foo/bar?q=val"}} // ``` // // ##### `import` // // Reads and returns the contents of another file, and parses it // as a template, adding any template definitions to the template // stack. If there are no definitions, the filepath will be the // definition name. Any {{ define }} blocks will be accessible by // {{ template }} or {{ block }}. Imports must happen before the // template or block action is called. Note that the contents are // NOT escaped, so you should only import trusted template files. // // **filename.html** // ``` // {{ define "main" }} // content // {{ end }} // ``` // // **index.html** // ``` // {{ import "/path/to/filename.html" }} // {{ template "main" }} // ``` // // ##### `include` // // Includes the contents of another file, rendering it in-place. // Optionally can pass key-value pairs as arguments to be accessed // by the included file. Note that the contents are NOT escaped, // so you should only include trusted template files. // // ``` // {{include "path/to/file.html"}} // no arguments // {{include "path/to/file.html" "arg1" 2 "value 3"}} // with arguments // ``` // // ##### `readFile` // // Reads and returns the contents of another file, as-is. // Note that the contents are NOT escaped, so you should // only read trusted files. // // ``` // {{readFile "path/to/file.html"}} // ``` // // ##### `listFiles` // // Returns a list of the files in the given directory, which is relative to the template context's file root. // // ``` // {{listFiles "/mydir"}} // ``` // // ##### `markdown` // // Renders the given Markdown text as HTML and returns it. This uses the // [Goldmark](https://github.com/yuin/goldmark) library, // which is CommonMark compliant. It also has these extensions // enabled: Github Flavored Markdown, Footnote, and syntax // highlighting provided by [Chroma](https://github.com/alecthomas/chroma). // // ``` // {{markdown "My _markdown_ text"}} // ``` // // ##### `.RemoteIP` // // Returns the client's IP address. // // ``` // {{.RemoteIP}} // ``` // // ##### `.Req` // // Accesses the current HTTP request, which has various fields, including: // // - `.Method` - the method // - `.URL` - the URL, which in turn has component fields (Scheme, Host, Path, etc.) // - `.Header` - the header fields // - `.Host` - the Host or :authority header of the request // // ``` // {{.Req.Header.Get "User-Agent"}} // ``` // // ##### `.OriginalReq` // // Like .Req, except it accesses the original HTTP request before rewrites or other internal modifications. // // ##### `.RespHeader.Add` // // Adds a header field to the HTTP response. // // ``` // {{.RespHeader.Add "Field-Name" "val"}} // ``` // // ##### `.RespHeader.Del` // // Deletes a header field on the HTTP response. // // ``` // {{.RespHeader.Del "Field-Name"}} // ``` // // ##### `.RespHeader.Set` // // Sets a header field on the HTTP response, replacing any existing value. // // ``` // {{.RespHeader.Set "Field-Name" "val"}} // ``` // // ##### `httpError` // // Returns an error with the given status code to the HTTP handler chain. // // ``` // {{if not (fileExists $includedFile)}}{{httpError 404}}{{end}} // ``` // // ##### `splitFrontMatter` // // Splits front matter out from the body. Front matter is metadata that appears at the very beginning of a file or string. Front matter can be in YAML, TOML, or JSON formats: // // **TOML** front matter starts and ends with `+++`: // // ``` // +++ // template = "blog" // title = "Blog Homepage" // sitename = "A Caddy site" // +++ // ``` // // **YAML** is surrounded by `---`: // // ``` // --- // template: blog // title: Blog Homepage // sitename: A Caddy site // --- // ``` // // **JSON** is simply `{` and `}`: // // ``` // // { // "template": "blog", // "title": "Blog Homepage", // "sitename": "A Caddy site" // } // // ``` // // The resulting front matter will be made available like so: // // - `.Meta` to access the metadata fields, for example: `{{$parsed.Meta.title}}` // - `.Body` to access the body after the front matter, for example: `{{markdown $parsed.Body}}` // // ##### `stripHTML` // // Removes HTML from a string. // // ``` // {{stripHTML "Shows <b>only</b> text content"}} // ``` // // ##### `humanize` // // Transforms size and time inputs to a human readable format. // This uses the [go-humanize](https://github.com/dustin/go-humanize) library. // // The first argument must be a format type, and the last argument // is the input, or the input can be piped in. The supported format // types are: // - **size** which turns an integer amount of bytes into a string like `2.3 MB` // - **time** which turns a time string into a relative time string like `2 weeks ago` // // For the `time` format, the layout for parsing the input can be configured // by appending a colon `:` followed by the desired time layout. You can // find the documentation on time layouts [in Go's docs](https://pkg.go.dev/time#pkg-constants). // The default time layout is `RFC1123Z`, i.e. `Mon, 02 Jan 2006 15:04:05 -0700`. // // ``` // {{humanize "size" "2048000"}} // {{placeholder "http.response.header.Content-Length" | humanize "size"}} // {{humanize "time" "Fri, 05 May 2022 15:04:05 +0200"}} // {{humanize "time:2006-Jan-02" "2022-May-05"}} // ``` type Templates struct { // The root path from which to load files. Required if template functions // accessing the file system are used (such as include). Default is // `{http.vars.root}` if set, or current working directory otherwise. FileRoot string `json:"file_root,omitempty"` // The MIME types for which to render templates. It is important to use // this if the route matchers do not exclude images or other binary files. // Default is text/plain, text/markdown, and text/html. MIMETypes []string `json:"mime_types,omitempty"` // The template action delimiters. If set, must be precisely two elements: // the opening and closing delimiters. Default: `["{{", "}}"]` Delimiters []string `json:"delimiters,omitempty"` customFuncs []template.FuncMap } // Customfunctions is the interface for registering custom template functions. type CustomFunctions interface { // CustomTemplateFunctions should return the mapping from custom function names to implementations. CustomTemplateFunctions() template.FuncMap } // CaddyModule returns the Caddy module information. func (Templates) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.handlers.templates", New: func() caddy.Module { return new(Templates) }, } } // Provision provisions t. func (t *Templates) Provision(ctx caddy.Context) error { fnModInfos := caddy.GetModules("http.handlers.templates.functions") customFuncs := make([]template.FuncMap, 0, len(fnModInfos)) for _, modInfo := range fnModInfos { mod := modInfo.New() fnMod, ok := mod.(CustomFunctions) if !ok { return fmt.Errorf("module %q does not satisfy the CustomFunctions interface", modInfo.ID) } customFuncs = append(customFuncs, fnMod.CustomTemplateFunctions()) } t.customFuncs = customFuncs if t.MIMETypes == nil { t.MIMETypes = defaultMIMETypes } if t.FileRoot == "" { t.FileRoot = "{http.vars.root}" } return nil } // Validate ensures t has a valid configuration. func (t *Templates) Validate() error { if len(t.Delimiters) != 0 && len(t.Delimiters) != 2 { return fmt.Errorf("delimiters must consist of exactly two elements: opening and closing") } return nil } func (t *Templates) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { buf := bufPool.Get().(*bytes.Buffer) buf.Reset() defer bufPool.Put(buf) // shouldBuf determines whether to execute templates on this response, // since generally we will not want to execute for images or CSS, etc. shouldBuf := func(status int, header http.Header) bool { ct := header.Get("Content-Type") for _, mt := range t.MIMETypes { if strings.Contains(ct, mt) { return true } } return false } rec := caddyhttp.NewResponseRecorder(w, buf, shouldBuf) err := next.ServeHTTP(rec, r) if err != nil { return err } if !rec.Buffered() { return nil } err = t.executeTemplate(rec, r) if err != nil { return err } rec.Header().Set("Content-Length", strconv.Itoa(buf.Len())) rec.Header().Del("Accept-Ranges") // we don't know ranges for dynamically-created content rec.Header().Del("Last-Modified") // useless for dynamic content since it's always changing // we don't know a way to quickly generate etag for dynamic content, // and weak etags still cause browsers to rely on it even after a // refresh, so disable them until we find a better way to do this rec.Header().Del("Etag") return rec.WriteResponse() } // executeTemplate executes the template contained in wb.buf and replaces it with the results. func (t *Templates) executeTemplate(rr caddyhttp.ResponseRecorder, r *http.Request) error { var fs http.FileSystem if t.FileRoot != "" { repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) fs = http.Dir(repl.ReplaceAll(t.FileRoot, ".")) } ctx := &TemplateContext{ Root: fs, Req: r, RespHeader: WrappedHeader{rr.Header()}, config: t, CustomFuncs: t.customFuncs, } err := ctx.executeTemplateInBuffer(r.URL.Path, rr.Buffer()) if err != nil { // templates may return a custom HTTP error to be propagated to the client, // otherwise for any other error we assume the template is broken var handlerErr caddyhttp.HandlerError if errors.As(err, &handlerErr) { return handlerErr } return caddyhttp.Error(http.StatusInternalServerError, err) } return nil } // virtualResponseWriter is used in virtualized HTTP requests // that templates may execute. type virtualResponseWriter struct { status int header http.Header body *bytes.Buffer } func (vrw *virtualResponseWriter) Header() http.Header { return vrw.header } func (vrw *virtualResponseWriter) WriteHeader(statusCode int) { vrw.status = statusCode } func (vrw *virtualResponseWriter) Write(data []byte) (int, error) { return vrw.body.Write(data) } var defaultMIMETypes = []string{ "text/html", "text/plain", "text/markdown", } // Interface guards var ( _ caddy.Provisioner = (*Templates)(nil) _ caddy.Validator = (*Templates)(nil) _ caddyhttp.MiddlewareHandler = (*Templates)(nil) )
Go
caddy/modules/caddyhttp/templates/tplcontext.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 templates import ( "bytes" "fmt" "io" "io/fs" "net" "net/http" "os" "path" "strconv" "strings" "sync" "text/template" "time" "github.com/Masterminds/sprig/v3" chromahtml "github.com/alecthomas/chroma/v2/formatters/html" "github.com/dustin/go-humanize" "github.com/yuin/goldmark" highlighting "github.com/yuin/goldmark-highlighting/v2" "github.com/yuin/goldmark/extension" "github.com/yuin/goldmark/parser" gmhtml "github.com/yuin/goldmark/renderer/html" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) // TemplateContext is the TemplateContext with which HTTP templates are executed. type TemplateContext struct { Root http.FileSystem Req *http.Request Args []any // defined by arguments to funcInclude RespHeader WrappedHeader CustomFuncs []template.FuncMap // functions added by plugins config *Templates tpl *template.Template } // NewTemplate returns a new template intended to be evaluated with this // context, as it is initialized with configuration from this context. func (c *TemplateContext) NewTemplate(tplName string) *template.Template { c.tpl = template.New(tplName) // customize delimiters, if applicable if c.config != nil && len(c.config.Delimiters) == 2 { c.tpl.Delims(c.config.Delimiters[0], c.config.Delimiters[1]) } // add sprig library c.tpl.Funcs(sprigFuncMap) // add all custom functions for _, funcMap := range c.CustomFuncs { c.tpl.Funcs(funcMap) } // add our own library c.tpl.Funcs(template.FuncMap{ "include": c.funcInclude, "readFile": c.funcReadFile, "import": c.funcImport, "httpInclude": c.funcHTTPInclude, "stripHTML": c.funcStripHTML, "markdown": c.funcMarkdown, "splitFrontMatter": c.funcSplitFrontMatter, "listFiles": c.funcListFiles, "fileStat": c.funcFileStat, "env": c.funcEnv, "placeholder": c.funcPlaceholder, "fileExists": c.funcFileExists, "httpError": c.funcHTTPError, "humanize": c.funcHumanize, }) return c.tpl } // OriginalReq returns the original, unmodified, un-rewritten request as // it originally came in over the wire. func (c TemplateContext) OriginalReq() http.Request { or, _ := c.Req.Context().Value(caddyhttp.OriginalRequestCtxKey).(http.Request) return or } // funcInclude returns the contents of filename relative to the site root and renders it in place. // Note that included files are NOT escaped, so you should only include // trusted files. If it is not trusted, be sure to use escaping functions // in your template. func (c TemplateContext) funcInclude(filename string, args ...any) (string, error) { bodyBuf := bufPool.Get().(*bytes.Buffer) bodyBuf.Reset() defer bufPool.Put(bodyBuf) err := c.readFileToBuffer(filename, bodyBuf) if err != nil { return "", err } c.Args = args err = c.executeTemplateInBuffer(filename, bodyBuf) if err != nil { return "", err } return bodyBuf.String(), nil } // funcReadFile returns the contents of a filename relative to the site root. // Note that included files are NOT escaped, so you should only include // trusted files. If it is not trusted, be sure to use escaping functions // in your template. func (c TemplateContext) funcReadFile(filename string) (string, error) { bodyBuf := bufPool.Get().(*bytes.Buffer) bodyBuf.Reset() defer bufPool.Put(bodyBuf) err := c.readFileToBuffer(filename, bodyBuf) if err != nil { return "", err } return bodyBuf.String(), nil } // readFileToBuffer reads a file into a buffer func (c TemplateContext) readFileToBuffer(filename string, bodyBuf *bytes.Buffer) error { if c.Root == nil { return fmt.Errorf("root file system not specified") } file, err := c.Root.Open(filename) if err != nil { return err } defer file.Close() _, err = io.Copy(bodyBuf, file) if err != nil { return err } return nil } // funcHTTPInclude returns the body of a virtual (lightweight) request // to the given URI on the same server. Note that included bodies // are NOT escaped, so you should only include trusted resources. // If it is not trusted, be sure to use escaping functions yourself. func (c TemplateContext) funcHTTPInclude(uri string) (string, error) { // prevent virtual request loops by counting how many levels // deep we are; and if we get too deep, return an error recursionCount := 1 if numStr := c.Req.Header.Get(recursionPreventionHeader); numStr != "" { num, err := strconv.Atoi(numStr) if err != nil { return "", fmt.Errorf("parsing %s: %v", recursionPreventionHeader, err) } if num >= 3 { return "", fmt.Errorf("virtual request cycle") } recursionCount = num + 1 } buf := bufPool.Get().(*bytes.Buffer) buf.Reset() defer bufPool.Put(buf) virtReq, err := http.NewRequest("GET", uri, nil) if err != nil { return "", err } virtReq.Host = c.Req.Host virtReq.Header = c.Req.Header.Clone() virtReq.Header.Set("Accept-Encoding", "identity") // https://github.com/caddyserver/caddy/issues/4352 virtReq.Trailer = c.Req.Trailer.Clone() virtReq.Header.Set(recursionPreventionHeader, strconv.Itoa(recursionCount)) vrw := &virtualResponseWriter{body: buf, header: make(http.Header)} server := c.Req.Context().Value(caddyhttp.ServerCtxKey).(http.Handler) server.ServeHTTP(vrw, virtReq) if vrw.status >= 400 { return "", fmt.Errorf("http %d", vrw.status) } err = c.executeTemplateInBuffer(uri, buf) if err != nil { return "", err } return buf.String(), nil } // funcImport parses the filename into the current template stack. The imported // file will be rendered within the current template by calling {{ block }} or // {{ template }} from the standard template library. If the imported file has // no {{ define }} blocks, the name of the import will be the path func (c *TemplateContext) funcImport(filename string) (string, error) { bodyBuf := bufPool.Get().(*bytes.Buffer) bodyBuf.Reset() defer bufPool.Put(bodyBuf) err := c.readFileToBuffer(filename, bodyBuf) if err != nil { return "", err } _, err = c.tpl.Parse(bodyBuf.String()) if err != nil { return "", err } return "", nil } func (c *TemplateContext) executeTemplateInBuffer(tplName string, buf *bytes.Buffer) error { c.NewTemplate(tplName) _, err := c.tpl.Parse(buf.String()) if err != nil { return err } buf.Reset() // reuse buffer for output return c.tpl.Execute(buf, c) } func (c TemplateContext) funcPlaceholder(name string) string { repl := c.Req.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) value, _ := repl.GetString(name) return value } func (TemplateContext) funcEnv(varName string) string { return os.Getenv(varName) } // Cookie gets the value of a cookie with name name. func (c TemplateContext) Cookie(name string) string { cookies := c.Req.Cookies() for _, cookie := range cookies { if cookie.Name == name { return cookie.Value } } return "" } // RemoteIP gets the IP address of the client making the request. func (c TemplateContext) RemoteIP() string { ip, _, err := net.SplitHostPort(c.Req.RemoteAddr) if err != nil { return c.Req.RemoteAddr } return ip } // Host returns the hostname portion of the Host header // from the HTTP request. func (c TemplateContext) Host() (string, error) { host, _, err := net.SplitHostPort(c.Req.Host) if err != nil { if !strings.Contains(c.Req.Host, ":") { // common with sites served on the default port 80 return c.Req.Host, nil } return "", err } return host, nil } // funcStripHTML returns s without HTML tags. It is fairly naive // but works with most valid HTML inputs. func (TemplateContext) funcStripHTML(s string) string { var buf bytes.Buffer var inTag, inQuotes bool var tagStart int for i, ch := range s { if inTag { if ch == '>' && !inQuotes { inTag = false } else if ch == '<' && !inQuotes { // false start buf.WriteString(s[tagStart:i]) tagStart = i } else if ch == '"' { inQuotes = !inQuotes } continue } if ch == '<' { inTag = true tagStart = i continue } buf.WriteRune(ch) } if inTag { // false start buf.WriteString(s[tagStart:]) } return buf.String() } // funcMarkdown renders the markdown body as HTML. The resulting // HTML is NOT escaped so that it can be rendered as HTML. func (TemplateContext) funcMarkdown(input any) (string, error) { inputStr := caddy.ToString(input) md := goldmark.New( goldmark.WithExtensions( extension.GFM, extension.Footnote, highlighting.NewHighlighting( highlighting.WithFormatOptions( chromahtml.WithClasses(true), ), ), ), goldmark.WithParserOptions( parser.WithAutoHeadingID(), ), goldmark.WithRendererOptions( gmhtml.WithUnsafe(), // TODO: this is not awesome, maybe should be configurable? ), ) buf := bufPool.Get().(*bytes.Buffer) buf.Reset() defer bufPool.Put(buf) err := md.Convert([]byte(inputStr), buf) if err != nil { return "", err } return buf.String(), nil } // splitFrontMatter parses front matter out from the beginning of input, // and returns the separated key-value pairs and the body/content. input // must be a "stringy" value. func (TemplateContext) funcSplitFrontMatter(input any) (parsedMarkdownDoc, error) { meta, body, err := extractFrontMatter(caddy.ToString(input)) if err != nil { return parsedMarkdownDoc{}, err } return parsedMarkdownDoc{Meta: meta, Body: body}, nil } // funcListFiles reads and returns a slice of names from the given // directory relative to the root of c. func (c TemplateContext) funcListFiles(name string) ([]string, error) { if c.Root == nil { return nil, fmt.Errorf("root file system not specified") } dir, err := c.Root.Open(path.Clean(name)) if err != nil { return nil, err } defer dir.Close() stat, err := dir.Stat() if err != nil { return nil, err } if !stat.IsDir() { return nil, fmt.Errorf("%v is not a directory", name) } dirInfo, err := dir.Readdir(0) if err != nil { return nil, err } names := make([]string, len(dirInfo)) for i, fileInfo := range dirInfo { names[i] = fileInfo.Name() } return names, nil } // funcFileExists returns true if filename can be opened successfully. func (c TemplateContext) funcFileExists(filename string) (bool, error) { if c.Root == nil { return false, fmt.Errorf("root file system not specified") } file, err := c.Root.Open(filename) if err == nil { file.Close() return true, nil } return false, nil } // funcFileStat returns Stat of a filename func (c TemplateContext) funcFileStat(filename string) (fs.FileInfo, error) { if c.Root == nil { return nil, fmt.Errorf("root file system not specified") } file, err := c.Root.Open(path.Clean(filename)) if err != nil { return nil, err } defer file.Close() return file.Stat() } // funcHTTPError returns a structured HTTP handler error. EXPERIMENTAL; SUBJECT TO CHANGE. // Example usage: `{{if not (fileExists $includeFile)}}{{httpError 404}}{{end}}` func (c TemplateContext) funcHTTPError(statusCode int) (bool, error) { return false, caddyhttp.Error(statusCode, nil) } // funcHumanize transforms size and time inputs to a human readable format. // // Size inputs are expected to be integers, and are formatted as a // byte size, such as "83 MB". // // Time inputs are parsed using the given layout (default layout is RFC1123Z) // and are formatted as a relative time, such as "2 weeks ago". // See https://pkg.go.dev/time#pkg-constants for time layout docs. func (c TemplateContext) funcHumanize(formatType, data string) (string, error) { // The format type can optionally be followed // by a colon to provide arguments for the format parts := strings.Split(formatType, ":") switch parts[0] { case "size": dataint, dataerr := strconv.ParseUint(data, 10, 64) if dataerr != nil { return "", fmt.Errorf("humanize: size cannot be parsed: %s", dataerr.Error()) } return humanize.Bytes(dataint), nil case "time": timelayout := time.RFC1123Z if len(parts) > 1 { timelayout = parts[1] } dataint, dataerr := time.Parse(timelayout, data) if dataerr != nil { return "", fmt.Errorf("humanize: time cannot be parsed: %s", dataerr.Error()) } return humanize.Time(dataint), nil } return "", fmt.Errorf("no know function was given") } // WrappedHeader wraps niladic functions so that they // can be used in templates. (Template functions must // return a value.) type WrappedHeader struct{ http.Header } // Add adds a header field value, appending val to // existing values for that field. It returns an // empty string. func (h WrappedHeader) Add(field, val string) string { h.Header.Add(field, val) return "" } // Set sets a header field value, overwriting any // other values for that field. It returns an // empty string. func (h WrappedHeader) Set(field, val string) string { h.Header.Set(field, val) return "" } // Del deletes a header field. It returns an empty string. func (h WrappedHeader) Del(field string) string { h.Header.Del(field) return "" } var bufPool = sync.Pool{ New: func() any { return new(bytes.Buffer) }, } // at time of writing, sprig.FuncMap() makes a copy, thus // involves iterating the whole map, so do it just once var sprigFuncMap = sprig.TxtFuncMap() const recursionPreventionHeader = "Caddy-Templates-Include"
Go
caddy/modules/caddyhttp/templates/tplcontext_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 templates import ( "bytes" "context" "fmt" "net/http" "os" "path/filepath" "reflect" "sort" "strings" "testing" "time" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) type handle struct { } func (h *handle) ServeHTTP(w http.ResponseWriter, r *http.Request) { if r.Header.Get("Accept-Encoding") == "identity" { w.Write([]byte("good contents")) } else { w.Write([]byte("bad cause Accept-Encoding: " + r.Header.Get("Accept-Encoding"))) } } func TestHTTPInclude(t *testing.T) { tplContext := getContextOrFail(t) for i, test := range []struct { uri string handler *handle expect string }{ { uri: "https://example.com/foo/bar", handler: &handle{}, expect: "good contents", }, } { ctx := context.WithValue(tplContext.Req.Context(), caddyhttp.ServerCtxKey, test.handler) tplContext.Req = tplContext.Req.WithContext(ctx) tplContext.Req.Header.Add("Accept-Encoding", "gzip") result, err := tplContext.funcHTTPInclude(test.uri) if result != test.expect { t.Errorf("Test %d: expected '%s' but got '%s'", i, test.expect, result) } if err != nil { t.Errorf("Test %d: got error: %v", i, result) } } } func TestMarkdown(t *testing.T) { tplContext := getContextOrFail(t) for i, test := range []struct { body string expect string }{ { body: "- str1\n- str2\n", expect: "<ul>\n<li>str1</li>\n<li>str2</li>\n</ul>\n", }, } { result, err := tplContext.funcMarkdown(test.body) if result != test.expect { t.Errorf("Test %d: expected '%s' but got '%s'", i, test.expect, result) } if err != nil { t.Errorf("Test %d: got error: %v", i, result) } } } func TestCookie(t *testing.T) { for i, test := range []struct { cookie *http.Cookie cookieName string expect string }{ { // happy path cookie: &http.Cookie{Name: "cookieName", Value: "cookieValue"}, cookieName: "cookieName", expect: "cookieValue", }, { // try to get a non-existing cookie cookie: &http.Cookie{Name: "cookieName", Value: "cookieValue"}, cookieName: "notExisting", expect: "", }, { // partial name match cookie: &http.Cookie{Name: "cookie", Value: "cookieValue"}, cookieName: "cook", expect: "", }, { // cookie with optional fields cookie: &http.Cookie{Name: "cookie", Value: "cookieValue", Path: "/path", Domain: "https://localhost", Expires: time.Now().Add(10 * time.Minute), MaxAge: 120}, cookieName: "cookie", expect: "cookieValue", }, } { tplContext := getContextOrFail(t) tplContext.Req.AddCookie(test.cookie) actual := tplContext.Cookie(test.cookieName) if actual != test.expect { t.Errorf("Test %d: Expected cookie value '%s' but got '%s' for cookie with name '%s'", i, test.expect, actual, test.cookieName) } } } func TestImport(t *testing.T) { for i, test := range []struct { fileContent string fileName string shouldErr bool expect string }{ { // file exists, template is defined fileContent: `{{ define "imported" }}text{{end}}`, fileName: "file1", shouldErr: false, expect: `"imported"`, }, { // file does not exit fileContent: "", fileName: "", shouldErr: true, }, } { tplContext := getContextOrFail(t) var absFilePath string // create files for test case if test.fileName != "" { absFilePath := filepath.Join(fmt.Sprintf("%s", tplContext.Root), test.fileName) if err := os.WriteFile(absFilePath, []byte(test.fileContent), os.ModePerm); err != nil { os.Remove(absFilePath) t.Fatalf("Test %d: Expected no error creating file, got: '%s'", i, err.Error()) } } // perform test tplContext.NewTemplate("parent") actual, err := tplContext.funcImport(test.fileName) templateWasDefined := strings.Contains(tplContext.tpl.DefinedTemplates(), test.expect) if err != nil { if !test.shouldErr { t.Errorf("Test %d: Expected no error, got: '%s'", i, err) } } else if test.shouldErr { t.Errorf("Test %d: Expected error but had none", i) } else if !templateWasDefined && actual != "" { // template should be defined, return value should be an empty string t.Errorf("Test %d: Expected template %s to be define but got %s", i, test.expect, tplContext.tpl.DefinedTemplates()) } if absFilePath != "" { if err := os.Remove(absFilePath); err != nil && !os.IsNotExist(err) { t.Fatalf("Test %d: Expected no error removing temporary test file, got: %v", i, err) } } } } func TestNestedInclude(t *testing.T) { for i, test := range []struct { child string childFile string parent string parentFile string shouldErr bool expect string child2 string child2File string }{ { // include in parent child: `{{ include "file1" }}`, childFile: "file0", parent: `{{ $content := "file2" }}{{ $p := include $content}}`, parentFile: "file1", shouldErr: false, expect: ``, child2: `This shouldn't show`, child2File: "file2", }, } { context := getContextOrFail(t) var absFilePath string var absFilePath0 string var absFilePath1 string var buf *bytes.Buffer var err error // create files and for test case if test.parentFile != "" { absFilePath = filepath.Join(fmt.Sprintf("%s", context.Root), test.parentFile) if err := os.WriteFile(absFilePath, []byte(test.parent), os.ModePerm); err != nil { os.Remove(absFilePath) t.Fatalf("Test %d: Expected no error creating file, got: '%s'", i, err.Error()) } } if test.childFile != "" { absFilePath0 = filepath.Join(fmt.Sprintf("%s", context.Root), test.childFile) if err := os.WriteFile(absFilePath0, []byte(test.child), os.ModePerm); err != nil { os.Remove(absFilePath0) t.Fatalf("Test %d: Expected no error creating file, got: '%s'", i, err.Error()) } } if test.child2File != "" { absFilePath1 = filepath.Join(fmt.Sprintf("%s", context.Root), test.child2File) if err := os.WriteFile(absFilePath1, []byte(test.child2), os.ModePerm); err != nil { os.Remove(absFilePath0) t.Fatalf("Test %d: Expected no error creating file, got: '%s'", i, err.Error()) } } buf = bufPool.Get().(*bytes.Buffer) buf.Reset() defer bufPool.Put(buf) buf.WriteString(test.child) err = context.executeTemplateInBuffer(test.childFile, buf) if err != nil { if !test.shouldErr { t.Errorf("Test %d: Expected no error, got: '%s'", i, err) } } else if test.shouldErr { t.Errorf("Test %d: Expected error but had none", i) } else if buf.String() != test.expect { // t.Errorf("Test %d: Expected '%s' but got '%s'", i, test.expect, buf.String()) } if absFilePath != "" { if err := os.Remove(absFilePath); err != nil && !os.IsNotExist(err) { t.Fatalf("Test %d: Expected no error removing temporary test file, got: %v", i, err) } } if absFilePath0 != "" { if err := os.Remove(absFilePath0); err != nil && !os.IsNotExist(err) { t.Fatalf("Test %d: Expected no error removing temporary test file, got: %v", i, err) } } if absFilePath1 != "" { if err := os.Remove(absFilePath1); err != nil && !os.IsNotExist(err) { t.Fatalf("Test %d: Expected no error removing temporary test file, got: %v", i, err) } } } } func TestInclude(t *testing.T) { for i, test := range []struct { fileContent string fileName string shouldErr bool expect string args string }{ { // file exists, content is text only fileContent: "text", fileName: "file1", shouldErr: false, expect: "text", }, { // file exists, content is template fileContent: "{{ if . }}text{{ end }}", fileName: "file1", shouldErr: false, expect: "text", }, { // file does not exit fileContent: "", fileName: "", shouldErr: true, }, { // args fileContent: "{{ index .Args 0 }}", fileName: "file1", shouldErr: false, args: "text", expect: "text", }, { // args, reference arg out of range fileContent: "{{ index .Args 1 }}", fileName: "file1", shouldErr: true, args: "text", }, } { tplContext := getContextOrFail(t) var absFilePath string // create files for test case if test.fileName != "" { absFilePath := filepath.Join(fmt.Sprintf("%s", tplContext.Root), test.fileName) if err := os.WriteFile(absFilePath, []byte(test.fileContent), os.ModePerm); err != nil { os.Remove(absFilePath) t.Fatalf("Test %d: Expected no error creating file, got: '%s'", i, err.Error()) } } // perform test actual, err := tplContext.funcInclude(test.fileName, test.args) if err != nil { if !test.shouldErr { t.Errorf("Test %d: Expected no error, got: '%s'", i, err) } } else if test.shouldErr { t.Errorf("Test %d: Expected error but had none", i) } else if actual != test.expect { t.Errorf("Test %d: Expected %s but got %s", i, test.expect, actual) } if absFilePath != "" { if err := os.Remove(absFilePath); err != nil && !os.IsNotExist(err) { t.Fatalf("Test %d: Expected no error removing temporary test file, got: %v", i, err) } } } } func TestCookieMultipleCookies(t *testing.T) { tplContext := getContextOrFail(t) cookieNameBase, cookieValueBase := "cookieName", "cookieValue" for i := 0; i < 10; i++ { tplContext.Req.AddCookie(&http.Cookie{ Name: fmt.Sprintf("%s%d", cookieNameBase, i), Value: fmt.Sprintf("%s%d", cookieValueBase, i), }) } for i := 0; i < 10; i++ { expectedCookieVal := fmt.Sprintf("%s%d", cookieValueBase, i) actualCookieVal := tplContext.Cookie(fmt.Sprintf("%s%d", cookieNameBase, i)) if actualCookieVal != expectedCookieVal { t.Errorf("Expected cookie value %s, found %s", expectedCookieVal, actualCookieVal) } } } func TestIP(t *testing.T) { tplContext := getContextOrFail(t) for i, test := range []struct { inputRemoteAddr string expect string }{ {"1.1.1.1:1111", "1.1.1.1"}, {"1.1.1.1", "1.1.1.1"}, {"[::1]:11", "::1"}, {"[2001:db8:a0b:12f0::1]", "[2001:db8:a0b:12f0::1]"}, {`[fe80:1::3%eth0]:44`, `fe80:1::3%eth0`}, } { tplContext.Req.RemoteAddr = test.inputRemoteAddr if actual := tplContext.RemoteIP(); actual != test.expect { t.Errorf("Test %d: Expected %s but got %s", i, test.expect, actual) } } } func TestStripHTML(t *testing.T) { tplContext := getContextOrFail(t) for i, test := range []struct { input string expect string }{ { // no tags input: `h1`, expect: `h1`, }, { // happy path input: `<h1>h1</h1>`, expect: `h1`, }, { // tag in quotes input: `<h1">">h1</h1>`, expect: `h1`, }, { // multiple tags input: `<h1><b>h1</b></h1>`, expect: `h1`, }, { // tags not closed input: `<h1`, expect: `<h1`, }, { // false start input: `<h1<b>hi`, expect: `<h1hi`, }, } { actual := tplContext.funcStripHTML(test.input) if actual != test.expect { t.Errorf("Test %d: Expected %s, found %s. Input was StripHTML(%s)", i, test.expect, actual, test.input) } } } func TestFileListing(t *testing.T) { for i, test := range []struct { fileNames []string inputBase string shouldErr bool verifyErr func(error) bool }{ { // directory and files exist fileNames: []string{"file1", "file2"}, shouldErr: false, }, { // directory exists, no files fileNames: []string{}, shouldErr: false, }, { // file or directory does not exist fileNames: nil, inputBase: "doesNotExist", shouldErr: true, verifyErr: os.IsNotExist, }, { // directory and files exist, but path to a file fileNames: []string{"file1", "file2"}, inputBase: "file1", shouldErr: true, verifyErr: func(err error) bool { return strings.HasSuffix(err.Error(), "is not a directory") }, }, { // try to escape Context Root fileNames: nil, inputBase: filepath.Join("..", "..", "..", "..", "..", "etc"), shouldErr: true, verifyErr: os.IsNotExist, }, } { tplContext := getContextOrFail(t) var dirPath string var err error // create files for test case if test.fileNames != nil { dirPath, err = os.MkdirTemp(fmt.Sprintf("%s", tplContext.Root), "caddy_ctxtest") if err != nil { t.Fatalf("Test %d: Expected no error creating directory, got: '%s'", i, err.Error()) } for _, name := range test.fileNames { absFilePath := filepath.Join(dirPath, name) if err = os.WriteFile(absFilePath, []byte(""), os.ModePerm); err != nil { os.RemoveAll(dirPath) t.Fatalf("Test %d: Expected no error creating file, got: '%s'", i, err.Error()) } } } // perform test input := filepath.ToSlash(filepath.Join(filepath.Base(dirPath), test.inputBase)) actual, err := tplContext.funcListFiles(input) if err != nil { if !test.shouldErr { t.Errorf("Test %d: Expected no error, got: '%s'", i, err) } else if !test.verifyErr(err) { t.Errorf("Test %d: Could not verify error content, got: '%s'", i, err) } } else if test.shouldErr { t.Errorf("Test %d: Expected error but had none", i) } else { numFiles := len(test.fileNames) // reflect.DeepEqual does not consider two empty slices to be equal if numFiles == 0 && len(actual) != 0 { t.Errorf("Test %d: Expected files %v, got: %v", i, test.fileNames, actual) } else { sort.Strings(actual) if numFiles > 0 && !reflect.DeepEqual(test.fileNames, actual) { t.Errorf("Test %d: Expected files %v, got: %v", i, test.fileNames, actual) } } } if dirPath != "" { if err := os.RemoveAll(dirPath); err != nil && !os.IsNotExist(err) { t.Fatalf("Test %d: Expected no error removing temporary test directory, got: %v", i, err) } } } } func TestSplitFrontMatter(t *testing.T) { tplContext := getContextOrFail(t) for i, test := range []struct { input string expect string body string }{ { // yaml with windows newline input: "---\r\ntitle: Welcome\r\n---\r\n# Test\\r\\n", expect: `Welcome`, body: "\r\n# Test\\r\\n", }, { // yaml input: `--- title: Welcome --- ### Test`, expect: `Welcome`, body: "\n### Test", }, { // yaml with dots for closer input: `--- title: Welcome ... ### Test`, expect: `Welcome`, body: "\n### Test", }, { // yaml with non-fence '...' line after closing fence (i.e. first matching closing fence should be used) input: `--- title: Welcome --- ### Test ... yeah`, expect: `Welcome`, body: "\n### Test\n...\nyeah", }, { // toml input: `+++ title = "Welcome" +++ ### Test`, expect: `Welcome`, body: "\n### Test", }, { // json input: `{ "title": "Welcome" } ### Test`, expect: `Welcome`, body: "\n### Test", }, } { result, _ := tplContext.funcSplitFrontMatter(test.input) if result.Meta["title"] != test.expect { t.Errorf("Test %d: Expected %s, found %s. Input was SplitFrontMatter(%s)", i, test.expect, result.Meta["title"], test.input) } if result.Body != test.body { t.Errorf("Test %d: Expected body %s, found %s. Input was SplitFrontMatter(%s)", i, test.body, result.Body, test.input) } } } func TestHumanize(t *testing.T) { tplContext := getContextOrFail(t) for i, test := range []struct { format string inputData string expect string errorCase bool verifyErr func(actual_string, substring string) bool }{ { format: "size", inputData: "2048000", expect: "2.0 MB", errorCase: false, verifyErr: strings.Contains, }, { format: "time", inputData: "Fri, 05 May 2022 15:04:05 +0200", expect: "ago", errorCase: false, verifyErr: strings.HasSuffix, }, { format: "time:2006-Jan-02", inputData: "2022-May-05", expect: "ago", errorCase: false, verifyErr: strings.HasSuffix, }, { format: "time", inputData: "Fri, 05 May 2022 15:04:05 GMT+0200", expect: "error:", errorCase: true, verifyErr: strings.HasPrefix, }, } { if actual, err := tplContext.funcHumanize(test.format, test.inputData); !test.verifyErr(actual, test.expect) { if !test.errorCase { t.Errorf("Test %d: Expected '%s' but got '%s'", i, test.expect, actual) if err != nil { t.Errorf("Test %d: error: %s", i, err.Error()) } } } } } func getContextOrFail(t *testing.T) TemplateContext { tplContext, err := initTestContext() t.Cleanup(func() { os.RemoveAll(string(tplContext.Root.(http.Dir))) }) if err != nil { t.Fatalf("failed to prepare test context: %v", err) } return tplContext } func initTestContext() (TemplateContext, error) { body := bytes.NewBufferString("request body") request, err := http.NewRequest("GET", "https://example.com/foo/bar", body) if err != nil { return TemplateContext{}, err } tmpDir, err := os.MkdirTemp(os.TempDir(), "caddy") if err != nil { return TemplateContext{}, err } return TemplateContext{ Root: http.Dir(tmpDir), Req: request, RespHeader: WrappedHeader{make(http.Header)}, }, nil }
Go
caddy/modules/caddyhttp/tracing/module.go
package tracing import ( "fmt" "net/http" "go.uber.org/zap" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func init() { caddy.RegisterModule(Tracing{}) httpcaddyfile.RegisterHandlerDirective("tracing", parseCaddyfile) } // Tracing implements an HTTP handler that adds support for distributed tracing, // using OpenTelemetry. This module is responsible for the injection and // propagation of the trace context. Configure this module via environment // variables (see https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/sdk-environment-variables.md). // Some values can be overwritten in the configuration file. type Tracing struct { // SpanName is a span name. It should follow the naming guidelines here: // https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/api.md#span SpanName string `json:"span"` // otel implements opentelemetry related logic. otel openTelemetryWrapper logger *zap.Logger } // CaddyModule returns the Caddy module information. func (Tracing) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.handlers.tracing", New: func() caddy.Module { return new(Tracing) }, } } // Provision implements caddy.Provisioner. func (ot *Tracing) Provision(ctx caddy.Context) error { ot.logger = ctx.Logger() var err error ot.otel, err = newOpenTelemetryWrapper(ctx, ot.SpanName) return err } // Cleanup implements caddy.CleanerUpper and closes any idle connections. It // calls Shutdown method for a trace provider https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/sdk.md#shutdown. func (ot *Tracing) Cleanup() error { if err := ot.otel.cleanup(ot.logger); err != nil { return fmt.Errorf("tracerProvider shutdown: %w", err) } return nil } // ServeHTTP implements caddyhttp.MiddlewareHandler. func (ot *Tracing) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { return ot.otel.ServeHTTP(w, r, next) } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. Syntax: // // tracing { // [span <span_name>] // } func (ot *Tracing) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { setParameter := func(d *caddyfile.Dispenser, val *string) error { if d.NextArg() { *val = d.Val() } else { return d.ArgErr() } if d.NextArg() { return d.ArgErr() } return nil } // paramsMap is a mapping between "string" parameter from the Caddyfile and its destination within the module paramsMap := map[string]*string{ "span": &ot.SpanName, } for d.Next() { args := d.RemainingArgs() if len(args) > 0 { return d.ArgErr() } for d.NextBlock(0) { if dst, ok := paramsMap[d.Val()]; ok { if err := setParameter(d, dst); err != nil { return err } } else { return d.ArgErr() } } } return nil } func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) { var m Tracing err := m.UnmarshalCaddyfile(h.Dispenser) return &m, err } // Interface guards var ( _ caddy.Provisioner = (*Tracing)(nil) _ caddyhttp.MiddlewareHandler = (*Tracing)(nil) _ caddyfile.Unmarshaler = (*Tracing)(nil) )
Go
caddy/modules/caddyhttp/tracing/module_test.go
package tracing import ( "context" "errors" "net/http" "net/http/httptest" "strings" "testing" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func TestTracing_UnmarshalCaddyfile(t *testing.T) { tests := []struct { name string spanName string d *caddyfile.Dispenser wantErr bool }{ { name: "Full config", spanName: "my-span", d: caddyfile.NewTestDispenser(` tracing { span my-span }`), wantErr: false, }, { name: "Only span name in the config", spanName: "my-span", d: caddyfile.NewTestDispenser(` tracing { span my-span }`), wantErr: false, }, { name: "Empty config", d: caddyfile.NewTestDispenser(` tracing { }`), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ot := &Tracing{} if err := ot.UnmarshalCaddyfile(tt.d); (err != nil) != tt.wantErr { t.Errorf("UnmarshalCaddyfile() error = %v, wantErrType %v", err, tt.wantErr) } if ot.SpanName != tt.spanName { t.Errorf("UnmarshalCaddyfile() SpanName = %v, want SpanName %v", ot.SpanName, tt.spanName) } }) } } func TestTracing_UnmarshalCaddyfile_Error(t *testing.T) { tests := []struct { name string d *caddyfile.Dispenser wantErr bool }{ { name: "Unknown parameter", d: caddyfile.NewTestDispenser(` tracing { foo bar }`), wantErr: true, }, { name: "Missed argument", d: caddyfile.NewTestDispenser(` tracing { span }`), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ot := &Tracing{} if err := ot.UnmarshalCaddyfile(tt.d); (err != nil) != tt.wantErr { t.Errorf("UnmarshalCaddyfile() error = %v, wantErrType %v", err, tt.wantErr) } }) } } func TestTracing_ServeHTTP_Propagation_Without_Initial_Headers(t *testing.T) { ot := &Tracing{ SpanName: "mySpan", } req := createRequestWithContext("GET", "https://example.com/foo") w := httptest.NewRecorder() var handler caddyhttp.HandlerFunc = func(writer http.ResponseWriter, request *http.Request) error { traceparent := request.Header.Get("Traceparent") if traceparent == "" || strings.HasPrefix(traceparent, "00-00000000000000000000000000000000-0000000000000000") { t.Errorf("Invalid traceparent: %v", traceparent) } return nil } ctx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()}) defer cancel() if err := ot.Provision(ctx); err != nil { t.Errorf("Provision error: %v", err) t.FailNow() } if err := ot.ServeHTTP(w, req, handler); err != nil { t.Errorf("ServeHTTP error: %v", err) } } func TestTracing_ServeHTTP_Propagation_With_Initial_Headers(t *testing.T) { ot := &Tracing{ SpanName: "mySpan", } req := createRequestWithContext("GET", "https://example.com/foo") req.Header.Set("traceparent", "00-11111111111111111111111111111111-1111111111111111-01") w := httptest.NewRecorder() var handler caddyhttp.HandlerFunc = func(writer http.ResponseWriter, request *http.Request) error { traceparent := request.Header.Get("Traceparent") if !strings.HasPrefix(traceparent, "00-11111111111111111111111111111111") { t.Errorf("Invalid traceparent: %v", traceparent) } return nil } ctx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()}) defer cancel() if err := ot.Provision(ctx); err != nil { t.Errorf("Provision error: %v", err) t.FailNow() } if err := ot.ServeHTTP(w, req, handler); err != nil { t.Errorf("ServeHTTP error: %v", err) } } func TestTracing_ServeHTTP_Next_Error(t *testing.T) { ot := &Tracing{ SpanName: "mySpan", } req := createRequestWithContext("GET", "https://example.com/foo") w := httptest.NewRecorder() expectErr := errors.New("test error") var handler caddyhttp.HandlerFunc = func(writer http.ResponseWriter, request *http.Request) error { return expectErr } ctx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()}) defer cancel() if err := ot.Provision(ctx); err != nil { t.Errorf("Provision error: %v", err) t.FailNow() } if err := ot.ServeHTTP(w, req, handler); err == nil || !errors.Is(err, expectErr) { t.Errorf("expected error, got: %v", err) } } func createRequestWithContext(method string, url string) *http.Request { r, _ := http.NewRequest(method, url, nil) repl := caddy.NewReplacer() ctx := context.WithValue(r.Context(), caddy.ReplacerCtxKey, repl) r = r.WithContext(ctx) return r }
Go
caddy/modules/caddyhttp/tracing/tracer.go
package tracing import ( "context" "fmt" "net/http" "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" "go.opentelemetry.io/contrib/propagators/autoprop" "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc" "go.opentelemetry.io/otel/propagation" "go.opentelemetry.io/otel/sdk/resource" sdktrace "go.opentelemetry.io/otel/sdk/trace" semconv "go.opentelemetry.io/otel/semconv/v1.17.0" "go.opentelemetry.io/otel/trace" "go.uber.org/zap" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) const ( webEngineName = "Caddy" defaultSpanName = "handler" nextCallCtxKey caddy.CtxKey = "nextCall" ) // nextCall store the next handler, and the error value return on calling it (if any) type nextCall struct { next caddyhttp.Handler err error } // openTelemetryWrapper is responsible for the tracing injection, extraction and propagation. type openTelemetryWrapper struct { propagators propagation.TextMapPropagator handler http.Handler spanName string } // newOpenTelemetryWrapper is responsible for the openTelemetryWrapper initialization using provided configuration. func newOpenTelemetryWrapper( ctx context.Context, spanName string, ) (openTelemetryWrapper, error) { if spanName == "" { spanName = defaultSpanName } ot := openTelemetryWrapper{ spanName: spanName, } version, _ := caddy.Version() res, err := ot.newResource(webEngineName, version) if err != nil { return ot, fmt.Errorf("creating resource error: %w", err) } traceExporter, err := otlptracegrpc.New(ctx) if err != nil { return ot, fmt.Errorf("creating trace exporter error: %w", err) } ot.propagators = autoprop.NewTextMapPropagator() tracerProvider := globalTracerProvider.getTracerProvider( sdktrace.WithBatcher(traceExporter), sdktrace.WithResource(res), ) ot.handler = otelhttp.NewHandler(http.HandlerFunc(ot.serveHTTP), ot.spanName, otelhttp.WithTracerProvider(tracerProvider), otelhttp.WithPropagators(ot.propagators), otelhttp.WithSpanNameFormatter(ot.spanNameFormatter), ) return ot, nil } // serveHTTP injects a tracing context and call the next handler. func (ot *openTelemetryWrapper) serveHTTP(w http.ResponseWriter, r *http.Request) { ctx := r.Context() ot.propagators.Inject(ctx, propagation.HeaderCarrier(r.Header)) spanCtx := trace.SpanContextFromContext(ctx) if spanCtx.IsValid() { if extra, ok := ctx.Value(caddyhttp.ExtraLogFieldsCtxKey).(*caddyhttp.ExtraLogFields); ok { extra.Add(zap.String("traceID", spanCtx.TraceID().String())) } } next := ctx.Value(nextCallCtxKey).(*nextCall) next.err = next.next.ServeHTTP(w, r) } // ServeHTTP propagates call to the by wrapped by `otelhttp` next handler. func (ot *openTelemetryWrapper) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { n := &nextCall{ next: next, err: nil, } ot.handler.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), nextCallCtxKey, n))) return n.err } // cleanup flush all remaining data and shutdown a tracerProvider func (ot *openTelemetryWrapper) cleanup(logger *zap.Logger) error { return globalTracerProvider.cleanupTracerProvider(logger) } // newResource creates a resource that describe current handler instance and merge it with a default attributes value. func (ot *openTelemetryWrapper) newResource( webEngineName, webEngineVersion string, ) (*resource.Resource, error) { return resource.Merge(resource.Default(), resource.NewSchemaless( semconv.WebEngineName(webEngineName), semconv.WebEngineVersion(webEngineVersion), )) } // spanNameFormatter performs the replacement of placeholders in the span name func (ot *openTelemetryWrapper) spanNameFormatter(operation string, r *http.Request) string { return r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer).ReplaceAll(operation, "") }
Go
caddy/modules/caddyhttp/tracing/tracerprovider.go
package tracing import ( "context" "fmt" "sync" sdktrace "go.opentelemetry.io/otel/sdk/trace" "go.uber.org/zap" ) // globalTracerProvider stores global tracer provider and is responsible for graceful shutdown when nobody is using it. var globalTracerProvider = &tracerProvider{} type tracerProvider struct { mu sync.Mutex tracerProvider *sdktrace.TracerProvider tracerProvidersCounter int } // getTracerProvider create or return an existing global TracerProvider func (t *tracerProvider) getTracerProvider(opts ...sdktrace.TracerProviderOption) *sdktrace.TracerProvider { t.mu.Lock() defer t.mu.Unlock() t.tracerProvidersCounter++ if t.tracerProvider == nil { t.tracerProvider = sdktrace.NewTracerProvider( opts..., ) } return t.tracerProvider } // cleanupTracerProvider gracefully shutdown a TracerProvider func (t *tracerProvider) cleanupTracerProvider(logger *zap.Logger) error { t.mu.Lock() defer t.mu.Unlock() if t.tracerProvidersCounter > 0 { t.tracerProvidersCounter-- } if t.tracerProvidersCounter == 0 { if t.tracerProvider != nil { // tracerProvider.ForceFlush SHOULD be invoked according to https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/sdk.md#forceflush if err := t.tracerProvider.ForceFlush(context.Background()); err != nil { logger.Error("forcing flush", zap.Error(err)) } // tracerProvider.Shutdown MUST be invoked according to https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/sdk.md#shutdown if err := t.tracerProvider.Shutdown(context.Background()); err != nil { return fmt.Errorf("tracerProvider shutdown error: %w", err) } } t.tracerProvider = nil } return nil }
Go
caddy/modules/caddyhttp/tracing/tracerprovider_test.go
package tracing import ( "testing" "go.uber.org/zap" ) func Test_tracersProvider_getTracerProvider(t *testing.T) { tp := tracerProvider{} tp.getTracerProvider() tp.getTracerProvider() if tp.tracerProvider == nil { t.Errorf("There should be tracer provider") } if tp.tracerProvidersCounter != 2 { t.Errorf("Tracer providers counter should equal to 2") } } func Test_tracersProvider_cleanupTracerProvider(t *testing.T) { tp := tracerProvider{} tp.getTracerProvider() tp.getTracerProvider() err := tp.cleanupTracerProvider(zap.NewNop()) if err != nil { t.Errorf("There should be no error: %v", err) } if tp.tracerProvider == nil { t.Errorf("There should be tracer provider") } if tp.tracerProvidersCounter != 1 { t.Errorf("Tracer providers counter should equal to 1") } }
Go
caddy/modules/caddyhttp/tracing/tracer_test.go
package tracing import ( "context" "testing" "github.com/caddyserver/caddy/v2" ) func TestOpenTelemetryWrapper_newOpenTelemetryWrapper(t *testing.T) { ctx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()}) defer cancel() var otw openTelemetryWrapper var err error if otw, err = newOpenTelemetryWrapper(ctx, "", ); err != nil { t.Errorf("newOpenTelemetryWrapper() error = %v", err) t.FailNow() } if otw.propagators == nil { t.Errorf("Propagators should not be empty") } }
Go
caddy/modules/caddypki/adminapi.go
// Copyright 2020 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 caddypki import ( "encoding/json" "fmt" "net/http" "strings" "go.uber.org/zap" "github.com/caddyserver/caddy/v2" ) func init() { caddy.RegisterModule(adminAPI{}) } // adminAPI is a module that serves PKI endpoints to retrieve // information about the CAs being managed by Caddy. type adminAPI struct { ctx caddy.Context log *zap.Logger pkiApp *PKI } // CaddyModule returns the Caddy module information. func (adminAPI) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "admin.api.pki", New: func() caddy.Module { return new(adminAPI) }, } } // Provision sets up the adminAPI module. func (a *adminAPI) Provision(ctx caddy.Context) error { a.ctx = ctx a.log = ctx.Logger(a) // TODO: passing in 'a' is a hack until the admin API is officially extensible (see #5032) // Avoid initializing PKI if it wasn't configured if pkiApp := a.ctx.AppIfConfigured("pki"); pkiApp != nil { a.pkiApp = pkiApp.(*PKI) } return nil } // Routes returns the admin routes for the PKI app. func (a *adminAPI) Routes() []caddy.AdminRoute { return []caddy.AdminRoute{ { Pattern: adminPKIEndpointBase, Handler: caddy.AdminHandlerFunc(a.handleAPIEndpoints), }, } } // handleAPIEndpoints routes API requests within adminPKIEndpointBase. func (a *adminAPI) handleAPIEndpoints(w http.ResponseWriter, r *http.Request) error { uri := strings.TrimPrefix(r.URL.Path, "/pki/") parts := strings.Split(uri, "/") switch { case len(parts) == 2 && parts[0] == "ca" && parts[1] != "": return a.handleCAInfo(w, r) case len(parts) == 3 && parts[0] == "ca" && parts[1] != "" && parts[2] == "certificates": return a.handleCACerts(w, r) } return caddy.APIError{ HTTPStatus: http.StatusNotFound, Err: fmt.Errorf("resource not found: %v", r.URL.Path), } } // handleCAInfo returns information about a particular // CA by its ID. If the CA ID is the default, then the CA will be // provisioned if it has not already been. Other CA IDs will return an // error if they have not been previously provisioned. func (a *adminAPI) handleCAInfo(w http.ResponseWriter, r *http.Request) error { if r.Method != http.MethodGet { return caddy.APIError{ HTTPStatus: http.StatusMethodNotAllowed, Err: fmt.Errorf("method not allowed: %v", r.Method), } } ca, err := a.getCAFromAPIRequestPath(r) if err != nil { return err } rootCert, interCert, err := rootAndIntermediatePEM(ca) if err != nil { return caddy.APIError{ HTTPStatus: http.StatusInternalServerError, Err: fmt.Errorf("failed to get root and intermediate cert for CA %s: %v", ca.ID, err), } } repl := ca.newReplacer() response := caInfo{ ID: ca.ID, Name: ca.Name, RootCN: repl.ReplaceAll(ca.RootCommonName, ""), IntermediateCN: repl.ReplaceAll(ca.IntermediateCommonName, ""), RootCert: string(rootCert), IntermediateCert: string(interCert), } encoded, err := json.Marshal(response) if err != nil { return caddy.APIError{ HTTPStatus: http.StatusInternalServerError, Err: err, } } w.Header().Set("Content-Type", "application/json") _, _ = w.Write(encoded) return nil } // handleCACerts returns the certificate chain for a particular // CA by its ID. If the CA ID is the default, then the CA will be // provisioned if it has not already been. Other CA IDs will return an // error if they have not been previously provisioned. func (a *adminAPI) handleCACerts(w http.ResponseWriter, r *http.Request) error { if r.Method != http.MethodGet { return caddy.APIError{ HTTPStatus: http.StatusMethodNotAllowed, Err: fmt.Errorf("method not allowed: %v", r.Method), } } ca, err := a.getCAFromAPIRequestPath(r) if err != nil { return err } rootCert, interCert, err := rootAndIntermediatePEM(ca) if err != nil { return caddy.APIError{ HTTPStatus: http.StatusInternalServerError, Err: fmt.Errorf("failed to get root and intermediate cert for CA %s: %v", ca.ID, err), } } w.Header().Set("Content-Type", "application/pem-certificate-chain") _, err = w.Write(interCert) if err == nil { _, _ = w.Write(rootCert) } return nil } func (a *adminAPI) getCAFromAPIRequestPath(r *http.Request) (*CA, error) { // Grab the CA ID from the request path, it should be the 4th segment (/pki/ca/<ca>) id := strings.Split(r.URL.Path, "/")[3] if id == "" { return nil, caddy.APIError{ HTTPStatus: http.StatusBadRequest, Err: fmt.Errorf("missing CA in path"), } } // Find the CA by ID, if PKI is configured var ca *CA var ok bool if a.pkiApp != nil { ca, ok = a.pkiApp.CAs[id] } // If we didn't find the CA, and PKI is not configured // then we'll either error out if the CA ID is not the // default. If the CA ID is the default, then we'll // provision it, because the user probably aims to // change their config to enable PKI immediately after // if they actually requested the local CA ID. if !ok { if id != DefaultCAID { return nil, caddy.APIError{ HTTPStatus: http.StatusNotFound, Err: fmt.Errorf("no certificate authority configured with id: %s", id), } } // Provision the default CA, which generates and stores a root // certificate in storage, if one doesn't already exist. ca = new(CA) err := ca.Provision(a.ctx, id, a.log) if err != nil { return nil, caddy.APIError{ HTTPStatus: http.StatusInternalServerError, Err: fmt.Errorf("failed to provision CA %s, %w", id, err), } } } return ca, nil } func rootAndIntermediatePEM(ca *CA) (root, inter []byte, err error) { root, err = pemEncodeCert(ca.RootCertificate().Raw) if err != nil { return } inter, err = pemEncodeCert(ca.IntermediateCertificate().Raw) if err != nil { return } return } // caInfo is the response structure for the CA info API endpoint. type caInfo struct { ID string `json:"id"` Name string `json:"name"` RootCN string `json:"root_common_name"` IntermediateCN string `json:"intermediate_common_name"` RootCert string `json:"root_certificate"` IntermediateCert string `json:"intermediate_certificate"` } // adminPKIEndpointBase is the base admin endpoint under which all PKI admin endpoints exist. const adminPKIEndpointBase = "/pki/" // Interface guards var ( _ caddy.AdminRouter = (*adminAPI)(nil) _ caddy.Provisioner = (*adminAPI)(nil) )
Go
caddy/modules/caddypki/ca.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 caddypki import ( "crypto" "crypto/x509" "encoding/json" "errors" "fmt" "io/fs" "path" "sync" "time" "github.com/caddyserver/certmagic" "github.com/smallstep/certificates/authority" "github.com/smallstep/certificates/db" "github.com/smallstep/truststore" "go.uber.org/zap" "github.com/caddyserver/caddy/v2" ) // CA describes a certificate authority, which consists of // root/signing certificates and various settings pertaining // to the issuance of certificates and trusting them. type CA struct { // The user-facing name of the certificate authority. Name string `json:"name,omitempty"` // The name to put in the CommonName field of the // root certificate. RootCommonName string `json:"root_common_name,omitempty"` // The name to put in the CommonName field of the // intermediate certificates. IntermediateCommonName string `json:"intermediate_common_name,omitempty"` // The lifetime for the intermediate certificates IntermediateLifetime caddy.Duration `json:"intermediate_lifetime,omitempty"` // Whether Caddy will attempt to install the CA's root // into the system trust store, as well as into Java // and Mozilla Firefox trust stores. Default: true. InstallTrust *bool `json:"install_trust,omitempty"` // The root certificate to use; if null, one will be generated. Root *KeyPair `json:"root,omitempty"` // The intermediate (signing) certificate; if null, one will be generated. Intermediate *KeyPair `json:"intermediate,omitempty"` // Optionally configure a separate storage module associated with this // issuer, instead of using Caddy's global/default-configured storage. // This can be useful if you want to keep your signing keys in a // separate location from your leaf certificates. StorageRaw json.RawMessage `json:"storage,omitempty" caddy:"namespace=caddy.storage inline_key=module"` // The unique config-facing ID of the certificate authority. // Since the ID is set in JSON config via object key, this // field is exported only for purposes of config generation // and module provisioning. ID string `json:"-"` storage certmagic.Storage root, inter *x509.Certificate interKey any // TODO: should we just store these as crypto.Signer? mu *sync.RWMutex rootCertPath string // mainly used for logging purposes if trusting log *zap.Logger ctx caddy.Context } // Provision sets up the CA. func (ca *CA) Provision(ctx caddy.Context, id string, log *zap.Logger) error { ca.mu = new(sync.RWMutex) ca.log = log.Named("ca." + id) ca.ctx = ctx if id == "" { return fmt.Errorf("CA ID is required (use 'local' for the default CA)") } ca.mu.Lock() ca.ID = id ca.mu.Unlock() if ca.StorageRaw != nil { val, err := ctx.LoadModule(ca, "StorageRaw") if err != nil { return fmt.Errorf("loading storage module: %v", err) } cmStorage, err := val.(caddy.StorageConverter).CertMagicStorage() if err != nil { return fmt.Errorf("creating storage configuration: %v", err) } ca.storage = cmStorage } if ca.storage == nil { ca.storage = ctx.Storage() } if ca.Name == "" { ca.Name = defaultCAName } if ca.RootCommonName == "" { ca.RootCommonName = defaultRootCommonName } if ca.IntermediateCommonName == "" { ca.IntermediateCommonName = defaultIntermediateCommonName } if ca.IntermediateLifetime == 0 { ca.IntermediateLifetime = caddy.Duration(defaultIntermediateLifetime) } else if time.Duration(ca.IntermediateLifetime) >= defaultRootLifetime { return fmt.Errorf("intermediate certificate lifetime must be less than root certificate lifetime (%s)", defaultRootLifetime) } // load the certs and key that will be used for signing var rootCert, interCert *x509.Certificate var rootKey, interKey crypto.Signer var err error if ca.Root != nil { if ca.Root.Format == "" || ca.Root.Format == "pem_file" { ca.rootCertPath = ca.Root.Certificate } rootCert, rootKey, err = ca.Root.Load() } else { ca.rootCertPath = "storage:" + ca.storageKeyRootCert() rootCert, rootKey, err = ca.loadOrGenRoot() } if err != nil { return err } if ca.Intermediate != nil { interCert, interKey, err = ca.Intermediate.Load() } else { interCert, interKey, err = ca.loadOrGenIntermediate(rootCert, rootKey) } if err != nil { return err } ca.mu.Lock() ca.root, ca.inter, ca.interKey = rootCert, interCert, interKey ca.mu.Unlock() return nil } // RootCertificate returns the CA's root certificate (public key). func (ca CA) RootCertificate() *x509.Certificate { ca.mu.RLock() defer ca.mu.RUnlock() return ca.root } // RootKey returns the CA's root private key. Since the root key is // not cached in memory long-term, it needs to be loaded from storage, // which could yield an error. func (ca CA) RootKey() (any, error) { _, rootKey, err := ca.loadOrGenRoot() return rootKey, err } // IntermediateCertificate returns the CA's intermediate // certificate (public key). func (ca CA) IntermediateCertificate() *x509.Certificate { ca.mu.RLock() defer ca.mu.RUnlock() return ca.inter } // IntermediateKey returns the CA's intermediate private key. func (ca CA) IntermediateKey() any { ca.mu.RLock() defer ca.mu.RUnlock() return ca.interKey } // NewAuthority returns a new Smallstep-powered signing authority for this CA. // Note that we receive *CA (a pointer) in this method to ensure the closure within it, which // executes at a later time, always has the only copy of the CA so it can access the latest, // renewed certificates since NewAuthority was called. See #4517 and #4669. func (ca *CA) NewAuthority(authorityConfig AuthorityConfig) (*authority.Authority, error) { // get the root certificate and the issuer cert+key rootCert := ca.RootCertificate() // set up the signer; cert/key which signs the leaf certs var signerOption authority.Option if authorityConfig.SignWithRoot { // if we're signing with root, we can just pass the // cert/key directly, since it's unlikely to expire // while Caddy is running (long lifetime) var issuerCert *x509.Certificate var issuerKey any issuerCert = rootCert var err error issuerKey, err = ca.RootKey() if err != nil { return nil, fmt.Errorf("loading signing key: %v", err) } signerOption = authority.WithX509Signer(issuerCert, issuerKey.(crypto.Signer)) } else { // if we're signing with intermediate, we need to make // sure it's always fresh, because the intermediate may // renew while Caddy is running (medium lifetime) signerOption = authority.WithX509SignerFunc(func() ([]*x509.Certificate, crypto.Signer, error) { issuerCert := ca.IntermediateCertificate() issuerKey := ca.IntermediateKey().(crypto.Signer) ca.log.Debug("using intermediate signer", zap.String("serial", issuerCert.SerialNumber.String()), zap.String("not_before", issuerCert.NotBefore.String()), zap.String("not_after", issuerCert.NotAfter.String())) return []*x509.Certificate{issuerCert}, issuerKey, nil }) } opts := []authority.Option{ authority.WithConfig(&authority.Config{ AuthorityConfig: authorityConfig.AuthConfig, }), signerOption, authority.WithX509RootCerts(rootCert), } // Add a database if we have one if authorityConfig.DB != nil { opts = append(opts, authority.WithDatabase(*authorityConfig.DB)) } auth, err := authority.NewEmbedded(opts...) if err != nil { return nil, fmt.Errorf("initializing certificate authority: %v", err) } return auth, nil } func (ca CA) loadOrGenRoot() (rootCert *x509.Certificate, rootKey crypto.Signer, err error) { if ca.Root != nil { return ca.Root.Load() } rootCertPEM, err := ca.storage.Load(ca.ctx, ca.storageKeyRootCert()) if err != nil { if !errors.Is(err, fs.ErrNotExist) { return nil, nil, fmt.Errorf("loading root cert: %v", err) } // TODO: should we require that all or none of the assets are required before overwriting anything? rootCert, rootKey, err = ca.genRoot() if err != nil { return nil, nil, fmt.Errorf("generating root: %v", err) } } if rootCert == nil { rootCert, err = pemDecodeSingleCert(rootCertPEM) if err != nil { return nil, nil, fmt.Errorf("parsing root certificate PEM: %v", err) } } if rootKey == nil { rootKeyPEM, err := ca.storage.Load(ca.ctx, ca.storageKeyRootKey()) if err != nil { return nil, nil, fmt.Errorf("loading root key: %v", err) } rootKey, err = certmagic.PEMDecodePrivateKey(rootKeyPEM) if err != nil { return nil, nil, fmt.Errorf("decoding root key: %v", err) } } return rootCert, rootKey, nil } func (ca CA) genRoot() (rootCert *x509.Certificate, rootKey crypto.Signer, err error) { repl := ca.newReplacer() rootCert, rootKey, err = generateRoot(repl.ReplaceAll(ca.RootCommonName, "")) if err != nil { return nil, nil, fmt.Errorf("generating CA root: %v", err) } rootCertPEM, err := pemEncodeCert(rootCert.Raw) if err != nil { return nil, nil, fmt.Errorf("encoding root certificate: %v", err) } err = ca.storage.Store(ca.ctx, ca.storageKeyRootCert(), rootCertPEM) if err != nil { return nil, nil, fmt.Errorf("saving root certificate: %v", err) } rootKeyPEM, err := certmagic.PEMEncodePrivateKey(rootKey) if err != nil { return nil, nil, fmt.Errorf("encoding root key: %v", err) } err = ca.storage.Store(ca.ctx, ca.storageKeyRootKey(), rootKeyPEM) if err != nil { return nil, nil, fmt.Errorf("saving root key: %v", err) } return rootCert, rootKey, nil } func (ca CA) loadOrGenIntermediate(rootCert *x509.Certificate, rootKey crypto.Signer) (interCert *x509.Certificate, interKey crypto.Signer, err error) { interCertPEM, err := ca.storage.Load(ca.ctx, ca.storageKeyIntermediateCert()) if err != nil { if !errors.Is(err, fs.ErrNotExist) { return nil, nil, fmt.Errorf("loading intermediate cert: %v", err) } // TODO: should we require that all or none of the assets are required before overwriting anything? interCert, interKey, err = ca.genIntermediate(rootCert, rootKey) if err != nil { return nil, nil, fmt.Errorf("generating new intermediate cert: %v", err) } } if interCert == nil { interCert, err = pemDecodeSingleCert(interCertPEM) if err != nil { return nil, nil, fmt.Errorf("decoding intermediate certificate PEM: %v", err) } } if interKey == nil { interKeyPEM, err := ca.storage.Load(ca.ctx, ca.storageKeyIntermediateKey()) if err != nil { return nil, nil, fmt.Errorf("loading intermediate key: %v", err) } interKey, err = certmagic.PEMDecodePrivateKey(interKeyPEM) if err != nil { return nil, nil, fmt.Errorf("decoding intermediate key: %v", err) } } return interCert, interKey, nil } func (ca CA) genIntermediate(rootCert *x509.Certificate, rootKey crypto.Signer) (interCert *x509.Certificate, interKey crypto.Signer, err error) { repl := ca.newReplacer() interCert, interKey, err = generateIntermediate(repl.ReplaceAll(ca.IntermediateCommonName, ""), rootCert, rootKey, time.Duration(ca.IntermediateLifetime)) if err != nil { return nil, nil, fmt.Errorf("generating CA intermediate: %v", err) } interCertPEM, err := pemEncodeCert(interCert.Raw) if err != nil { return nil, nil, fmt.Errorf("encoding intermediate certificate: %v", err) } err = ca.storage.Store(ca.ctx, ca.storageKeyIntermediateCert(), interCertPEM) if err != nil { return nil, nil, fmt.Errorf("saving intermediate certificate: %v", err) } interKeyPEM, err := certmagic.PEMEncodePrivateKey(interKey) if err != nil { return nil, nil, fmt.Errorf("encoding intermediate key: %v", err) } err = ca.storage.Store(ca.ctx, ca.storageKeyIntermediateKey(), interKeyPEM) if err != nil { return nil, nil, fmt.Errorf("saving intermediate key: %v", err) } return interCert, interKey, nil } func (ca CA) storageKeyCAPrefix() string { return path.Join("pki", "authorities", certmagic.StorageKeys.Safe(ca.ID)) } func (ca CA) storageKeyRootCert() string { return path.Join(ca.storageKeyCAPrefix(), "root.crt") } func (ca CA) storageKeyRootKey() string { return path.Join(ca.storageKeyCAPrefix(), "root.key") } func (ca CA) storageKeyIntermediateCert() string { return path.Join(ca.storageKeyCAPrefix(), "intermediate.crt") } func (ca CA) storageKeyIntermediateKey() string { return path.Join(ca.storageKeyCAPrefix(), "intermediate.key") } func (ca CA) newReplacer() *caddy.Replacer { repl := caddy.NewReplacer() repl.Set("pki.ca.name", ca.Name) return repl } // installRoot installs this CA's root certificate into the // local trust store(s) if it is not already trusted. The CA // must already be provisioned. func (ca CA) installRoot() error { // avoid password prompt if already trusted if trusted(ca.root) { ca.log.Info("root certificate is already trusted by system", zap.String("path", ca.rootCertPath)) return nil } ca.log.Warn("installing root certificate (you might be prompted for password)", zap.String("path", ca.rootCertPath)) return truststore.Install(ca.root, truststore.WithDebug(), truststore.WithFirefox(), truststore.WithJava(), ) } // AuthorityConfig is used to help a CA configure // the underlying signing authority. type AuthorityConfig struct { SignWithRoot bool // TODO: should we just embed the underlying authority.Config struct type? DB *db.AuthDB AuthConfig *authority.AuthConfig } const ( // DefaultCAID is the default CA ID. DefaultCAID = "local" defaultCAName = "Caddy Local Authority" defaultRootCommonName = "{pki.ca.name} - {time.now.year} ECC Root" defaultIntermediateCommonName = "{pki.ca.name} - ECC Intermediate" defaultRootLifetime = 24 * time.Hour * 30 * 12 * 10 defaultIntermediateLifetime = 24 * time.Hour * 7 )
Go
caddy/modules/caddypki/certificates.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 caddypki import ( "crypto" "crypto/x509" "time" "go.step.sm/crypto/keyutil" "go.step.sm/crypto/x509util" ) func generateRoot(commonName string) (*x509.Certificate, crypto.Signer, error) { template, signer, err := newCert(commonName, x509util.DefaultRootTemplate, defaultRootLifetime) if err != nil { return nil, nil, err } root, err := x509util.CreateCertificate(template, template, signer.Public(), signer) if err != nil { return nil, nil, err } return root, signer, nil } func generateIntermediate(commonName string, rootCrt *x509.Certificate, rootKey crypto.Signer, lifetime time.Duration) (*x509.Certificate, crypto.Signer, error) { template, signer, err := newCert(commonName, x509util.DefaultIntermediateTemplate, lifetime) if err != nil { return nil, nil, err } intermediate, err := x509util.CreateCertificate(template, rootCrt, signer.Public(), rootKey) if err != nil { return nil, nil, err } return intermediate, signer, nil } func newCert(commonName, templateName string, lifetime time.Duration) (cert *x509.Certificate, signer crypto.Signer, err error) { signer, err = keyutil.GenerateDefaultSigner() if err != nil { return nil, nil, err } csr, err := x509util.CreateCertificateRequest(commonName, []string{}, signer) if err != nil { return nil, nil, err } template, err := x509util.NewCertificate(csr, x509util.WithTemplate(templateName, x509util.CreateTemplateData(commonName, []string{}))) if err != nil { return nil, nil, err } cert = template.GetCertificate() cert.NotBefore = time.Now().Truncate(time.Second) cert.NotAfter = cert.NotBefore.Add(lifetime) return cert, signer, nil }
Go
caddy/modules/caddypki/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 caddypki import ( "crypto/x509" "encoding/json" "encoding/pem" "fmt" "net/http" "os" "path" "github.com/smallstep/truststore" "github.com/spf13/cobra" caddycmd "github.com/caddyserver/caddy/v2/cmd" "github.com/caddyserver/caddy/v2" ) func init() { caddycmd.RegisterCommand(caddycmd.Command{ Name: "trust", Usage: "[--ca <id>] [--address <listen>] [--config <path> [--adapter <name>]]", Short: "Installs a CA certificate into local trust stores", Long: ` Adds a root certificate into the local trust stores. Caddy will attempt to install its root certificates into the local trust stores automatically when they are first generated, but it might fail if Caddy doesn't have the appropriate permissions to write to the trust store. This command is necessary to pre-install the certificates before using them, if the server process runs as an unprivileged user (such as via systemd). By default, this command installs the root certificate for Caddy's default CA (i.e. 'local'). You may specify the ID of another CA with the --ca flag. This command will attempt to connect to Caddy's admin API running at '` + caddy.DefaultAdminListen + `' to fetch the root certificate. You may explicitly specify the --address, or use the --config flag to load the admin address from your config, if not using the default.`, CobraFunc: func(cmd *cobra.Command) { cmd.Flags().StringP("ca", "", "", "The ID of the CA to trust (defaults to 'local')") cmd.Flags().StringP("address", "", "", "Address of the administration API listener (if --config is not used)") cmd.Flags().StringP("config", "c", "", "Configuration file (if --address is not used)") cmd.Flags().StringP("adapter", "a", "", "Name of config adapter to apply (if --config is used)") cmd.RunE = caddycmd.WrapCommandFuncForCobra(cmdTrust) }, }) caddycmd.RegisterCommand(caddycmd.Command{ Name: "untrust", Usage: "[--cert <path>] | [[--ca <id>] [--address <listen>] [--config <path> [--adapter <name>]]]", Short: "Untrusts a locally-trusted CA certificate", Long: ` Untrusts a root certificate from the local trust store(s). This command uninstalls trust; it does not necessarily delete the root certificate from trust stores entirely. Thus, repeatedly trusting and untrusting new certificates can fill up trust databases. This command does not delete or modify certificate files from Caddy's configured storage. This command can be used in one of two ways. Either by specifying which certificate to untrust by a direct path to the certificate file with the --cert flag, or by fetching the root certificate for the CA from the admin API (default behaviour). If the admin API is used, then the CA defaults to 'local'. You may specify the ID of another CA with the --ca flag. By default, this will attempt to connect to the Caddy's admin API running at '` + caddy.DefaultAdminListen + `' to fetch the root certificate. You may explicitly specify the --address, or use the --config flag to load the admin address from your config, if not using the default.`, CobraFunc: func(cmd *cobra.Command) { cmd.Flags().StringP("cert", "p", "", "The path to the CA certificate to untrust") cmd.Flags().StringP("ca", "", "", "The ID of the CA to untrust (defaults to 'local')") cmd.Flags().StringP("address", "", "", "Address of the administration API listener (if --config is not used)") cmd.Flags().StringP("config", "c", "", "Configuration file (if --address is not used)") cmd.Flags().StringP("adapter", "a", "", "Name of config adapter to apply (if --config is used)") cmd.RunE = caddycmd.WrapCommandFuncForCobra(cmdUntrust) }, }) } func cmdTrust(fl caddycmd.Flags) (int, error) { caID := fl.String("ca") addrFlag := fl.String("address") configFlag := fl.String("config") configAdapterFlag := fl.String("adapter") // Prepare the URI to the admin endpoint if caID == "" { caID = DefaultCAID } // Determine where we're sending the request to get the CA info adminAddr, err := caddycmd.DetermineAdminAPIAddress(addrFlag, nil, configFlag, configAdapterFlag) if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("couldn't determine admin API address: %v", err) } // Fetch the root cert from the admin API rootCert, err := rootCertFromAdmin(adminAddr, caID) if err != nil { return caddy.ExitCodeFailedStartup, err } // Set up the CA struct; we only need to fill in the root // because we're only using it to make use of the installRoot() // function. Also needs a logger for warnings, and a "cert path" // for the root cert; since we're loading from the API and we // don't know the actual storage path via this flow, we'll just // pass through the admin API address instead. ca := CA{ log: caddy.Log(), root: rootCert, rootCertPath: adminAddr + path.Join(adminPKIEndpointBase, "ca", caID), } // Install the cert! err = ca.installRoot() if err != nil { return caddy.ExitCodeFailedStartup, err } return caddy.ExitCodeSuccess, nil } func cmdUntrust(fl caddycmd.Flags) (int, error) { certFile := fl.String("cert") caID := fl.String("ca") addrFlag := fl.String("address") configFlag := fl.String("config") configAdapterFlag := fl.String("adapter") if certFile != "" && (caID != "" || addrFlag != "" || configFlag != "") { return caddy.ExitCodeFailedStartup, fmt.Errorf("conflicting command line arguments, cannot use --cert with other flags") } // If a file was specified, try to uninstall the cert matching that file if certFile != "" { // Sanity check, make sure cert file exists first _, err := os.Stat(certFile) if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("accessing certificate file: %v", err) } // Uninstall the file! err = truststore.UninstallFile(certFile, truststore.WithDebug(), truststore.WithFirefox(), truststore.WithJava()) if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("failed to uninstall certificate file: %v", err) } return caddy.ExitCodeSuccess, nil } // Prepare the URI to the admin endpoint if caID == "" { caID = DefaultCAID } // Determine where we're sending the request to get the CA info adminAddr, err := caddycmd.DetermineAdminAPIAddress(addrFlag, nil, configFlag, configAdapterFlag) if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("couldn't determine admin API address: %v", err) } // Fetch the root cert from the admin API rootCert, err := rootCertFromAdmin(adminAddr, caID) if err != nil { return caddy.ExitCodeFailedStartup, err } // Uninstall the cert! err = truststore.Uninstall(rootCert, truststore.WithDebug(), truststore.WithFirefox(), truststore.WithJava()) if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("failed to uninstall certificate file: %v", err) } return caddy.ExitCodeSuccess, nil } // rootCertFromAdmin makes the API request to fetch the root certificate for the named CA via admin API. func rootCertFromAdmin(adminAddr string, caID string) (*x509.Certificate, error) { uri := path.Join(adminPKIEndpointBase, "ca", caID) // Make the request to fetch the CA info resp, err := caddycmd.AdminAPIRequest(adminAddr, http.MethodGet, uri, make(http.Header), nil) if err != nil { return nil, fmt.Errorf("requesting CA info: %v", err) } defer resp.Body.Close() // Decode the response caInfo := new(caInfo) err = json.NewDecoder(resp.Body).Decode(caInfo) if err != nil { return nil, fmt.Errorf("failed to decode JSON response: %v", err) } // Decode the root cert rootBlock, _ := pem.Decode([]byte(caInfo.RootCert)) if rootBlock == nil { return nil, fmt.Errorf("failed to decode root certificate: %v", err) } rootCert, err := x509.ParseCertificate(rootBlock.Bytes) if err != nil { return nil, fmt.Errorf("failed to parse root certificate: %v", err) } return rootCert, nil }
Go
caddy/modules/caddypki/crypto.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 caddypki import ( "bytes" "crypto" "crypto/x509" "encoding/pem" "fmt" "os" "github.com/caddyserver/certmagic" ) func pemDecodeSingleCert(pemDER []byte) (*x509.Certificate, error) { pemBlock, remaining := pem.Decode(pemDER) if pemBlock == nil { return nil, fmt.Errorf("no PEM block found") } if len(remaining) > 0 { return nil, fmt.Errorf("input contained more than a single PEM block") } if pemBlock.Type != "CERTIFICATE" { return nil, fmt.Errorf("expected PEM block type to be CERTIFICATE, but got '%s'", pemBlock.Type) } return x509.ParseCertificate(pemBlock.Bytes) } func pemEncodeCert(der []byte) ([]byte, error) { return pemEncode("CERTIFICATE", der) } func pemEncode(blockType string, b []byte) ([]byte, error) { var buf bytes.Buffer err := pem.Encode(&buf, &pem.Block{Type: blockType, Bytes: b}) return buf.Bytes(), err } func trusted(cert *x509.Certificate) bool { chains, err := cert.Verify(x509.VerifyOptions{}) return len(chains) > 0 && err == nil } // KeyPair represents a public-private key pair, where the // public key is also called a certificate. type KeyPair struct { // The certificate. By default, this should be the path to // a PEM file unless format is something else. Certificate string `json:"certificate,omitempty"` // The private key. By default, this should be the path to // a PEM file unless format is something else. PrivateKey string `json:"private_key,omitempty"` // The format in which the certificate and private // key are provided. Default: pem_file Format string `json:"format,omitempty"` } // Load loads the certificate and key. func (kp KeyPair) Load() (*x509.Certificate, crypto.Signer, error) { switch kp.Format { case "", "pem_file": certData, err := os.ReadFile(kp.Certificate) if err != nil { return nil, nil, err } keyData, err := os.ReadFile(kp.PrivateKey) if err != nil { return nil, nil, err } cert, err := pemDecodeSingleCert(certData) if err != nil { return nil, nil, err } key, err := certmagic.PEMDecodePrivateKey(keyData) if err != nil { return nil, nil, err } return cert, key, nil default: return nil, nil, fmt.Errorf("unsupported format: %s", kp.Format) } }
Go
caddy/modules/caddypki/maintain.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 caddypki import ( "crypto/x509" "fmt" "log" "runtime/debug" "time" "go.uber.org/zap" ) func (p *PKI) maintenance() { defer func() { if err := recover(); err != nil { log.Printf("[PANIC] PKI maintenance: %v\n%s", err, debug.Stack()) } }() ticker := time.NewTicker(10 * time.Minute) // TODO: make configurable defer ticker.Stop() for { select { case <-ticker.C: p.renewCerts() case <-p.ctx.Done(): return } } } func (p *PKI) renewCerts() { for _, ca := range p.CAs { err := p.renewCertsForCA(ca) if err != nil { p.log.Error("renewing intermediate certificates", zap.Error(err), zap.String("ca", ca.ID)) } } } func (p *PKI) renewCertsForCA(ca *CA) error { ca.mu.Lock() defer ca.mu.Unlock() log := p.log.With(zap.String("ca", ca.ID)) // only maintain the root if it's not manually provided in the config if ca.Root == nil { if needsRenewal(ca.root) { // TODO: implement root renewal (use same key) log.Warn("root certificate expiring soon (FIXME: ROOT RENEWAL NOT YET IMPLEMENTED)", zap.Duration("time_remaining", time.Until(ca.inter.NotAfter)), ) } } // only maintain the intermediate if it's not manually provided in the config if ca.Intermediate == nil { if needsRenewal(ca.inter) { log.Info("intermediate expires soon; renewing", zap.Duration("time_remaining", time.Until(ca.inter.NotAfter)), ) rootCert, rootKey, err := ca.loadOrGenRoot() if err != nil { return fmt.Errorf("loading root key: %v", err) } interCert, interKey, err := ca.genIntermediate(rootCert, rootKey) if err != nil { return fmt.Errorf("generating new certificate: %v", err) } ca.inter, ca.interKey = interCert, interKey log.Info("renewed intermediate", zap.Time("new_expiration", ca.inter.NotAfter), ) } } return nil } func needsRenewal(cert *x509.Certificate) bool { lifetime := cert.NotAfter.Sub(cert.NotBefore) renewalWindow := time.Duration(float64(lifetime) * renewalWindowRatio) renewalWindowStart := cert.NotAfter.Add(-renewalWindow) return time.Now().After(renewalWindowStart) } const renewalWindowRatio = 0.2 // TODO: make configurable
Go
caddy/modules/caddypki/pki.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 caddypki import ( "fmt" "go.uber.org/zap" "github.com/caddyserver/caddy/v2" ) func init() { caddy.RegisterModule(PKI{}) } // PKI provides Public Key Infrastructure facilities for Caddy. // // This app can define certificate authorities (CAs) which are capable // of signing certificates. Other modules can be configured to use // the CAs defined by this app for issuing certificates or getting // key information needed for establishing trust. type PKI struct { // The certificate authorities to manage. Each CA is keyed by an // ID that is used to uniquely identify it from other CAs. // At runtime, the GetCA() method should be used instead to ensure // the default CA is provisioned if it hadn't already been. // The default CA ID is "local". CAs map[string]*CA `json:"certificate_authorities,omitempty"` ctx caddy.Context log *zap.Logger } // CaddyModule returns the Caddy module information. func (PKI) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "pki", New: func() caddy.Module { return new(PKI) }, } } // Provision sets up the configuration for the PKI app. func (p *PKI) Provision(ctx caddy.Context) error { p.ctx = ctx p.log = ctx.Logger() for caID, ca := range p.CAs { err := ca.Provision(ctx, caID, p.log) if err != nil { return fmt.Errorf("provisioning CA '%s': %v", caID, err) } } // if this app is initialized at all, ensure there's at // least a default CA that can be used: the standard CA // which is used implicitly for signing local-use certs if len(p.CAs) == 0 { err := p.ProvisionDefaultCA(ctx) if err != nil { return fmt.Errorf("provisioning CA '%s': %v", DefaultCAID, err) } } return nil } // ProvisionDefaultCA sets up the default CA. func (p *PKI) ProvisionDefaultCA(ctx caddy.Context) error { if p.CAs == nil { p.CAs = make(map[string]*CA) } p.CAs[DefaultCAID] = new(CA) return p.CAs[DefaultCAID].Provision(ctx, DefaultCAID, p.log) } // Start starts the PKI app. func (p *PKI) Start() error { // install roots to trust store, if not disabled for _, ca := range p.CAs { if ca.InstallTrust != nil && !*ca.InstallTrust { ca.log.Info("root certificate trust store installation disabled; unconfigured clients may show warnings", zap.String("path", ca.rootCertPath)) continue } if err := ca.installRoot(); err != nil { // could be some system dependencies that are missing; // shouldn't totally prevent startup, but we should log it ca.log.Error("failed to install root certificate", zap.Error(err), zap.String("certificate_file", ca.rootCertPath)) } } // see if root/intermediates need renewal... p.renewCerts() // ...and keep them renewed go p.maintenance() return nil } // Stop stops the PKI app. func (p *PKI) Stop() error { return nil } // GetCA retrieves a CA by ID. If the ID is the default // CA ID, and it hasn't been provisioned yet, it will // be provisioned. func (p *PKI) GetCA(ctx caddy.Context, id string) (*CA, error) { ca, ok := p.CAs[id] if !ok { // for anything other than the default CA ID, error out if it wasn't configured if id != DefaultCAID { return nil, fmt.Errorf("no certificate authority configured with id: %s", id) } // for the default CA ID, provision it, because we want it to "just work" err := p.ProvisionDefaultCA(ctx) if err != nil { return nil, fmt.Errorf("failed to provision default CA: %s", err) } ca = p.CAs[id] } return ca, nil } // Interface guards var ( _ caddy.Provisioner = (*PKI)(nil) _ caddy.App = (*PKI)(nil) )
Go
caddy/modules/caddypki/acmeserver/acmeserver.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 acmeserver import ( "context" "fmt" weakrand "math/rand" "net" "net/http" "os" "path/filepath" "regexp" "strings" "time" "github.com/go-chi/chi" "github.com/smallstep/certificates/acme" "github.com/smallstep/certificates/acme/api" acmeNoSQL "github.com/smallstep/certificates/acme/db/nosql" "github.com/smallstep/certificates/authority" "github.com/smallstep/certificates/authority/provisioner" "github.com/smallstep/certificates/db" "github.com/smallstep/nosql" "go.uber.org/zap" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" "github.com/caddyserver/caddy/v2/modules/caddypki" ) func init() { caddy.RegisterModule(Handler{}) } // Handler is an ACME server handler. type Handler struct { // The ID of the CA to use for signing. This refers to // the ID given to the CA in the `pki` app. If omitted, // the default ID is "local". CA string `json:"ca,omitempty"` // The lifetime for issued certificates Lifetime caddy.Duration `json:"lifetime,omitempty"` // The hostname or IP address by which ACME clients // will access the server. This is used to populate // the ACME directory endpoint. If not set, the Host // header of the request will be used. // COMPATIBILITY NOTE / TODO: This property may go away in the // future. Do not rely on this property long-term; check release notes. Host string `json:"host,omitempty"` // The path prefix under which to serve all ACME // endpoints. All other requests will not be served // by this handler and will be passed through to // the next one. Default: "/acme/". // COMPATIBILITY NOTE / TODO: This property may go away in the // future, as it is currently only required due to // limitations in the underlying library. Do not rely // on this property long-term; check release notes. PathPrefix string `json:"path_prefix,omitempty"` // If true, the CA's root will be the issuer instead of // the intermediate. This is NOT recommended and should // only be used when devices/clients do not properly // validate certificate chains. EXPERIMENTAL: Might be // changed or removed in the future. SignWithRoot bool `json:"sign_with_root,omitempty"` // The addresses of DNS resolvers to use when looking up // the TXT records for solving DNS challenges. // It accepts [network addresses](/docs/conventions#network-addresses) // with port range of only 1. If the host is an IP address, // it will be dialed directly to resolve the upstream server. // If the host is not an IP address, the addresses are resolved // using the [name resolution convention](https://golang.org/pkg/net/#hdr-Name_Resolution) // of the Go standard library. If the array contains more // than 1 resolver address, one is chosen at random. Resolvers []string `json:"resolvers,omitempty"` logger *zap.Logger resolvers []caddy.NetworkAddress ctx caddy.Context acmeDB acme.DB acmeAuth *authority.Authority acmeClient acme.Client acmeLinker acme.Linker acmeEndpoints http.Handler } // CaddyModule returns the Caddy module information. func (Handler) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.handlers.acme_server", New: func() caddy.Module { return new(Handler) }, } } // Provision sets up the ACME server handler. func (ash *Handler) Provision(ctx caddy.Context) error { ash.ctx = ctx ash.logger = ctx.Logger() // set some defaults if ash.CA == "" { ash.CA = caddypki.DefaultCAID } if ash.PathPrefix == "" { ash.PathPrefix = defaultPathPrefix } if ash.Lifetime == 0 { ash.Lifetime = caddy.Duration(12 * time.Hour) } // get a reference to the configured CA appModule, err := ctx.App("pki") if err != nil { return err } pkiApp := appModule.(*caddypki.PKI) ca, err := pkiApp.GetCA(ctx, ash.CA) if err != nil { return err } // make sure leaf cert lifetime is less than the intermediate cert lifetime. this check only // applies for caddy-managed intermediate certificates if ca.Intermediate == nil && ash.Lifetime >= ca.IntermediateLifetime { return fmt.Errorf("certificate lifetime (%s) should be less than intermediate certificate lifetime (%s)", time.Duration(ash.Lifetime), time.Duration(ca.IntermediateLifetime)) } database, err := ash.openDatabase() if err != nil { return err } authorityConfig := caddypki.AuthorityConfig{ SignWithRoot: ash.SignWithRoot, AuthConfig: &authority.AuthConfig{ Provisioners: provisioner.List{ &provisioner.ACME{ Name: ash.CA, Type: provisioner.TypeACME.String(), Claims: &provisioner.Claims{ MinTLSDur: &provisioner.Duration{Duration: 5 * time.Minute}, MaxTLSDur: &provisioner.Duration{Duration: 24 * time.Hour * 365}, DefaultTLSDur: &provisioner.Duration{Duration: time.Duration(ash.Lifetime)}, }, }, }, }, DB: database, } ash.acmeAuth, err = ca.NewAuthority(authorityConfig) if err != nil { return err } ash.acmeDB, err = acmeNoSQL.New(ash.acmeAuth.GetDatabase().(nosql.DB)) if err != nil { return fmt.Errorf("configuring ACME DB: %v", err) } ash.acmeClient, err = ash.makeClient() if err != nil { return err } ash.acmeLinker = acme.NewLinker( ash.Host, strings.Trim(ash.PathPrefix, "/"), ) // extract its http.Handler so we can use it directly r := chi.NewRouter() r.Route(ash.PathPrefix, func(r chi.Router) { api.Route(r) }) ash.acmeEndpoints = r return nil } func (ash Handler) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { if strings.HasPrefix(r.URL.Path, ash.PathPrefix) { acmeCtx := acme.NewContext( r.Context(), ash.acmeDB, ash.acmeClient, ash.acmeLinker, nil, ) acmeCtx = authority.NewContext(acmeCtx, ash.acmeAuth) r = r.WithContext(acmeCtx) ash.acmeEndpoints.ServeHTTP(w, r) return nil } return next.ServeHTTP(w, r) } func (ash Handler) getDatabaseKey() string { key := ash.CA key = strings.ToLower(key) key = strings.TrimSpace(key) return keyCleaner.ReplaceAllLiteralString(key, "") } // Cleanup implements caddy.CleanerUpper and closes any idle databases. func (ash Handler) Cleanup() error { key := ash.getDatabaseKey() deleted, err := databasePool.Delete(key) if deleted { ash.logger.Debug("unloading unused CA database", zap.String("db_key", key)) } if err != nil { ash.logger.Error("closing CA database", zap.String("db_key", key), zap.Error(err)) } return err } func (ash Handler) openDatabase() (*db.AuthDB, error) { key := ash.getDatabaseKey() database, loaded, err := databasePool.LoadOrNew(key, func() (caddy.Destructor, error) { dbFolder := filepath.Join(caddy.AppDataDir(), "acme_server", key) dbPath := filepath.Join(dbFolder, "db") err := os.MkdirAll(dbFolder, 0o755) if err != nil { return nil, fmt.Errorf("making folder for CA database: %v", err) } dbConfig := &db.Config{ Type: "bbolt", DataSource: dbPath, } database, err := db.New(dbConfig) return databaseCloser{&database}, err }) if loaded { ash.logger.Debug("loaded preexisting CA database", zap.String("db_key", key)) } return database.(databaseCloser).DB, err } // makeClient creates an ACME client which will use a custom // resolver instead of net.DefaultResolver. func (ash Handler) makeClient() (acme.Client, error) { for _, v := range ash.Resolvers { addr, err := caddy.ParseNetworkAddressWithDefaults(v, "udp", 53) if err != nil { return nil, err } if addr.PortRangeSize() != 1 { return nil, fmt.Errorf("resolver address must have exactly one address; cannot call %v", addr) } ash.resolvers = append(ash.resolvers, addr) } var resolver *net.Resolver if len(ash.resolvers) != 0 { dialer := &net.Dialer{ Timeout: 2 * time.Second, } resolver = &net.Resolver{ PreferGo: true, Dial: func(ctx context.Context, network, address string) (net.Conn, error) { //nolint:gosec addr := ash.resolvers[weakrand.Intn(len(ash.resolvers))] return dialer.DialContext(ctx, addr.Network, addr.JoinHostPort(0)) }, } } else { resolver = net.DefaultResolver } return resolverClient{ Client: acme.NewClient(), resolver: resolver, ctx: ash.ctx, }, nil } type resolverClient struct { acme.Client resolver *net.Resolver ctx context.Context } func (c resolverClient) LookupTxt(name string) ([]string, error) { return c.resolver.LookupTXT(c.ctx, name) } const defaultPathPrefix = "/acme/" var ( keyCleaner = regexp.MustCompile(`[^\w.-_]`) databasePool = caddy.NewUsagePool() ) type databaseCloser struct { DB *db.AuthDB } func (closer databaseCloser) Destruct() error { return (*closer.DB).Shutdown() } // Interface guards var ( _ caddyhttp.MiddlewareHandler = (*Handler)(nil) _ caddy.Provisioner = (*Handler)(nil) )
Go
caddy/modules/caddypki/acmeserver/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 acmeserver import ( "time" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile" "github.com/caddyserver/caddy/v2/modules/caddypki" ) func init() { httpcaddyfile.RegisterDirective("acme_server", parseACMEServer) } // parseACMEServer sets up an ACME server handler from Caddyfile tokens. // // acme_server [<matcher>] { // ca <id> // lifetime <duration> // resolvers <addresses...> // } func parseACMEServer(h httpcaddyfile.Helper) ([]httpcaddyfile.ConfigValue, error) { if !h.Next() { return nil, h.ArgErr() } matcherSet, err := h.ExtractMatcherSet() if err != nil { return nil, err } var acmeServer Handler var ca *caddypki.CA for h.Next() { if h.NextArg() { return nil, h.ArgErr() } for h.NextBlock(0) { switch h.Val() { case "ca": if !h.AllArgs(&acmeServer.CA) { return nil, h.ArgErr() } if ca == nil { ca = new(caddypki.CA) } ca.ID = acmeServer.CA case "lifetime": if !h.NextArg() { return nil, h.ArgErr() } dur, err := caddy.ParseDuration(h.Val()) if err != nil { return nil, err } if d := time.Duration(ca.IntermediateLifetime); d > 0 && dur > d { return nil, h.Errf("certificate lifetime (%s) exceeds intermediate certificate lifetime (%s)", dur, d) } acmeServer.Lifetime = caddy.Duration(dur) case "resolvers": acmeServer.Resolvers = h.RemainingArgs() if len(acmeServer.Resolvers) == 0 { return nil, h.Errf("must specify at least one resolver address") } } } } configVals := h.NewRoute(matcherSet, acmeServer) if ca == nil { return configVals, nil } return append(configVals, httpcaddyfile.ConfigValue{ Class: "pki.ca", Value: ca, }), nil }
Go
caddy/modules/caddytls/acmeissuer.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 caddytls import ( "context" "crypto/x509" "errors" "fmt" "net/url" "os" "strconv" "time" "github.com/caddyserver/certmagic" "github.com/mholt/acmez" "github.com/mholt/acmez/acme" "go.uber.org/zap" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func init() { caddy.RegisterModule(ACMEIssuer{}) } // ACMEIssuer manages certificates using the ACME protocol (RFC 8555). type ACMEIssuer struct { // The URL to the CA's ACME directory endpoint. Default: // https://acme-v02.api.letsencrypt.org/directory CA string `json:"ca,omitempty"` // The URL to the test CA's ACME directory endpoint. // This endpoint is only used during retries if there // is a failure using the primary CA. Default: // https://acme-staging-v02.api.letsencrypt.org/directory TestCA string `json:"test_ca,omitempty"` // Your email address, so the CA can contact you if necessary. // Not required, but strongly recommended to provide one so // you can be reached if there is a problem. Your email is // not sent to any Caddy mothership or used for any purpose // other than ACME transactions. Email string `json:"email,omitempty"` // If you have an existing account with the ACME server, put // the private key here in PEM format. The ACME client will // look up your account information with this key first before // trying to create a new one. You can use placeholders here, // for example if you have it in an environment variable. AccountKey string `json:"account_key,omitempty"` // If using an ACME CA that requires an external account // binding, specify the CA-provided credentials here. ExternalAccount *acme.EAB `json:"external_account,omitempty"` // Time to wait before timing out an ACME operation. // Default: 0 (no timeout) ACMETimeout caddy.Duration `json:"acme_timeout,omitempty"` // Configures the various ACME challenge types. Challenges *ChallengesConfig `json:"challenges,omitempty"` // An array of files of CA certificates to accept when connecting to the // ACME CA. Generally, you should only use this if the ACME CA endpoint // is internal or for development/testing purposes. TrustedRootsPEMFiles []string `json:"trusted_roots_pem_files,omitempty"` // Preferences for selecting alternate certificate chains, if offered // by the CA. By default, the first offered chain will be selected. // If configured, the chains may be sorted and the first matching chain // will be selected. PreferredChains *ChainPreference `json:"preferred_chains,omitempty"` rootPool *x509.CertPool logger *zap.Logger template certmagic.ACMEIssuer // set at Provision magic *certmagic.Config // set at PreCheck issuer *certmagic.ACMEIssuer // set at PreCheck; result of template + magic } // CaddyModule returns the Caddy module information. func (ACMEIssuer) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "tls.issuance.acme", New: func() caddy.Module { return new(ACMEIssuer) }, } } // Provision sets up iss. func (iss *ACMEIssuer) Provision(ctx caddy.Context) error { iss.logger = ctx.Logger() repl := caddy.NewReplacer() // expand email address, if non-empty if iss.Email != "" { email, err := repl.ReplaceOrErr(iss.Email, true, true) if err != nil { return fmt.Errorf("expanding email address '%s': %v", iss.Email, err) } iss.Email = email } // expand account key, if non-empty if iss.AccountKey != "" { accountKey, err := repl.ReplaceOrErr(iss.AccountKey, true, true) if err != nil { return fmt.Errorf("expanding account key PEM '%s': %v", iss.AccountKey, err) } iss.AccountKey = accountKey } // DNS providers if iss.Challenges != nil && iss.Challenges.DNS != nil && iss.Challenges.DNS.ProviderRaw != nil { val, err := ctx.LoadModule(iss.Challenges.DNS, "ProviderRaw") if err != nil { return fmt.Errorf("loading DNS provider module: %v", err) } if deprecatedProvider, ok := val.(acmez.Solver); ok { // TODO: For a temporary amount of time, we are allowing the use of DNS // providers from go-acme/lego since there are so many providers implemented // using that API -- they are adapted as an all-in-one Caddy module in this // repository: https://github.com/caddy-dns/lego-deprecated - the module is a // acmez.Solver type, so we use it directly. The user must set environment // variables to configure it. Remove this shim once a sufficient number of // DNS providers are implemented for the libdns APIs instead. iss.Challenges.DNS.solver = deprecatedProvider } else { iss.Challenges.DNS.solver = &certmagic.DNS01Solver{ DNSProvider: val.(certmagic.ACMEDNSProvider), TTL: time.Duration(iss.Challenges.DNS.TTL), PropagationDelay: time.Duration(iss.Challenges.DNS.PropagationDelay), PropagationTimeout: time.Duration(iss.Challenges.DNS.PropagationTimeout), Resolvers: iss.Challenges.DNS.Resolvers, OverrideDomain: iss.Challenges.DNS.OverrideDomain, } } } // add any custom CAs to trust store if len(iss.TrustedRootsPEMFiles) > 0 { iss.rootPool = x509.NewCertPool() for _, pemFile := range iss.TrustedRootsPEMFiles { pemData, err := os.ReadFile(pemFile) if err != nil { return fmt.Errorf("loading trusted root CA's PEM file: %s: %v", pemFile, err) } if !iss.rootPool.AppendCertsFromPEM(pemData) { return fmt.Errorf("unable to add %s to trust pool: %v", pemFile, err) } } } var err error iss.template, err = iss.makeIssuerTemplate() if err != nil { return err } return nil } func (iss *ACMEIssuer) makeIssuerTemplate() (certmagic.ACMEIssuer, error) { template := certmagic.ACMEIssuer{ CA: iss.CA, TestCA: iss.TestCA, Email: iss.Email, AccountKeyPEM: iss.AccountKey, CertObtainTimeout: time.Duration(iss.ACMETimeout), TrustedRoots: iss.rootPool, ExternalAccount: iss.ExternalAccount, Logger: iss.logger, } if iss.Challenges != nil { if iss.Challenges.HTTP != nil { template.DisableHTTPChallenge = iss.Challenges.HTTP.Disabled template.AltHTTPPort = iss.Challenges.HTTP.AlternatePort } if iss.Challenges.TLSALPN != nil { template.DisableTLSALPNChallenge = iss.Challenges.TLSALPN.Disabled template.AltTLSALPNPort = iss.Challenges.TLSALPN.AlternatePort } if iss.Challenges.DNS != nil { template.DNS01Solver = iss.Challenges.DNS.solver } template.ListenHost = iss.Challenges.BindHost } if iss.PreferredChains != nil { template.PreferredChains = certmagic.ChainPreference{ Smallest: iss.PreferredChains.Smallest, AnyCommonName: iss.PreferredChains.AnyCommonName, RootCommonName: iss.PreferredChains.RootCommonName, } } return template, nil } // SetConfig sets the associated certmagic config for this issuer. // This is required because ACME needs values from the config in // order to solve the challenges during issuance. This implements // the ConfigSetter interface. func (iss *ACMEIssuer) SetConfig(cfg *certmagic.Config) { iss.magic = cfg iss.issuer = certmagic.NewACMEIssuer(cfg, iss.template) } // PreCheck implements the certmagic.PreChecker interface. func (iss *ACMEIssuer) PreCheck(ctx context.Context, names []string, interactive bool) error { return iss.issuer.PreCheck(ctx, names, interactive) } // Issue obtains a certificate for the given csr. func (iss *ACMEIssuer) Issue(ctx context.Context, csr *x509.CertificateRequest) (*certmagic.IssuedCertificate, error) { return iss.issuer.Issue(ctx, csr) } // IssuerKey returns the unique issuer key for the configured CA endpoint. func (iss *ACMEIssuer) IssuerKey() string { return iss.issuer.IssuerKey() } // Revoke revokes the given certificate. func (iss *ACMEIssuer) Revoke(ctx context.Context, cert certmagic.CertificateResource, reason int) error { return iss.issuer.Revoke(ctx, cert, reason) } // GetACMEIssuer returns iss. This is useful when other types embed ACMEIssuer, because // type-asserting them to *ACMEIssuer will fail, but type-asserting them to an interface // with only this method will succeed, and will still allow the embedded ACMEIssuer // to be accessed and manipulated. func (iss *ACMEIssuer) GetACMEIssuer() *ACMEIssuer { return iss } // UnmarshalCaddyfile deserializes Caddyfile tokens into iss. // // ... acme [<directory_url>] { // dir <directory_url> // test_dir <test_directory_url> // email <email> // timeout <duration> // disable_http_challenge // disable_tlsalpn_challenge // alt_http_port <port> // alt_tlsalpn_port <port> // eab <key_id> <mac_key> // trusted_roots <pem_files...> // dns <provider_name> [<options>] // propagation_delay <duration> // propagation_timeout <duration> // resolvers <dns_servers...> // dns_ttl <duration> // dns_challenge_override_domain <domain> // preferred_chains [smallest] { // root_common_name <common_names...> // any_common_name <common_names...> // } // } func (iss *ACMEIssuer) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { if d.NextArg() { iss.CA = d.Val() if d.NextArg() { return d.ArgErr() } } for nesting := d.Nesting(); d.NextBlock(nesting); { switch d.Val() { case "dir": if iss.CA != "" { return d.Errf("directory is already specified: %s", iss.CA) } if !d.AllArgs(&iss.CA) { return d.ArgErr() } case "test_dir": if !d.AllArgs(&iss.TestCA) { return d.ArgErr() } case "email": if !d.AllArgs(&iss.Email) { return d.ArgErr() } case "timeout": var timeoutStr string if !d.AllArgs(&timeoutStr) { return d.ArgErr() } timeout, err := caddy.ParseDuration(timeoutStr) if err != nil { return d.Errf("invalid timeout duration %s: %v", timeoutStr, err) } iss.ACMETimeout = caddy.Duration(timeout) case "disable_http_challenge": if d.NextArg() { return d.ArgErr() } if iss.Challenges == nil { iss.Challenges = new(ChallengesConfig) } if iss.Challenges.HTTP == nil { iss.Challenges.HTTP = new(HTTPChallengeConfig) } iss.Challenges.HTTP.Disabled = true case "disable_tlsalpn_challenge": if d.NextArg() { return d.ArgErr() } if iss.Challenges == nil { iss.Challenges = new(ChallengesConfig) } if iss.Challenges.TLSALPN == nil { iss.Challenges.TLSALPN = new(TLSALPNChallengeConfig) } iss.Challenges.TLSALPN.Disabled = true case "alt_http_port": if !d.NextArg() { return d.ArgErr() } port, err := strconv.Atoi(d.Val()) if err != nil { return d.Errf("invalid port %s: %v", d.Val(), err) } if iss.Challenges == nil { iss.Challenges = new(ChallengesConfig) } if iss.Challenges.HTTP == nil { iss.Challenges.HTTP = new(HTTPChallengeConfig) } iss.Challenges.HTTP.AlternatePort = port case "alt_tlsalpn_port": if !d.NextArg() { return d.ArgErr() } port, err := strconv.Atoi(d.Val()) if err != nil { return d.Errf("invalid port %s: %v", d.Val(), err) } if iss.Challenges == nil { iss.Challenges = new(ChallengesConfig) } if iss.Challenges.TLSALPN == nil { iss.Challenges.TLSALPN = new(TLSALPNChallengeConfig) } iss.Challenges.TLSALPN.AlternatePort = port case "eab": iss.ExternalAccount = new(acme.EAB) if !d.AllArgs(&iss.ExternalAccount.KeyID, &iss.ExternalAccount.MACKey) { return d.ArgErr() } case "trusted_roots": iss.TrustedRootsPEMFiles = d.RemainingArgs() case "dns": if !d.NextArg() { return d.ArgErr() } provName := d.Val() if iss.Challenges == nil { iss.Challenges = new(ChallengesConfig) } if iss.Challenges.DNS == nil { iss.Challenges.DNS = new(DNSChallengeConfig) } unm, err := caddyfile.UnmarshalModule(d, "dns.providers."+provName) if err != nil { return err } iss.Challenges.DNS.ProviderRaw = caddyconfig.JSONModuleObject(unm, "name", provName, nil) case "propagation_delay": if !d.NextArg() { return d.ArgErr() } delayStr := d.Val() delay, err := caddy.ParseDuration(delayStr) if err != nil { return d.Errf("invalid propagation_delay duration %s: %v", delayStr, err) } if iss.Challenges == nil { iss.Challenges = new(ChallengesConfig) } if iss.Challenges.DNS == nil { iss.Challenges.DNS = new(DNSChallengeConfig) } iss.Challenges.DNS.PropagationDelay = caddy.Duration(delay) case "propagation_timeout": if !d.NextArg() { return d.ArgErr() } timeoutStr := d.Val() var timeout time.Duration if timeoutStr == "-1" { timeout = time.Duration(-1) } else { var err error timeout, err = caddy.ParseDuration(timeoutStr) if err != nil { return d.Errf("invalid propagation_timeout duration %s: %v", timeoutStr, err) } } if iss.Challenges == nil { iss.Challenges = new(ChallengesConfig) } if iss.Challenges.DNS == nil { iss.Challenges.DNS = new(DNSChallengeConfig) } iss.Challenges.DNS.PropagationTimeout = caddy.Duration(timeout) case "resolvers": if iss.Challenges == nil { iss.Challenges = new(ChallengesConfig) } if iss.Challenges.DNS == nil { iss.Challenges.DNS = new(DNSChallengeConfig) } iss.Challenges.DNS.Resolvers = d.RemainingArgs() if len(iss.Challenges.DNS.Resolvers) == 0 { return d.ArgErr() } case "dns_ttl": if !d.NextArg() { return d.ArgErr() } ttlStr := d.Val() ttl, err := caddy.ParseDuration(ttlStr) if err != nil { return d.Errf("invalid dns_ttl duration %s: %v", ttlStr, err) } if iss.Challenges == nil { iss.Challenges = new(ChallengesConfig) } if iss.Challenges.DNS == nil { iss.Challenges.DNS = new(DNSChallengeConfig) } iss.Challenges.DNS.TTL = caddy.Duration(ttl) case "dns_challenge_override_domain": arg := d.RemainingArgs() if len(arg) != 1 { return d.ArgErr() } if iss.Challenges == nil { iss.Challenges = new(ChallengesConfig) } if iss.Challenges.DNS == nil { iss.Challenges.DNS = new(DNSChallengeConfig) } iss.Challenges.DNS.OverrideDomain = arg[0] case "preferred_chains": chainPref, err := ParseCaddyfilePreferredChainsOptions(d) if err != nil { return err } iss.PreferredChains = chainPref default: return d.Errf("unrecognized ACME issuer property: %s", d.Val()) } } } return nil } // onDemandAskRequest makes a request to the ask URL // to see if a certificate can be obtained for name. // The certificate request should be denied if this // returns an error. func onDemandAskRequest(logger *zap.Logger, ask string, name string) error { askURL, err := url.Parse(ask) if err != nil { return fmt.Errorf("parsing ask URL: %v", err) } qs := askURL.Query() qs.Set("domain", name) askURL.RawQuery = qs.Encode() askURLString := askURL.String() resp, err := onDemandAskClient.Get(askURLString) if err != nil { return fmt.Errorf("error checking %v to determine if certificate for hostname '%s' should be allowed: %v", ask, name, err) } resp.Body.Close() logger.Debug("response from ask endpoint", zap.String("domain", name), zap.String("url", askURLString), zap.Int("status", resp.StatusCode)) if resp.StatusCode < 200 || resp.StatusCode > 299 { return fmt.Errorf("%s: %w %s - non-2xx status code %d", name, errAskDenied, ask, resp.StatusCode) } return nil } func ParseCaddyfilePreferredChainsOptions(d *caddyfile.Dispenser) (*ChainPreference, error) { chainPref := new(ChainPreference) if d.NextArg() { smallestOpt := d.Val() if smallestOpt == "smallest" { trueBool := true chainPref.Smallest = &trueBool if d.NextArg() { // Only one argument allowed return nil, d.ArgErr() } if d.NextBlock(d.Nesting()) { // Don't allow other options when smallest == true return nil, d.Err("No more options are accepted when using the 'smallest' option") } } else { // Smallest option should always be 'smallest' or unset return nil, d.Errf("Invalid argument '%s'", smallestOpt) } } for nesting := d.Nesting(); d.NextBlock(nesting); { switch d.Val() { case "root_common_name": rootCommonNameOpt := d.RemainingArgs() chainPref.RootCommonName = rootCommonNameOpt if rootCommonNameOpt == nil { return nil, d.ArgErr() } if chainPref.AnyCommonName != nil { return nil, d.Err("Can't set root_common_name when any_common_name is already set") } case "any_common_name": anyCommonNameOpt := d.RemainingArgs() chainPref.AnyCommonName = anyCommonNameOpt if anyCommonNameOpt == nil { return nil, d.ArgErr() } if chainPref.RootCommonName != nil { return nil, d.Err("Can't set any_common_name when root_common_name is already set") } default: return nil, d.Errf("Received unrecognized parameter '%s'", d.Val()) } } if chainPref.Smallest == nil && chainPref.RootCommonName == nil && chainPref.AnyCommonName == nil { return nil, d.Err("No options for preferred_chains received") } return chainPref, nil } // ChainPreference describes the client's preferred certificate chain, // useful if the CA offers alternate chains. The first matching chain // will be selected. type ChainPreference struct { // Prefer chains with the fewest number of bytes. Smallest *bool `json:"smallest,omitempty"` // Select first chain having a root with one of // these common names. RootCommonName []string `json:"root_common_name,omitempty"` // Select first chain that has any issuer with one // of these common names. AnyCommonName []string `json:"any_common_name,omitempty"` } // errAskDenied is an error that should be wrapped or returned when the // configured "ask" endpoint does not allow a certificate to be issued, // to distinguish that from other errors such as connection failure. var errAskDenied = errors.New("certificate not allowed by ask endpoint") // Interface guards var ( _ certmagic.PreChecker = (*ACMEIssuer)(nil) _ certmagic.Issuer = (*ACMEIssuer)(nil) _ certmagic.Revoker = (*ACMEIssuer)(nil) _ caddy.Provisioner = (*ACMEIssuer)(nil) _ ConfigSetter = (*ACMEIssuer)(nil) _ caddyfile.Unmarshaler = (*ACMEIssuer)(nil) )
Go
caddy/modules/caddytls/automation.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 caddytls import ( "encoding/json" "errors" "fmt" "net/http" "strings" "time" "github.com/caddyserver/certmagic" "github.com/mholt/acmez" "go.uber.org/zap" "github.com/caddyserver/caddy/v2" ) // AutomationConfig governs the automated management of TLS certificates. type AutomationConfig struct { // The list of automation policies. The first policy matching // a certificate or subject name will be applied. Policies []*AutomationPolicy `json:"policies,omitempty"` // On-Demand TLS defers certificate operations to the // moment they are needed, e.g. during a TLS handshake. // Useful when you don't know all the hostnames at // config-time, or when you are not in control of the // domain names you are managing certificates for. // In 2015, Caddy became the first web server to // implement this experimental technology. // // Note that this field does not enable on-demand TLS; // it only configures it for when it is used. To enable // it, create an automation policy with `on_demand`. OnDemand *OnDemandConfig `json:"on_demand,omitempty"` // Caddy staples OCSP (and caches the response) for all // qualifying certificates by default. This setting // changes how often it scans responses for freshness, // and updates them if they are getting stale. Default: 1h OCSPCheckInterval caddy.Duration `json:"ocsp_interval,omitempty"` // Every so often, Caddy will scan all loaded, managed // certificates for expiration. This setting changes how // frequently the scan for expiring certificates is // performed. Default: 10m RenewCheckInterval caddy.Duration `json:"renew_interval,omitempty"` // How often to scan storage units for old or expired // assets and remove them. These scans exert lots of // reads (and list operations) on the storage module, so // choose a longer interval for large deployments. // Default: 24h // // Storage will always be cleaned when the process first // starts. Then, a new cleaning will be started this // duration after the previous cleaning started if the // previous cleaning finished in less than half the time // of this interval (otherwise next start will be skipped). StorageCleanInterval caddy.Duration `json:"storage_clean_interval,omitempty"` defaultPublicAutomationPolicy *AutomationPolicy defaultInternalAutomationPolicy *AutomationPolicy // only initialized if necessary } // AutomationPolicy designates the policy for automating the // management (obtaining, renewal, and revocation) of managed // TLS certificates. // // An AutomationPolicy value is not valid until it has been // provisioned; use the `AddAutomationPolicy()` method on the // TLS app to properly provision a new policy. type AutomationPolicy struct { // Which subjects (hostnames or IP addresses) this policy applies to. // // This list is a filter, not a command. In other words, it is used // only to filter whether this policy should apply to a subject that // needs a certificate; it does NOT command the TLS app to manage a // certificate for that subject. To have Caddy automate a certificate // or specific subjects, use the "automate" certificate loader module // of the TLS app. SubjectsRaw []string `json:"subjects,omitempty"` // The modules that may issue certificates. Default: internal if all // subjects do not qualify for public certificates; othewise acme and // zerossl. IssuersRaw []json.RawMessage `json:"issuers,omitempty" caddy:"namespace=tls.issuance inline_key=module"` // Modules that can get a custom certificate to use for any // given TLS handshake at handshake-time. Custom certificates // can be useful if another entity is managing certificates // and Caddy need only get it and serve it. Specifying a Manager // enables on-demand TLS, i.e. it has the side-effect of setting // the on_demand parameter to `true`. // // TODO: This is an EXPERIMENTAL feature. Subject to change or removal. ManagersRaw []json.RawMessage `json:"get_certificate,omitempty" caddy:"namespace=tls.get_certificate inline_key=via"` // If true, certificates will be requested with MustStaple. Not all // CAs support this, and there are potentially serious consequences // of enabling this feature without proper threat modeling. MustStaple bool `json:"must_staple,omitempty"` // How long before a certificate's expiration to try renewing it, // as a function of its total lifetime. As a general and conservative // rule, it is a good idea to renew a certificate when it has about // 1/3 of its total lifetime remaining. This utilizes the majority // of the certificate's lifetime while still saving time to // troubleshoot problems. However, for extremely short-lived certs, // you may wish to increase the ratio to ~1/2. RenewalWindowRatio float64 `json:"renewal_window_ratio,omitempty"` // The type of key to generate for certificates. // Supported values: `ed25519`, `p256`, `p384`, `rsa2048`, `rsa4096`. KeyType string `json:"key_type,omitempty"` // Optionally configure a separate storage module associated with this // manager, instead of using Caddy's global/default-configured storage. StorageRaw json.RawMessage `json:"storage,omitempty" caddy:"namespace=caddy.storage inline_key=module"` // If true, certificates will be managed "on demand"; that is, during // TLS handshakes or when needed, as opposed to at startup or config // load. This enables On-Demand TLS for this policy. OnDemand bool `json:"on_demand,omitempty"` // Disables OCSP stapling. Disabling OCSP stapling puts clients at // greater risk, reduces their privacy, and usually lowers client // performance. It is NOT recommended to disable this unless you // are able to justify the costs. // EXPERIMENTAL. Subject to change. DisableOCSPStapling bool `json:"disable_ocsp_stapling,omitempty"` // Overrides the URLs of OCSP responders embedded in certificates. // Each key is a OCSP server URL to override, and its value is the // replacement. An empty value will disable querying of that server. // EXPERIMENTAL. Subject to change. OCSPOverrides map[string]string `json:"ocsp_overrides,omitempty"` // Issuers and Managers store the decoded issuer and manager modules; // they are only used to populate an underlying certmagic.Config's // fields during provisioning so that the modules can survive a // re-provisioning. Issuers []certmagic.Issuer `json:"-"` Managers []certmagic.Manager `json:"-"` subjects []string magic *certmagic.Config storage certmagic.Storage } // Provision sets up ap and builds its underlying CertMagic config. func (ap *AutomationPolicy) Provision(tlsApp *TLS) error { // replace placeholders in subjects to allow environment variables repl := caddy.NewReplacer() subjects := make([]string, len(ap.SubjectsRaw)) for i, sub := range ap.SubjectsRaw { subjects[i] = repl.ReplaceAll(sub, "") } ap.subjects = subjects // policy-specific storage implementation if ap.StorageRaw != nil { val, err := tlsApp.ctx.LoadModule(ap, "StorageRaw") if err != nil { return fmt.Errorf("loading TLS storage module: %v", err) } cmStorage, err := val.(caddy.StorageConverter).CertMagicStorage() if err != nil { return fmt.Errorf("creating TLS storage configuration: %v", err) } ap.storage = cmStorage } // we don't store loaded modules directly in the certmagic config since // policy provisioning may happen more than once (during auto-HTTPS) and // loading a module clears its config bytes; thus, load the module and // store them on the policy before putting it on the config // load and provision any cert manager modules if ap.ManagersRaw != nil { vals, err := tlsApp.ctx.LoadModule(ap, "ManagersRaw") if err != nil { return fmt.Errorf("loading external certificate manager modules: %v", err) } for _, getCertVal := range vals.([]any) { ap.Managers = append(ap.Managers, getCertVal.(certmagic.Manager)) } } // load and provision any explicitly-configured issuer modules if ap.IssuersRaw != nil { val, err := tlsApp.ctx.LoadModule(ap, "IssuersRaw") if err != nil { return fmt.Errorf("loading TLS automation management module: %s", err) } for _, issVal := range val.([]any) { ap.Issuers = append(ap.Issuers, issVal.(certmagic.Issuer)) } } issuers := ap.Issuers if len(issuers) == 0 { var err error issuers, err = DefaultIssuersProvisioned(tlsApp.ctx) if err != nil { return err } } keyType := ap.KeyType if keyType != "" { var err error keyType, err = caddy.NewReplacer().ReplaceOrErr(ap.KeyType, true, true) if err != nil { return fmt.Errorf("invalid key type %s: %s", ap.KeyType, err) } if _, ok := supportedCertKeyTypes[keyType]; !ok { return fmt.Errorf("unrecognized key type: %s", keyType) } } keySource := certmagic.StandardKeyGenerator{ KeyType: supportedCertKeyTypes[keyType], } storage := ap.storage if storage == nil { storage = tlsApp.ctx.Storage() } // on-demand TLS var ond *certmagic.OnDemandConfig if ap.OnDemand || len(ap.Managers) > 0 { // ask endpoint is now required after a number of negligence cases causing abuse; // but is still allowed for explicit subjects (non-wildcard, non-unbounded), // for the internal issuer since it doesn't cause ACME issuer pressure if ap.isWildcardOrDefault() && !ap.onlyInternalIssuer() && (tlsApp.Automation == nil || tlsApp.Automation.OnDemand == nil || tlsApp.Automation.OnDemand.Ask == "") { return fmt.Errorf("on-demand TLS cannot be enabled without an 'ask' endpoint to prevent abuse; please refer to documentation for details") } ond = &certmagic.OnDemandConfig{ DecisionFunc: func(name string) error { if tlsApp.Automation == nil || tlsApp.Automation.OnDemand == nil { return nil } if err := onDemandAskRequest(tlsApp.logger, tlsApp.Automation.OnDemand.Ask, name); err != nil { // distinguish true errors from denials, because it's important to elevate actual errors if errors.Is(err, errAskDenied) { tlsApp.logger.Debug("certificate issuance denied", zap.String("ask_endpoint", tlsApp.Automation.OnDemand.Ask), zap.String("domain", name), zap.Error(err)) } else { tlsApp.logger.Error("request to 'ask' endpoint failed", zap.String("ask_endpoint", tlsApp.Automation.OnDemand.Ask), zap.String("domain", name), zap.Error(err)) } return err } // check the rate limiter last because // doing so makes a reservation if !onDemandRateLimiter.Allow() { return fmt.Errorf("on-demand rate limit exceeded") } return nil }, Managers: ap.Managers, } } template := certmagic.Config{ MustStaple: ap.MustStaple, RenewalWindowRatio: ap.RenewalWindowRatio, KeySource: keySource, OnEvent: tlsApp.onEvent, OnDemand: ond, OCSP: certmagic.OCSPConfig{ DisableStapling: ap.DisableOCSPStapling, ResponderOverrides: ap.OCSPOverrides, }, Storage: storage, Issuers: issuers, Logger: tlsApp.logger, } certCacheMu.RLock() ap.magic = certmagic.New(certCache, template) certCacheMu.RUnlock() // sometimes issuers may need the parent certmagic.Config in // order to function properly (for example, ACMEIssuer needs // access to the correct storage and cache so it can solve // ACME challenges -- it's an annoying, inelegant circular // dependency that I don't know how to resolve nicely!) for _, issuer := range ap.magic.Issuers { if annoying, ok := issuer.(ConfigSetter); ok { annoying.SetConfig(ap.magic) } } return nil } // Subjects returns the list of subjects with all placeholders replaced. func (ap *AutomationPolicy) Subjects() []string { return ap.subjects } func (ap *AutomationPolicy) onlyInternalIssuer() bool { if len(ap.Issuers) != 1 { return false } _, ok := ap.Issuers[0].(*InternalIssuer) return ok } // isWildcardOrDefault determines if the subjects include any wildcard domains, // or is the "default" policy (i.e. no subjects) which is unbounded. func (ap *AutomationPolicy) isWildcardOrDefault() bool { isWildcardOrDefault := false if len(ap.subjects) == 0 { isWildcardOrDefault = true } for _, sub := range ap.subjects { if strings.HasPrefix(sub, "*") { isWildcardOrDefault = true break } } return isWildcardOrDefault } // DefaultIssuers returns empty Issuers (not provisioned) to be used as defaults. // This function is experimental and has no compatibility promises. func DefaultIssuers() []certmagic.Issuer { return []certmagic.Issuer{ new(ACMEIssuer), &ZeroSSLIssuer{ACMEIssuer: new(ACMEIssuer)}, } } // DefaultIssuersProvisioned returns empty but provisioned default Issuers from // DefaultIssuers(). This function is experimental and has no compatibility promises. func DefaultIssuersProvisioned(ctx caddy.Context) ([]certmagic.Issuer, error) { issuers := DefaultIssuers() for i, iss := range issuers { if prov, ok := iss.(caddy.Provisioner); ok { err := prov.Provision(ctx) if err != nil { return nil, fmt.Errorf("provisioning default issuer %d: %T: %v", i, iss, err) } } } return issuers, nil } // ChallengesConfig configures the ACME challenges. type ChallengesConfig struct { // HTTP configures the ACME HTTP challenge. This // challenge is enabled and used automatically // and by default. HTTP *HTTPChallengeConfig `json:"http,omitempty"` // TLSALPN configures the ACME TLS-ALPN challenge. // This challenge is enabled and used automatically // and by default. TLSALPN *TLSALPNChallengeConfig `json:"tls-alpn,omitempty"` // Configures the ACME DNS challenge. Because this // challenge typically requires credentials for // interfacing with a DNS provider, this challenge is // not enabled by default. This is the only challenge // type which does not require a direct connection // to Caddy from an external server. // // NOTE: DNS providers are currently being upgraded, // and this API is subject to change, but should be // stabilized soon. DNS *DNSChallengeConfig `json:"dns,omitempty"` // Optionally customize the host to which a listener // is bound if required for solving a challenge. BindHost string `json:"bind_host,omitempty"` } // HTTPChallengeConfig configures the ACME HTTP challenge. type HTTPChallengeConfig struct { // If true, the HTTP challenge will be disabled. Disabled bool `json:"disabled,omitempty"` // An alternate port on which to service this // challenge. Note that the HTTP challenge port is // hard-coded into the spec and cannot be changed, // so you would have to forward packets from the // standard HTTP challenge port to this one. AlternatePort int `json:"alternate_port,omitempty"` } // TLSALPNChallengeConfig configures the ACME TLS-ALPN challenge. type TLSALPNChallengeConfig struct { // If true, the TLS-ALPN challenge will be disabled. Disabled bool `json:"disabled,omitempty"` // An alternate port on which to service this // challenge. Note that the TLS-ALPN challenge port // is hard-coded into the spec and cannot be changed, // so you would have to forward packets from the // standard TLS-ALPN challenge port to this one. AlternatePort int `json:"alternate_port,omitempty"` } // DNSChallengeConfig configures the ACME DNS challenge. // // NOTE: This API is still experimental and is subject to change. type DNSChallengeConfig struct { // The DNS provider module to use which will manage // the DNS records relevant to the ACME challenge. ProviderRaw json.RawMessage `json:"provider,omitempty" caddy:"namespace=dns.providers inline_key=name"` // The TTL of the TXT record used for the DNS challenge. TTL caddy.Duration `json:"ttl,omitempty"` // How long to wait before starting propagation checks. // Default: 0 (no wait). PropagationDelay caddy.Duration `json:"propagation_delay,omitempty"` // Maximum time to wait for temporary DNS record to appear. // Set to -1 to disable propagation checks. // Default: 2 minutes. PropagationTimeout caddy.Duration `json:"propagation_timeout,omitempty"` // Custom DNS resolvers to prefer over system/built-in defaults. // Often necessary to configure when using split-horizon DNS. Resolvers []string `json:"resolvers,omitempty"` // Override the domain to use for the DNS challenge. This // is to delegate the challenge to a different domain, // e.g. one that updates faster or one with a provider API. OverrideDomain string `json:"override_domain,omitempty"` solver acmez.Solver } // OnDemandConfig configures on-demand TLS, for obtaining // needed certificates at handshake-time. Because this // feature can easily be abused, you should use this to // establish rate limits and/or an internal endpoint that // Caddy can "ask" if it should be allowed to manage // certificates for a given hostname. type OnDemandConfig struct { // REQUIRED. If Caddy needs to load a certificate from // storage or obtain/renew a certificate during a TLS // handshake, it will perform a quick HTTP request to // this URL to check if it should be allowed to try to // get a certificate for the name in the "domain" query // string parameter, like so: `?domain=example.com`. // The endpoint must return a 200 OK status if a certificate // is allowed; anything else will cause it to be denied. // Redirects are not followed. Ask string `json:"ask,omitempty"` // DEPRECATED. An optional rate limit to throttle // the checking of storage and the issuance of // certificates from handshakes if not already in // storage. WILL BE REMOVED IN A FUTURE RELEASE. RateLimit *RateLimit `json:"rate_limit,omitempty"` } // DEPRECATED. RateLimit specifies an interval with optional burst size. type RateLimit struct { // A duration value. Storage may be checked and a certificate may be // obtained 'burst' times during this interval. Interval caddy.Duration `json:"interval,omitempty"` // How many times during an interval storage can be checked or a // certificate can be obtained. Burst int `json:"burst,omitempty"` } // ConfigSetter is implemented by certmagic.Issuers that // need access to a parent certmagic.Config as part of // their provisioning phase. For example, the ACMEIssuer // requires a config so it can access storage and the // cache to solve ACME challenges. type ConfigSetter interface { SetConfig(cfg *certmagic.Config) } // These perpetual values are used for on-demand TLS. var ( onDemandRateLimiter = certmagic.NewRateLimiter(0, 0) onDemandAskClient = &http.Client{ Timeout: 10 * time.Second, CheckRedirect: func(req *http.Request, via []*http.Request) error { return fmt.Errorf("following http redirects is not allowed") }, } )
Go
caddy/modules/caddytls/certmanagers.go
package caddytls import ( "context" "crypto/tls" "fmt" "io" "net/http" "net/url" "strings" "github.com/caddyserver/certmagic" "github.com/tailscale/tscert" "go.uber.org/zap" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func init() { caddy.RegisterModule(Tailscale{}) caddy.RegisterModule(HTTPCertGetter{}) } // Tailscale is a module that can get certificates from the local Tailscale process. type Tailscale struct { logger *zap.Logger } // CaddyModule returns the Caddy module information. func (Tailscale) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "tls.get_certificate.tailscale", New: func() caddy.Module { return new(Tailscale) }, } } func (ts *Tailscale) Provision(ctx caddy.Context) error { ts.logger = ctx.Logger() return nil } func (ts Tailscale) GetCertificate(ctx context.Context, hello *tls.ClientHelloInfo) (*tls.Certificate, error) { canGetCert, err := ts.canHazCertificate(ctx, hello) if err == nil && !canGetCert { return nil, nil // pass-thru: Tailscale can't offer a cert for this name } if err != nil { ts.logger.Warn("could not get status; will try to get certificate anyway", zap.Error(err)) } return tscert.GetCertificate(hello) } // canHazCertificate returns true if Tailscale reports it can get a certificate for the given ClientHello. func (ts Tailscale) canHazCertificate(ctx context.Context, hello *tls.ClientHelloInfo) (bool, error) { if !strings.HasSuffix(strings.ToLower(hello.ServerName), tailscaleDomainAliasEnding) { return false, nil } status, err := tscert.GetStatus(ctx) if err != nil { return false, err } for _, domain := range status.CertDomains { if certmagic.MatchWildcard(hello.ServerName, domain) { return true, nil } } return false, nil } // UnmarshalCaddyfile deserializes Caddyfile tokens into ts. // // ... tailscale func (Tailscale) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { if d.NextArg() { return d.ArgErr() } } return nil } // tailscaleDomainAliasEnding is the ending for all Tailscale custom domains. const tailscaleDomainAliasEnding = ".ts.net" // HTTPCertGetter can get a certificate via HTTP(S) request. type HTTPCertGetter struct { // The URL from which to download the certificate. Required. // // The URL will be augmented with query string parameters taken // from the TLS handshake: // // - server_name: The SNI value // - signature_schemes: Comma-separated list of hex IDs of signatures // - cipher_suites: Comma-separated list of hex IDs of cipher suites // // To be valid, the response must be HTTP 200 with a PEM body // consisting of blocks for the certificate chain and the private // key. URL string `json:"url,omitempty"` ctx context.Context } // CaddyModule returns the Caddy module information. func (hcg HTTPCertGetter) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "tls.get_certificate.http", New: func() caddy.Module { return new(HTTPCertGetter) }, } } func (hcg *HTTPCertGetter) Provision(ctx caddy.Context) error { hcg.ctx = ctx if hcg.URL == "" { return fmt.Errorf("URL is required") } return nil } func (hcg HTTPCertGetter) GetCertificate(ctx context.Context, hello *tls.ClientHelloInfo) (*tls.Certificate, error) { sigs := make([]string, len(hello.SignatureSchemes)) for i, sig := range hello.SignatureSchemes { sigs[i] = fmt.Sprintf("%x", uint16(sig)) // you won't believe what %x uses if the val is a Stringer } suites := make([]string, len(hello.CipherSuites)) for i, cs := range hello.CipherSuites { suites[i] = fmt.Sprintf("%x", cs) } parsed, err := url.Parse(hcg.URL) if err != nil { return nil, err } qs := parsed.Query() qs.Set("server_name", hello.ServerName) qs.Set("signature_schemes", strings.Join(sigs, ",")) qs.Set("cipher_suites", strings.Join(suites, ",")) parsed.RawQuery = qs.Encode() req, err := http.NewRequestWithContext(hcg.ctx, http.MethodGet, parsed.String(), nil) if err != nil { return nil, err } resp, err := http.DefaultClient.Do(req) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("got HTTP %d", resp.StatusCode) } bodyBytes, err := io.ReadAll(resp.Body) if err != nil { return nil, fmt.Errorf("error reading response body: %v", err) } cert, err := tlsCertFromCertAndKeyPEMBundle(bodyBytes) if err != nil { return nil, err } return &cert, nil } // UnmarshalCaddyfile deserializes Caddyfile tokens into ts. // // ... http <url> func (hcg *HTTPCertGetter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { if !d.NextArg() { return d.ArgErr() } hcg.URL = d.Val() if d.NextArg() { return d.ArgErr() } for nesting := d.Nesting(); d.NextBlock(nesting); { return d.Err("block not allowed here") } } return nil } // Interface guards var ( _ certmagic.Manager = (*Tailscale)(nil) _ caddy.Provisioner = (*Tailscale)(nil) _ caddyfile.Unmarshaler = (*Tailscale)(nil) _ certmagic.Manager = (*HTTPCertGetter)(nil) _ caddy.Provisioner = (*HTTPCertGetter)(nil) _ caddyfile.Unmarshaler = (*HTTPCertGetter)(nil) )
Go
caddy/modules/caddytls/certselection.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 caddytls import ( "crypto/tls" "crypto/x509" "encoding/json" "fmt" "math/big" "github.com/caddyserver/certmagic" ) // CustomCertSelectionPolicy represents a policy for selecting the certificate // used to complete a handshake when there may be multiple options. All fields // specified must match the candidate certificate for it to be chosen. // This was needed to solve https://github.com/caddyserver/caddy/issues/2588. type CustomCertSelectionPolicy struct { // The certificate must have one of these serial numbers. SerialNumber []bigInt `json:"serial_number,omitempty"` // The certificate must have one of these organization names. SubjectOrganization []string `json:"subject_organization,omitempty"` // The certificate must use this public key algorithm. PublicKeyAlgorithm PublicKeyAlgorithm `json:"public_key_algorithm,omitempty"` // The certificate must have at least one of the tags in the list. AnyTag []string `json:"any_tag,omitempty"` // The certificate must have all of the tags in the list. AllTags []string `json:"all_tags,omitempty"` } // SelectCertificate implements certmagic.CertificateSelector. It // only chooses a certificate that at least meets the criteria in // p. It then chooses the first non-expired certificate that is // compatible with the client. If none are valid, it chooses the // first viable candidate anyway. func (p CustomCertSelectionPolicy) SelectCertificate(hello *tls.ClientHelloInfo, choices []certmagic.Certificate) (certmagic.Certificate, error) { viable := make([]certmagic.Certificate, 0, len(choices)) nextChoice: for _, cert := range choices { if len(p.SerialNumber) > 0 { var found bool for _, sn := range p.SerialNumber { if cert.Leaf.SerialNumber.Cmp(&sn.Int) == 0 { found = true break } } if !found { continue } } if len(p.SubjectOrganization) > 0 { var found bool for _, subjOrg := range p.SubjectOrganization { for _, org := range cert.Leaf.Subject.Organization { if subjOrg == org { found = true break } } } if !found { continue } } if p.PublicKeyAlgorithm != PublicKeyAlgorithm(x509.UnknownPublicKeyAlgorithm) && PublicKeyAlgorithm(cert.Leaf.PublicKeyAlgorithm) != p.PublicKeyAlgorithm { continue } if len(p.AnyTag) > 0 { var found bool for _, tag := range p.AnyTag { if cert.HasTag(tag) { found = true break } } if !found { continue } } if len(p.AllTags) > 0 { for _, tag := range p.AllTags { if !cert.HasTag(tag) { continue nextChoice } } } // this certificate at least meets the policy's requirements, // but we still have to check expiration and compatibility viable = append(viable, cert) } if len(viable) == 0 { return certmagic.Certificate{}, fmt.Errorf("no certificates matched custom selection policy") } return certmagic.DefaultCertificateSelector(hello, viable) } // bigInt is a big.Int type that interops with JSON encodings as a string. type bigInt struct{ big.Int } func (bi bigInt) MarshalJSON() ([]byte, error) { return json.Marshal(bi.String()) } func (bi *bigInt) UnmarshalJSON(p []byte) error { if string(p) == "null" { return nil } var stringRep string err := json.Unmarshal(p, &stringRep) if err != nil { return err } _, ok := bi.SetString(stringRep, 10) if !ok { return fmt.Errorf("not a valid big integer: %s", p) } return nil }
Go
caddy/modules/caddytls/connpolicy.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 caddytls import ( "crypto/tls" "crypto/x509" "encoding/base64" "encoding/json" "fmt" "io" "os" "path/filepath" "strings" "github.com/mholt/acmez" "go.uber.org/zap" "github.com/caddyserver/caddy/v2" ) func init() { caddy.RegisterModule(LeafCertClientAuth{}) } // ConnectionPolicies govern the establishment of TLS connections. It is // an ordered group of connection policies; the first matching policy will // be used to configure TLS connections at handshake-time. type ConnectionPolicies []*ConnectionPolicy // Provision sets up each connection policy. It should be called // during the Validate() phase, after the TLS app (if any) is // already set up. func (cp ConnectionPolicies) Provision(ctx caddy.Context) error { for i, pol := range cp { // matchers mods, err := ctx.LoadModule(pol, "MatchersRaw") if err != nil { return fmt.Errorf("loading handshake matchers: %v", err) } for _, modIface := range mods.(map[string]any) { cp[i].matchers = append(cp[i].matchers, modIface.(ConnectionMatcher)) } // enable HTTP/2 by default if pol.ALPN == nil { pol.ALPN = append(pol.ALPN, defaultALPN...) } // pre-build standard TLS config so we don't have to at handshake-time err = pol.buildStandardTLSConfig(ctx) if err != nil { return fmt.Errorf("connection policy %d: building standard TLS config: %s", i, err) } if pol.ClientAuthentication != nil && len(pol.ClientAuthentication.VerifiersRaw) > 0 { clientCertValidations, err := ctx.LoadModule(pol.ClientAuthentication, "VerifiersRaw") if err != nil { return fmt.Errorf("loading client cert verifiers: %v", err) } for _, validator := range clientCertValidations.([]any) { cp[i].ClientAuthentication.verifiers = append(cp[i].ClientAuthentication.verifiers, validator.(ClientCertificateVerifier)) } } } return nil } // TLSConfig returns a standard-lib-compatible TLS configuration which // selects the first matching policy based on the ClientHello. func (cp ConnectionPolicies) TLSConfig(_ caddy.Context) *tls.Config { // using ServerName to match policies is extremely common, especially in configs // with lots and lots of different policies; we can fast-track those by indexing // them by SNI, so we don't have to iterate potentially thousands of policies // (TODO: this map does not account for wildcards, see if this is a problem in practice? look for reports of high connection latency with wildcard certs but low latency for non-wildcards in multi-thousand-cert deployments) indexedBySNI := make(map[string]ConnectionPolicies) if len(cp) > 30 { for _, p := range cp { for _, m := range p.matchers { if sni, ok := m.(MatchServerName); ok { for _, sniName := range sni { indexedBySNI[sniName] = append(indexedBySNI[sniName], p) } } } } } return &tls.Config{ MinVersion: tls.VersionTLS12, GetConfigForClient: func(hello *tls.ClientHelloInfo) (*tls.Config, error) { // filter policies by SNI first, if possible, to speed things up // when there may be lots of policies possiblePolicies := cp if indexedPolicies, ok := indexedBySNI[hello.ServerName]; ok { possiblePolicies = indexedPolicies } policyLoop: for _, pol := range possiblePolicies { for _, matcher := range pol.matchers { if !matcher.Match(hello) { continue policyLoop } } return pol.TLSConfig, nil } return nil, fmt.Errorf("no server TLS configuration available for ClientHello: %+v", hello) }, } } // ConnectionPolicy specifies the logic for handling a TLS handshake. // An empty policy is valid; safe and sensible defaults will be used. type ConnectionPolicy struct { // How to match this policy with a TLS ClientHello. If // this policy is the first to match, it will be used. MatchersRaw caddy.ModuleMap `json:"match,omitempty" caddy:"namespace=tls.handshake_match"` // How to choose a certificate if more than one matched // the given ServerName (SNI) value. CertSelection *CustomCertSelectionPolicy `json:"certificate_selection,omitempty"` // The list of cipher suites to support. Caddy's // defaults are modern and secure. CipherSuites []string `json:"cipher_suites,omitempty"` // The list of elliptic curves to support. Caddy's // defaults are modern and secure. Curves []string `json:"curves,omitempty"` // Protocols to use for Application-Layer Protocol // Negotiation (ALPN) during the handshake. ALPN []string `json:"alpn,omitempty"` // Minimum TLS protocol version to allow. Default: `tls1.2` ProtocolMin string `json:"protocol_min,omitempty"` // Maximum TLS protocol version to allow. Default: `tls1.3` ProtocolMax string `json:"protocol_max,omitempty"` // Enables and configures TLS client authentication. ClientAuthentication *ClientAuthentication `json:"client_authentication,omitempty"` // DefaultSNI becomes the ServerName in a ClientHello if there // is no policy configured for the empty SNI value. DefaultSNI string `json:"default_sni,omitempty"` // FallbackSNI becomes the ServerName in a ClientHello if // the original ServerName doesn't match any certificates // in the cache. The use cases for this are very niche; // typically if a client is a CDN and passes through the // ServerName of the downstream handshake but can accept // a certificate with the origin's hostname instead, then // you would set this to your origin's hostname. Note that // Caddy must be managing a certificate for this name. // // This feature is EXPERIMENTAL and subject to change or removal. FallbackSNI string `json:"fallback_sni,omitempty"` // Also known as "SSLKEYLOGFILE", TLS secrets will be written to // this file in NSS key log format which can then be parsed by // Wireshark and other tools. This is INSECURE as it allows other // programs or tools to decrypt TLS connections. However, this // capability can be useful for debugging and troubleshooting. // **ENABLING THIS LOG COMPROMISES SECURITY!** // // This feature is EXPERIMENTAL and subject to change or removal. InsecureSecretsLog string `json:"insecure_secrets_log,omitempty"` // TLSConfig is the fully-formed, standard lib TLS config // used to serve TLS connections. Provision all // ConnectionPolicies to populate this. It is exported only // so it can be minimally adjusted after provisioning // if necessary (like to adjust NextProtos to disable HTTP/2), // and may be unexported in the future. TLSConfig *tls.Config `json:"-"` matchers []ConnectionMatcher } func (p *ConnectionPolicy) buildStandardTLSConfig(ctx caddy.Context) error { tlsAppIface, err := ctx.App("tls") if err != nil { return fmt.Errorf("getting tls app: %v", err) } tlsApp := tlsAppIface.(*TLS) // fill in some "easy" default values, but for other values // (such as slices), we should ensure that they start empty // so the user-provided config can fill them in; then we will // fill in a default config at the end if they are still unset cfg := &tls.Config{ NextProtos: p.ALPN, GetCertificate: func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) { // TODO: I don't love how this works: we pre-build certmagic configs // so that handshakes are faster. Unfortunately, certmagic configs are // comprised of settings from both a TLS connection policy and a TLS // automation policy. The only two fields (as of March 2020; v2 beta 17) // of a certmagic config that come from the TLS connection policy are // CertSelection and DefaultServerName, so an automation policy is what // builds the base certmagic config. Since the pre-built config is // shared, I don't think we can change any of its fields per-handshake, // hence the awkward shallow copy (dereference) here and the subsequent // changing of some of its fields. I'm worried this dereference allocates // more at handshake-time, but I don't know how to practically pre-build // a certmagic config for each combination of conn policy + automation policy... cfg := *tlsApp.getConfigForName(hello.ServerName) if p.CertSelection != nil { // you would think we could just set this whether or not // p.CertSelection is nil, but that leads to panics if // it is, because cfg.CertSelection is an interface, // so it will have a non-nil value even if the actual // value underlying it is nil (sigh) cfg.CertSelection = p.CertSelection } cfg.DefaultServerName = p.DefaultSNI cfg.FallbackServerName = p.FallbackSNI return cfg.GetCertificate(hello) }, MinVersion: tls.VersionTLS12, MaxVersion: tls.VersionTLS13, } // session tickets support if tlsApp.SessionTickets != nil { cfg.SessionTicketsDisabled = tlsApp.SessionTickets.Disabled // session ticket key rotation tlsApp.SessionTickets.register(cfg) ctx.OnCancel(func() { // do cleanup when the context is canceled because, // though unlikely, it is possible that a context // needing a TLS server config could exist for less // than the lifetime of the whole app tlsApp.SessionTickets.unregister(cfg) }) } // TODO: Clean up session ticket active locks in storage if app (or process) is being closed! // add all the cipher suites in order, without duplicates cipherSuitesAdded := make(map[uint16]struct{}) for _, csName := range p.CipherSuites { csID := CipherSuiteID(csName) if csID == 0 { return fmt.Errorf("unsupported cipher suite: %s", csName) } if _, ok := cipherSuitesAdded[csID]; !ok { cipherSuitesAdded[csID] = struct{}{} cfg.CipherSuites = append(cfg.CipherSuites, csID) } } // add all the curve preferences in order, without duplicates curvesAdded := make(map[tls.CurveID]struct{}) for _, curveName := range p.Curves { curveID := SupportedCurves[curveName] if _, ok := curvesAdded[curveID]; !ok { curvesAdded[curveID] = struct{}{} cfg.CurvePreferences = append(cfg.CurvePreferences, curveID) } } // ensure ALPN includes the ACME TLS-ALPN protocol var alpnFound bool for _, a := range p.ALPN { if a == acmez.ACMETLS1Protocol { alpnFound = true break } } if !alpnFound && (cfg.NextProtos == nil || len(cfg.NextProtos) > 0) { cfg.NextProtos = append(cfg.NextProtos, acmez.ACMETLS1Protocol) } // min and max protocol versions if (p.ProtocolMin != "" && p.ProtocolMax != "") && p.ProtocolMin > p.ProtocolMax { return fmt.Errorf("protocol min (%x) cannot be greater than protocol max (%x)", p.ProtocolMin, p.ProtocolMax) } if p.ProtocolMin != "" { cfg.MinVersion = SupportedProtocols[p.ProtocolMin] } if p.ProtocolMax != "" { cfg.MaxVersion = SupportedProtocols[p.ProtocolMax] } // client authentication if p.ClientAuthentication != nil { err := p.ClientAuthentication.ConfigureTLSConfig(cfg) if err != nil { return fmt.Errorf("configuring TLS client authentication: %v", err) } } if p.InsecureSecretsLog != "" { filename, err := caddy.NewReplacer().ReplaceOrErr(p.InsecureSecretsLog, true, true) if err != nil { return err } filename, err = filepath.Abs(filename) if err != nil { return err } logFile, _, err := secretsLogPool.LoadOrNew(filename, func() (caddy.Destructor, error) { w, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0o600) return destructableWriter{w}, err }) if err != nil { return err } ctx.OnCancel(func() { _, _ = secretsLogPool.Delete(filename) }) cfg.KeyLogWriter = logFile.(io.Writer) tlsApp.logger.Warn("TLS SECURITY COMPROMISED: secrets logging is enabled!", zap.String("log_filename", filename)) } setDefaultTLSParams(cfg) p.TLSConfig = cfg return nil } // SettingsEmpty returns true if p's settings (fields // except the matchers) are all empty/unset. func (p ConnectionPolicy) SettingsEmpty() bool { return p.CertSelection == nil && p.CipherSuites == nil && p.Curves == nil && p.ALPN == nil && p.ProtocolMin == "" && p.ProtocolMax == "" && p.ClientAuthentication == nil && p.DefaultSNI == "" && p.InsecureSecretsLog == "" } // ClientAuthentication configures TLS client auth. type ClientAuthentication struct { // A list of base64 DER-encoded CA certificates // against which to validate client certificates. // Client certs which are not signed by any of // these CAs will be rejected. TrustedCACerts []string `json:"trusted_ca_certs,omitempty"` // TrustedCACertPEMFiles is a list of PEM file names // from which to load certificates of trusted CAs. // Client certificates which are not signed by any of // these CA certificates will be rejected. TrustedCACertPEMFiles []string `json:"trusted_ca_certs_pem_files,omitempty"` // DEPRECATED: This field is deprecated and will be removed in // a future version. Please use the `validators` field instead // with the tls.client_auth.leaf module instead. // // A list of base64 DER-encoded client leaf certs // to accept. If this list is not empty, client certs // which are not in this list will be rejected. TrustedLeafCerts []string `json:"trusted_leaf_certs,omitempty"` // Client certificate verification modules. These can perform // custom client authentication checks, such as ensuring the // certificate is not revoked. VerifiersRaw []json.RawMessage `json:"verifiers,omitempty" caddy:"namespace=tls.client_auth inline_key=verifier"` verifiers []ClientCertificateVerifier // The mode for authenticating the client. Allowed values are: // // Mode | Description // -----|--------------- // `request` | Ask clients for a certificate, but allow even if there isn't one; do not verify it // `require` | Require clients to present a certificate, but do not verify it // `verify_if_given` | Ask clients for a certificate; allow even if there isn't one, but verify it if there is // `require_and_verify` | Require clients to present a valid certificate that is verified // // The default mode is `require_and_verify` if any // TrustedCACerts or TrustedCACertPEMFiles or TrustedLeafCerts // are provided; otherwise, the default mode is `require`. Mode string `json:"mode,omitempty"` existingVerifyPeerCert func([][]byte, [][]*x509.Certificate) error } // Active returns true if clientauth has an actionable configuration. func (clientauth ClientAuthentication) Active() bool { return len(clientauth.TrustedCACerts) > 0 || len(clientauth.TrustedCACertPEMFiles) > 0 || len(clientauth.TrustedLeafCerts) > 0 || // TODO: DEPRECATED len(clientauth.VerifiersRaw) > 0 || len(clientauth.Mode) > 0 } // ConfigureTLSConfig sets up cfg to enforce clientauth's configuration. func (clientauth *ClientAuthentication) ConfigureTLSConfig(cfg *tls.Config) error { // if there's no actionable client auth, simply disable it if !clientauth.Active() { cfg.ClientAuth = tls.NoClientCert return nil } // enforce desired mode of client authentication if len(clientauth.Mode) > 0 { switch clientauth.Mode { case "request": cfg.ClientAuth = tls.RequestClientCert case "require": cfg.ClientAuth = tls.RequireAnyClientCert case "verify_if_given": cfg.ClientAuth = tls.VerifyClientCertIfGiven case "require_and_verify": cfg.ClientAuth = tls.RequireAndVerifyClientCert default: return fmt.Errorf("client auth mode not recognized: %s", clientauth.Mode) } } else { // otherwise, set a safe default mode if len(clientauth.TrustedCACerts) > 0 || len(clientauth.TrustedCACertPEMFiles) > 0 || len(clientauth.TrustedLeafCerts) > 0 { cfg.ClientAuth = tls.RequireAndVerifyClientCert } else { cfg.ClientAuth = tls.RequireAnyClientCert } } // enforce CA verification by adding CA certs to the ClientCAs pool if len(clientauth.TrustedCACerts) > 0 || len(clientauth.TrustedCACertPEMFiles) > 0 { caPool := x509.NewCertPool() for _, clientCAString := range clientauth.TrustedCACerts { clientCA, err := decodeBase64DERCert(clientCAString) if err != nil { return fmt.Errorf("parsing certificate: %v", err) } caPool.AddCert(clientCA) } for _, pemFile := range clientauth.TrustedCACertPEMFiles { pemContents, err := os.ReadFile(pemFile) if err != nil { return fmt.Errorf("reading %s: %v", pemFile, err) } caPool.AppendCertsFromPEM(pemContents) } cfg.ClientCAs = caPool } // TODO: DEPRECATED: Only here for backwards compatibility. // If leaf cert is specified, enforce by adding a client auth module if len(clientauth.TrustedLeafCerts) > 0 { caddy.Log().Named("tls.connection_policy").Warn("trusted_leaf_certs is deprecated; use leaf verifier module instead") var trustedLeafCerts []*x509.Certificate for _, clientCertString := range clientauth.TrustedLeafCerts { clientCert, err := decodeBase64DERCert(clientCertString) if err != nil { return fmt.Errorf("parsing certificate: %v", err) } trustedLeafCerts = append(trustedLeafCerts, clientCert) } clientauth.verifiers = append(clientauth.verifiers, LeafCertClientAuth{TrustedLeafCerts: trustedLeafCerts}) } // if a custom verification function already exists, wrap it clientauth.existingVerifyPeerCert = cfg.VerifyPeerCertificate cfg.VerifyPeerCertificate = clientauth.verifyPeerCertificate return nil } // verifyPeerCertificate is for use as a tls.Config.VerifyPeerCertificate // callback to do custom client certificate verification. It is intended // for installation only by clientauth.ConfigureTLSConfig(). func (clientauth *ClientAuthentication) verifyPeerCertificate(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error { // first use any pre-existing custom verification function if clientauth.existingVerifyPeerCert != nil { err := clientauth.existingVerifyPeerCert(rawCerts, verifiedChains) if err != nil { return err } } for _, verifier := range clientauth.verifiers { err := verifier.VerifyClientCertificate(rawCerts, verifiedChains) if err != nil { return err } } return nil } // decodeBase64DERCert base64-decodes, then DER-decodes, certStr. func decodeBase64DERCert(certStr string) (*x509.Certificate, error) { derBytes, err := base64.StdEncoding.DecodeString(certStr) if err != nil { return nil, err } return x509.ParseCertificate(derBytes) } // setDefaultTLSParams sets the default TLS cipher suites, protocol versions, // and server preferences of cfg if they are not already set; it does not // overwrite values, only fills in missing values. func setDefaultTLSParams(cfg *tls.Config) { if len(cfg.CipherSuites) == 0 { cfg.CipherSuites = getOptimalDefaultCipherSuites() } // Not a cipher suite, but still important for mitigating protocol downgrade attacks // (prepend since having it at end breaks http2 due to non-h2-approved suites before it) cfg.CipherSuites = append([]uint16{tls.TLS_FALLBACK_SCSV}, cfg.CipherSuites...) if len(cfg.CurvePreferences) == 0 { cfg.CurvePreferences = defaultCurves } if cfg.MinVersion == 0 { cfg.MinVersion = tls.VersionTLS12 } if cfg.MaxVersion == 0 { cfg.MaxVersion = tls.VersionTLS13 } } // LeafCertClientAuth verifies the client's leaf certificate. type LeafCertClientAuth struct { TrustedLeafCerts []*x509.Certificate } // CaddyModule returns the Caddy module information. func (LeafCertClientAuth) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "tls.client_auth.leaf", New: func() caddy.Module { return new(LeafCertClientAuth) }, } } func (l LeafCertClientAuth) VerifyClientCertificate(rawCerts [][]byte, _ [][]*x509.Certificate) error { if len(rawCerts) == 0 { return fmt.Errorf("no client certificate provided") } remoteLeafCert, err := x509.ParseCertificate(rawCerts[0]) if err != nil { return fmt.Errorf("can't parse the given certificate: %s", err.Error()) } for _, trustedLeafCert := range l.TrustedLeafCerts { if remoteLeafCert.Equal(trustedLeafCert) { return nil } } return fmt.Errorf("client leaf certificate failed validation") } // PublicKeyAlgorithm is a JSON-unmarshalable wrapper type. type PublicKeyAlgorithm x509.PublicKeyAlgorithm // UnmarshalJSON satisfies json.Unmarshaler. func (a *PublicKeyAlgorithm) UnmarshalJSON(b []byte) error { algoStr := strings.ToLower(strings.Trim(string(b), `"`)) algo, ok := publicKeyAlgorithms[algoStr] if !ok { return fmt.Errorf("unrecognized public key algorithm: %s (expected one of %v)", algoStr, publicKeyAlgorithms) } *a = PublicKeyAlgorithm(algo) return nil } // ConnectionMatcher is a type which matches TLS handshakes. type ConnectionMatcher interface { Match(*tls.ClientHelloInfo) bool } // ClientCertificateVerifier is a type which verifies client certificates. // It is called during verifyPeerCertificate in the TLS handshake. type ClientCertificateVerifier interface { VerifyClientCertificate(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error } var defaultALPN = []string{"h2", "http/1.1"} type destructableWriter struct{ *os.File } func (d destructableWriter) Destruct() error { return d.Close() } var secretsLogPool = caddy.NewUsagePool()
Go
caddy/modules/caddytls/fileloader.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 caddytls import ( "crypto/tls" "fmt" "os" "github.com/caddyserver/caddy/v2" ) func init() { caddy.RegisterModule(FileLoader{}) } // FileLoader loads certificates and their associated keys from disk. type FileLoader []CertKeyFilePair // CaddyModule returns the Caddy module information. func (FileLoader) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "tls.certificates.load_files", New: func() caddy.Module { return new(FileLoader) }, } } // CertKeyFilePair pairs certificate and key file names along with their // encoding format so that they can be loaded from disk. type CertKeyFilePair struct { // Path to the certificate (public key) file. Certificate string `json:"certificate"` // Path to the private key file. Key string `json:"key"` // The format of the cert and key. Can be "pem". Default: "pem" Format string `json:"format,omitempty"` // Arbitrary values to associate with this certificate. // Can be useful when you want to select a particular // certificate when there may be multiple valid candidates. Tags []string `json:"tags,omitempty"` } // LoadCertificates returns the certificates to be loaded by fl. func (fl FileLoader) LoadCertificates() ([]Certificate, error) { certs := make([]Certificate, 0, len(fl)) for _, pair := range fl { certData, err := os.ReadFile(pair.Certificate) if err != nil { return nil, err } keyData, err := os.ReadFile(pair.Key) if err != nil { return nil, err } var cert tls.Certificate switch pair.Format { case "": fallthrough case "pem": cert, err = tls.X509KeyPair(certData, keyData) default: return nil, fmt.Errorf("unrecognized certificate/key encoding format: %s", pair.Format) } if err != nil { return nil, err } certs = append(certs, Certificate{Certificate: cert, Tags: pair.Tags}) } return certs, nil } // Interface guard var _ CertificateLoader = (FileLoader)(nil)
Go
caddy/modules/caddytls/folderloader.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 caddytls import ( "bytes" "crypto/tls" "encoding/pem" "fmt" "os" "path/filepath" "strings" "github.com/caddyserver/caddy/v2" ) func init() { caddy.RegisterModule(FolderLoader{}) } // FolderLoader loads certificates and their associated keys from disk // by recursively walking the specified directories, looking for PEM // files which contain both a certificate and a key. type FolderLoader []string // CaddyModule returns the Caddy module information. func (FolderLoader) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "tls.certificates.load_folders", New: func() caddy.Module { return new(FolderLoader) }, } } // LoadCertificates loads all the certificates+keys in the directories // listed in fl from all files ending with .pem. This method of loading // certificates expects the certificate and key to be bundled into the // same file. func (fl FolderLoader) LoadCertificates() ([]Certificate, error) { var certs []Certificate for _, dir := range fl { err := filepath.Walk(dir, func(fpath string, info os.FileInfo, err error) error { if err != nil { return fmt.Errorf("unable to traverse into path: %s", fpath) } if info.IsDir() { return nil } if !strings.HasSuffix(strings.ToLower(info.Name()), ".pem") { return nil } bundle, err := os.ReadFile(fpath) if err != nil { return err } cert, err := tlsCertFromCertAndKeyPEMBundle(bundle) if err != nil { return fmt.Errorf("%s: %w", fpath, err) } certs = append(certs, Certificate{Certificate: cert}) return nil }) if err != nil { return nil, err } } return certs, nil } func tlsCertFromCertAndKeyPEMBundle(bundle []byte) (tls.Certificate, error) { certBuilder, keyBuilder := new(bytes.Buffer), new(bytes.Buffer) var foundKey bool // use only the first key in the file for { // Decode next block so we can see what type it is var derBlock *pem.Block derBlock, bundle = pem.Decode(bundle) if derBlock == nil { break } if derBlock.Type == "CERTIFICATE" { // Re-encode certificate as PEM, appending to certificate chain if err := pem.Encode(certBuilder, derBlock); err != nil { return tls.Certificate{}, err } } else if derBlock.Type == "EC PARAMETERS" { // EC keys generated from openssl can be composed of two blocks: // parameters and key (parameter block should come first) if !foundKey { // Encode parameters if err := pem.Encode(keyBuilder, derBlock); err != nil { return tls.Certificate{}, err } // Key must immediately follow derBlock, bundle = pem.Decode(bundle) if derBlock == nil || derBlock.Type != "EC PRIVATE KEY" { return tls.Certificate{}, fmt.Errorf("expected elliptic private key to immediately follow EC parameters") } if err := pem.Encode(keyBuilder, derBlock); err != nil { return tls.Certificate{}, err } foundKey = true } } else if derBlock.Type == "PRIVATE KEY" || strings.HasSuffix(derBlock.Type, " PRIVATE KEY") { // RSA key if !foundKey { if err := pem.Encode(keyBuilder, derBlock); err != nil { return tls.Certificate{}, err } foundKey = true } } else { return tls.Certificate{}, fmt.Errorf("unrecognized PEM block type: %s", derBlock.Type) } } certPEMBytes, keyPEMBytes := certBuilder.Bytes(), keyBuilder.Bytes() if len(certPEMBytes) == 0 { return tls.Certificate{}, fmt.Errorf("failed to parse PEM data") } if len(keyPEMBytes) == 0 { return tls.Certificate{}, fmt.Errorf("no private key block found") } cert, err := tls.X509KeyPair(certPEMBytes, keyPEMBytes) if err != nil { return tls.Certificate{}, fmt.Errorf("making X509 key pair: %v", err) } return cert, nil } var _ CertificateLoader = (FolderLoader)(nil)
Go
caddy/modules/caddytls/internalissuer.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 caddytls import ( "bytes" "context" "crypto/x509" "encoding/pem" "time" "github.com/caddyserver/certmagic" "github.com/smallstep/certificates/authority/provisioner" "go.uber.org/zap" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/modules/caddypki" ) func init() { caddy.RegisterModule(InternalIssuer{}) } // InternalIssuer is a certificate issuer that generates // certificates internally using a locally-configured // CA which can be customized using the `pki` app. type InternalIssuer struct { // The ID of the CA to use for signing. The default // CA ID is "local". The CA can be configured with the // `pki` app. CA string `json:"ca,omitempty"` // The validity period of certificates. Lifetime caddy.Duration `json:"lifetime,omitempty"` // If true, the root will be the issuer instead of // the intermediate. This is NOT recommended and should // only be used when devices/clients do not properly // validate certificate chains. SignWithRoot bool `json:"sign_with_root,omitempty"` ca *caddypki.CA logger *zap.Logger } // CaddyModule returns the Caddy module information. func (InternalIssuer) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "tls.issuance.internal", New: func() caddy.Module { return new(InternalIssuer) }, } } // Provision sets up the issuer. func (iss *InternalIssuer) Provision(ctx caddy.Context) error { iss.logger = ctx.Logger() // set some defaults if iss.CA == "" { iss.CA = caddypki.DefaultCAID } // get a reference to the configured CA appModule, err := ctx.App("pki") if err != nil { return err } pkiApp := appModule.(*caddypki.PKI) ca, err := pkiApp.GetCA(ctx, iss.CA) if err != nil { return err } iss.ca = ca // set any other default values if iss.Lifetime == 0 { iss.Lifetime = caddy.Duration(defaultInternalCertLifetime) } return nil } // IssuerKey returns the unique issuer key for the // confgured CA endpoint. func (iss InternalIssuer) IssuerKey() string { return iss.ca.ID } // Issue issues a certificate to satisfy the CSR. func (iss InternalIssuer) Issue(ctx context.Context, csr *x509.CertificateRequest) (*certmagic.IssuedCertificate, error) { // prepare the signing authority authCfg := caddypki.AuthorityConfig{ SignWithRoot: iss.SignWithRoot, } auth, err := iss.ca.NewAuthority(authCfg) if err != nil { return nil, err } // get the cert (public key) that will be used for signing var issuerCert *x509.Certificate if iss.SignWithRoot { issuerCert = iss.ca.RootCertificate() } else { issuerCert = iss.ca.IntermediateCertificate() } // ensure issued certificate does not expire later than its issuer lifetime := time.Duration(iss.Lifetime) if time.Now().Add(lifetime).After(issuerCert.NotAfter) { lifetime = time.Until(issuerCert.NotAfter) iss.logger.Warn("cert lifetime would exceed issuer NotAfter, clamping lifetime", zap.Duration("orig_lifetime", time.Duration(iss.Lifetime)), zap.Duration("lifetime", lifetime), zap.Time("not_after", issuerCert.NotAfter), ) } certChain, err := auth.Sign(csr, provisioner.SignOptions{}, customCertLifetime(caddy.Duration(lifetime))) if err != nil { return nil, err } var buf bytes.Buffer for _, cert := range certChain { err := pem.Encode(&buf, &pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw}) if err != nil { return nil, err } } return &certmagic.IssuedCertificate{ Certificate: buf.Bytes(), }, nil } // UnmarshalCaddyfile deserializes Caddyfile tokens into iss. // // ... internal { // ca <name> // lifetime <duration> // sign_with_root // } func (iss *InternalIssuer) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { for d.NextBlock(0) { switch d.Val() { case "ca": if !d.AllArgs(&iss.CA) { return d.ArgErr() } case "lifetime": if !d.NextArg() { return d.ArgErr() } dur, err := caddy.ParseDuration(d.Val()) if err != nil { return err } iss.Lifetime = caddy.Duration(dur) case "sign_with_root": if d.NextArg() { return d.ArgErr() } iss.SignWithRoot = true } } } return nil } // customCertLifetime allows us to customize certificates that are issued // by Smallstep libs, particularly the NotBefore & NotAfter dates. type customCertLifetime time.Duration func (d customCertLifetime) Modify(cert *x509.Certificate, _ provisioner.SignOptions) error { cert.NotBefore = time.Now() cert.NotAfter = cert.NotBefore.Add(time.Duration(d)) return nil } const defaultInternalCertLifetime = 12 * time.Hour // Interface guards var ( _ caddy.Provisioner = (*InternalIssuer)(nil) _ certmagic.Issuer = (*InternalIssuer)(nil) _ provisioner.CertificateModifier = (*customCertLifetime)(nil) )
Go
caddy/modules/caddytls/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 caddytls import ( "crypto/tls" "fmt" "net" "net/netip" "strings" "github.com/caddyserver/certmagic" "go.uber.org/zap" "github.com/caddyserver/caddy/v2" ) func init() { caddy.RegisterModule(MatchServerName{}) caddy.RegisterModule(MatchRemoteIP{}) } // MatchServerName matches based on SNI. Names in // this list may use left-most-label wildcards, // similar to wildcard certificates. type MatchServerName []string // CaddyModule returns the Caddy module information. func (MatchServerName) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "tls.handshake_match.sni", New: func() caddy.Module { return new(MatchServerName) }, } } // Match matches hello based on SNI. func (m MatchServerName) Match(hello *tls.ClientHelloInfo) bool { for _, name := range m { if certmagic.MatchWildcard(hello.ServerName, name) { return true } } return false } // MatchRemoteIP matches based on the remote IP of the // connection. Specific IPs or CIDR ranges can be specified. // // Note that IPs can sometimes be spoofed, so do not rely // on this as a replacement for actual authentication. type MatchRemoteIP struct { // The IPs or CIDR ranges to match. Ranges []string `json:"ranges,omitempty"` // The IPs or CIDR ranges to *NOT* match. NotRanges []string `json:"not_ranges,omitempty"` cidrs []netip.Prefix notCidrs []netip.Prefix logger *zap.Logger } // CaddyModule returns the Caddy module information. func (MatchRemoteIP) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "tls.handshake_match.remote_ip", New: func() caddy.Module { return new(MatchRemoteIP) }, } } // Provision parses m's IP ranges, either from IP or CIDR expressions. func (m *MatchRemoteIP) Provision(ctx caddy.Context) error { m.logger = ctx.Logger() for _, str := range m.Ranges { cidrs, err := m.parseIPRange(str) if err != nil { return err } m.cidrs = append(m.cidrs, cidrs...) } for _, str := range m.NotRanges { cidrs, err := m.parseIPRange(str) if err != nil { return err } m.notCidrs = append(m.notCidrs, cidrs...) } return nil } // Match matches hello based on the connection's remote IP. func (m MatchRemoteIP) Match(hello *tls.ClientHelloInfo) bool { remoteAddr := hello.Conn.RemoteAddr().String() ipStr, _, err := net.SplitHostPort(remoteAddr) if err != nil { ipStr = remoteAddr // weird; maybe no port? } ipAddr, err := netip.ParseAddr(ipStr) if err != nil { m.logger.Error("invalid client IP addresss", zap.String("ip", ipStr)) return false } return (len(m.cidrs) == 0 || m.matches(ipAddr, m.cidrs)) && (len(m.notCidrs) == 0 || !m.matches(ipAddr, m.notCidrs)) } func (MatchRemoteIP) parseIPRange(str string) ([]netip.Prefix, error) { var cidrs []netip.Prefix if strings.Contains(str, "/") { ipNet, err := netip.ParsePrefix(str) if err != nil { return nil, fmt.Errorf("parsing CIDR expression: %v", err) } cidrs = append(cidrs, ipNet) } else { ipAddr, err := netip.ParseAddr(str) if err != nil { return nil, fmt.Errorf("invalid IP address: '%s': %v", str, err) } ip := netip.PrefixFrom(ipAddr, ipAddr.BitLen()) cidrs = append(cidrs, ip) } return cidrs, nil } func (MatchRemoteIP) matches(ip netip.Addr, ranges []netip.Prefix) bool { for _, ipRange := range ranges { if ipRange.Contains(ip) { return true } } return false } // Interface guards var ( _ ConnectionMatcher = (*MatchServerName)(nil) _ ConnectionMatcher = (*MatchRemoteIP)(nil) )
Go
caddy/modules/caddytls/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 caddytls import ( "context" "crypto/tls" "net" "testing" "github.com/caddyserver/caddy/v2" ) func TestServerNameMatcher(t *testing.T) { for i, tc := range []struct { names []string input string expect bool }{ { names: []string{"example.com"}, input: "example.com", expect: true, }, { names: []string{"example.com"}, input: "foo.com", expect: false, }, { names: []string{"example.com"}, input: "", expect: false, }, { names: []string{}, input: "", expect: false, }, { names: []string{"foo", "example.com"}, input: "example.com", expect: true, }, { names: []string{"foo", "example.com"}, input: "sub.example.com", expect: false, }, { names: []string{"foo", "example.com"}, input: "foo.com", expect: false, }, { names: []string{"*.example.com"}, input: "example.com", expect: false, }, { names: []string{"*.example.com"}, input: "sub.example.com", expect: true, }, { names: []string{"*.example.com", "*.sub.example.com"}, input: "sub2.sub.example.com", expect: true, }, } { chi := &tls.ClientHelloInfo{ServerName: tc.input} actual := MatchServerName(tc.names).Match(chi) if actual != tc.expect { t.Errorf("Test %d: Expected %t but got %t (input=%s match=%v)", i, tc.expect, actual, tc.input, tc.names) } } } func TestRemoteIPMatcher(t *testing.T) { ctx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()}) defer cancel() for i, tc := range []struct { ranges []string notRanges []string input string expect bool }{ { ranges: []string{"127.0.0.1"}, input: "127.0.0.1:12345", expect: true, }, { ranges: []string{"127.0.0.1"}, input: "127.0.0.2:12345", expect: false, }, { ranges: []string{"127.0.0.1/16"}, input: "127.0.1.23:12345", expect: true, }, { ranges: []string{"127.0.0.1", "192.168.1.105"}, input: "192.168.1.105:12345", expect: true, }, { notRanges: []string{"127.0.0.1"}, input: "127.0.0.1:12345", expect: false, }, { notRanges: []string{"127.0.0.2"}, input: "127.0.0.1:12345", expect: true, }, { ranges: []string{"127.0.0.1"}, notRanges: []string{"127.0.0.2"}, input: "127.0.0.1:12345", expect: true, }, { ranges: []string{"127.0.0.2"}, notRanges: []string{"127.0.0.2"}, input: "127.0.0.2:12345", expect: false, }, { ranges: []string{"127.0.0.2"}, notRanges: []string{"127.0.0.2"}, input: "127.0.0.3:12345", expect: false, }, } { matcher := MatchRemoteIP{Ranges: tc.ranges, NotRanges: tc.notRanges} err := matcher.Provision(ctx) if err != nil { t.Fatalf("Test %d: Provision failed: %v", i, err) } addr := testAddr(tc.input) chi := &tls.ClientHelloInfo{Conn: testConn{addr: addr}} actual := matcher.Match(chi) if actual != tc.expect { t.Errorf("Test %d: Expected %t but got %t (input=%s ranges=%v notRanges=%v)", i, tc.expect, actual, tc.input, tc.ranges, tc.notRanges) } } } type testConn struct { *net.TCPConn addr testAddr } func (tc testConn) RemoteAddr() net.Addr { return tc.addr } type testAddr string func (testAddr) Network() string { return "tcp" } func (ta testAddr) String() string { return string(ta) }
Go
caddy/modules/caddytls/pemloader.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 caddytls import ( "crypto/tls" "fmt" "github.com/caddyserver/caddy/v2" ) func init() { caddy.RegisterModule(PEMLoader{}) } // PEMLoader loads certificates and their associated keys by // decoding their PEM blocks directly. This has the advantage // of not needing to store them on disk at all. type PEMLoader []CertKeyPEMPair // CaddyModule returns the Caddy module information. func (PEMLoader) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "tls.certificates.load_pem", New: func() caddy.Module { return new(PEMLoader) }, } } // CertKeyPEMPair pairs certificate and key PEM blocks. type CertKeyPEMPair struct { // The certificate (public key) in PEM format. CertificatePEM string `json:"certificate"` // The private key in PEM format. KeyPEM string `json:"key"` // Arbitrary values to associate with this certificate. // Can be useful when you want to select a particular // certificate when there may be multiple valid candidates. Tags []string `json:"tags,omitempty"` } // LoadCertificates returns the certificates contained in pl. func (pl PEMLoader) LoadCertificates() ([]Certificate, error) { certs := make([]Certificate, 0, len(pl)) for i, pair := range pl { cert, err := tls.X509KeyPair([]byte(pair.CertificatePEM), []byte(pair.KeyPEM)) if err != nil { return nil, fmt.Errorf("PEM pair %d: %v", i, err) } certs = append(certs, Certificate{ Certificate: cert, Tags: pair.Tags, }) } return certs, nil } // Interface guard var _ CertificateLoader = (PEMLoader)(nil)
Go
caddy/modules/caddytls/sessiontickets.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 caddytls import ( "crypto/rand" "crypto/tls" "encoding/json" "fmt" "io" "log" "runtime/debug" "sync" "time" "github.com/caddyserver/caddy/v2" ) // SessionTicketService configures and manages TLS session tickets. type SessionTicketService struct { // KeySource is the method by which Caddy produces or obtains // TLS session ticket keys (STEKs). By default, Caddy generates // them internally using a secure pseudorandom source. KeySource json.RawMessage `json:"key_source,omitempty" caddy:"namespace=tls.stek inline_key=provider"` // How often Caddy rotates STEKs. Default: 12h. RotationInterval caddy.Duration `json:"rotation_interval,omitempty"` // The maximum number of keys to keep in rotation. Default: 4. MaxKeys int `json:"max_keys,omitempty"` // Disables STEK rotation. DisableRotation bool `json:"disable_rotation,omitempty"` // Disables TLS session resumption by tickets. Disabled bool `json:"disabled,omitempty"` keySource STEKProvider configs map[*tls.Config]struct{} stopChan chan struct{} currentKeys [][32]byte mu *sync.Mutex } func (s *SessionTicketService) provision(ctx caddy.Context) error { s.configs = make(map[*tls.Config]struct{}) s.mu = new(sync.Mutex) // establish sane defaults if s.RotationInterval == 0 { s.RotationInterval = caddy.Duration(defaultSTEKRotationInterval) } if s.MaxKeys <= 0 { s.MaxKeys = defaultMaxSTEKs } if s.KeySource == nil { s.KeySource = json.RawMessage(`{"provider":"standard"}`) } // load the STEK module, which will provide keys val, err := ctx.LoadModule(s, "KeySource") if err != nil { return fmt.Errorf("loading TLS session ticket ephemeral keys provider module: %s", err) } s.keySource = val.(STEKProvider) // if session tickets or just rotation are // disabled, no need to start service if s.Disabled || s.DisableRotation { return nil } // start the STEK module; this ensures we have // a starting key before any config needs one return s.start() } // start loads the starting STEKs and spawns a goroutine // which loops to rotate the STEKs, which continues until // stop() is called. If start() was already called, this // is a no-op. func (s *SessionTicketService) start() error { if s.stopChan != nil { return nil } s.stopChan = make(chan struct{}) // initializing the key source gives us our // initial key(s) to start with; if successful, // we need to be sure to call Next() so that // the key source can know when it is done initialKeys, err := s.keySource.Initialize(s) if err != nil { return fmt.Errorf("setting STEK module configuration: %v", err) } s.mu.Lock() s.currentKeys = initialKeys s.mu.Unlock() // keep the keys rotated go s.stayUpdated() return nil } // stayUpdated is a blocking function which rotates // the keys whenever new ones are sent. It reads // from keysChan until s.stop() is called. func (s *SessionTicketService) stayUpdated() { defer func() { if err := recover(); err != nil { log.Printf("[PANIC] session ticket service: %v\n%s", err, debug.Stack()) } }() // this call is essential when Initialize() // returns without error, because the stop // channel is the only way the key source // will know when to clean up keysChan := s.keySource.Next(s.stopChan) for { select { case newKeys := <-keysChan: s.mu.Lock() s.currentKeys = newKeys configs := s.configs s.mu.Unlock() for cfg := range configs { cfg.SetSessionTicketKeys(newKeys) } case <-s.stopChan: return } } } // stop terminates the key rotation goroutine. func (s *SessionTicketService) stop() { if s.stopChan != nil { close(s.stopChan) } } // register sets the session ticket keys on cfg // and keeps them updated. Any values registered // must be unregistered, or they will not be // garbage-collected. s.start() must have been // called first. If session tickets are disabled // or if ticket key rotation is disabled, this // function is a no-op. func (s *SessionTicketService) register(cfg *tls.Config) { if s.Disabled || s.DisableRotation { return } s.mu.Lock() cfg.SetSessionTicketKeys(s.currentKeys) s.configs[cfg] = struct{}{} s.mu.Unlock() } // unregister stops session key management on cfg and // removes the internal stored reference to cfg. If // session tickets are disabled or if ticket key rotation // is disabled, this function is a no-op. func (s *SessionTicketService) unregister(cfg *tls.Config) { if s.Disabled || s.DisableRotation { return } s.mu.Lock() delete(s.configs, cfg) s.mu.Unlock() } // RotateSTEKs rotates the keys in keys by producing a new key and eliding // the oldest one. The new slice of keys is returned. func (s SessionTicketService) RotateSTEKs(keys [][32]byte) ([][32]byte, error) { // produce a new key newKey, err := s.generateSTEK() if err != nil { return nil, fmt.Errorf("generating STEK: %v", err) } // we need to prepend this new key to the list of // keys so that it is preferred, but we need to be // careful that we do not grow the slice larger // than MaxKeys, otherwise we'll be storing one // more key in memory than we expect; so be sure // that the slice does not grow beyond the limit // even for a brief period of time, since there's // no guarantee when that extra allocation will // be overwritten; this is why we first trim the // length to one less the max, THEN prepend the // new key if len(keys) >= s.MaxKeys { keys[len(keys)-1] = [32]byte{} // zero-out memory of oldest key keys = keys[:s.MaxKeys-1] // trim length of slice } keys = append([][32]byte{newKey}, keys...) // prepend new key return keys, nil } // generateSTEK generates key material suitable for use as a // session ticket ephemeral key. func (s *SessionTicketService) generateSTEK() ([32]byte, error) { var newTicketKey [32]byte _, err := io.ReadFull(rand.Reader, newTicketKey[:]) return newTicketKey, err } // STEKProvider is a type that can provide session ticket ephemeral // keys (STEKs). type STEKProvider interface { // Initialize provides the STEK configuration to the STEK // module so that it can obtain and manage keys accordingly. // It returns the initial key(s) to use. Implementations can // rely on Next() being called if Initialize() returns // without error, so that it may know when it is done. Initialize(config *SessionTicketService) ([][32]byte, error) // Next returns the channel through which the next session // ticket keys will be transmitted until doneChan is closed. // Keys should be sent on keysChan as they are updated. // When doneChan is closed, any resources allocated in // Initialize() must be cleaned up. Next(doneChan <-chan struct{}) (keysChan <-chan [][32]byte) } const ( defaultSTEKRotationInterval = 12 * time.Hour defaultMaxSTEKs = 4 )
Go
caddy/modules/caddytls/storageloader.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 caddytls import ( "crypto/tls" "fmt" "github.com/caddyserver/certmagic" "github.com/caddyserver/caddy/v2" ) func init() { caddy.RegisterModule(StorageLoader{}) } // StorageLoader loads certificates and their associated keys // from the globally configured storage module. type StorageLoader struct { // A list of pairs of certificate and key file names along with their // encoding format so that they can be loaded from storage. Pairs []CertKeyFilePair `json:"pairs,omitempty"` // Reference to the globally configured storage module. storage certmagic.Storage ctx caddy.Context } // CaddyModule returns the Caddy module information. func (StorageLoader) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "tls.certificates.load_storage", New: func() caddy.Module { return new(StorageLoader) }, } } // Provision loads the storage module for sl. func (sl *StorageLoader) Provision(ctx caddy.Context) error { sl.storage = ctx.Storage() sl.ctx = ctx return nil } // LoadCertificates returns the certificates to be loaded by sl. func (sl StorageLoader) LoadCertificates() ([]Certificate, error) { certs := make([]Certificate, 0, len(sl.Pairs)) for _, pair := range sl.Pairs { certData, err := sl.storage.Load(sl.ctx, pair.Certificate) if err != nil { return nil, err } keyData, err := sl.storage.Load(sl.ctx, pair.Key) if err != nil { return nil, err } var cert tls.Certificate switch pair.Format { case "": fallthrough case "pem": cert, err = tls.X509KeyPair(certData, keyData) default: return nil, fmt.Errorf("unrecognized certificate/key encoding format: %s", pair.Format) } if err != nil { return nil, err } certs = append(certs, Certificate{Certificate: cert, Tags: pair.Tags}) } return certs, nil } // Interface guard var ( _ CertificateLoader = (*StorageLoader)(nil) _ caddy.Provisioner = (*StorageLoader)(nil) )
Go
caddy/modules/caddytls/tls.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 caddytls import ( "context" "crypto/tls" "encoding/json" "fmt" "log" "net/http" "runtime/debug" "sync" "time" "github.com/caddyserver/certmagic" "go.uber.org/zap" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyevents" ) func init() { caddy.RegisterModule(TLS{}) caddy.RegisterModule(AutomateLoader{}) } var ( certCache *certmagic.Cache certCacheMu sync.RWMutex ) // TLS provides TLS facilities including certificate // loading and management, client auth, and more. type TLS struct { // Certificates to load into memory for quick recall during // TLS handshakes. Each key is the name of a certificate // loader module. // // The "automate" certificate loader module can be used to // specify a list of subjects that need certificates to be // managed automatically. The first matching automation // policy will be applied to manage the certificate(s). // // All loaded certificates get pooled // into the same cache and may be used to complete TLS // handshakes for the relevant server names (SNI). // Certificates loaded manually (anything other than // "automate") are not automatically managed and will // have to be refreshed manually before they expire. CertificatesRaw caddy.ModuleMap `json:"certificates,omitempty" caddy:"namespace=tls.certificates"` // Configures certificate automation. Automation *AutomationConfig `json:"automation,omitempty"` // Configures session ticket ephemeral keys (STEKs). SessionTickets *SessionTicketService `json:"session_tickets,omitempty"` // Configures the in-memory certificate cache. Cache *CertCacheOptions `json:"cache,omitempty"` // Disables OCSP stapling for manually-managed certificates only. // To configure OCSP stapling for automated certificates, use an // automation policy instead. // // Disabling OCSP stapling puts clients at greater risk, reduces their // privacy, and usually lowers client performance. It is NOT recommended // to disable this unless you are able to justify the costs. // EXPERIMENTAL. Subject to change. DisableOCSPStapling bool `json:"disable_ocsp_stapling,omitempty"` certificateLoaders []CertificateLoader automateNames []string ctx caddy.Context storageCleanTicker *time.Ticker storageCleanStop chan struct{} logger *zap.Logger events *caddyevents.App // set of subjects with managed certificates, // and hashes of manually-loaded certificates managing, loaded map[string]struct{} } // CaddyModule returns the Caddy module information. func (TLS) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "tls", New: func() caddy.Module { return new(TLS) }, } } // Provision sets up the configuration for the TLS app. func (t *TLS) Provision(ctx caddy.Context) error { eventsAppIface, err := ctx.App("events") if err != nil { return fmt.Errorf("getting events app: %v", err) } t.events = eventsAppIface.(*caddyevents.App) t.ctx = ctx t.logger = ctx.Logger() repl := caddy.NewReplacer() t.managing, t.loaded = make(map[string]struct{}), make(map[string]struct{}) // set up a new certificate cache; this (re)loads all certificates cacheOpts := certmagic.CacheOptions{ GetConfigForCert: func(cert certmagic.Certificate) (*certmagic.Config, error) { return t.getConfigForName(cert.Names[0]), nil }, Logger: t.logger.Named("cache"), } if t.Automation != nil { cacheOpts.OCSPCheckInterval = time.Duration(t.Automation.OCSPCheckInterval) cacheOpts.RenewCheckInterval = time.Duration(t.Automation.RenewCheckInterval) } if t.Cache != nil { cacheOpts.Capacity = t.Cache.Capacity } if cacheOpts.Capacity <= 0 { cacheOpts.Capacity = 10000 } certCacheMu.Lock() if certCache == nil { certCache = certmagic.NewCache(cacheOpts) } else { certCache.SetOptions(cacheOpts) } certCacheMu.Unlock() // certificate loaders val, err := ctx.LoadModule(t, "CertificatesRaw") if err != nil { return fmt.Errorf("loading certificate loader modules: %s", err) } for modName, modIface := range val.(map[string]any) { if modName == "automate" { // special case; these will be loaded in later using our automation facilities, // which we want to avoid doing during provisioning if automateNames, ok := modIface.(*AutomateLoader); ok && automateNames != nil { repl := caddy.NewReplacer() subjects := make([]string, len(*automateNames)) for i, sub := range *automateNames { subjects[i] = repl.ReplaceAll(sub, "") } t.automateNames = subjects } else { return fmt.Errorf("loading certificates with 'automate' requires array of strings, got: %T", modIface) } continue } t.certificateLoaders = append(t.certificateLoaders, modIface.(CertificateLoader)) } // automation/management policies if t.Automation == nil { t.Automation = new(AutomationConfig) } t.Automation.defaultPublicAutomationPolicy = new(AutomationPolicy) err = t.Automation.defaultPublicAutomationPolicy.Provision(t) if err != nil { return fmt.Errorf("provisioning default public automation policy: %v", err) } for _, n := range t.automateNames { // if any names specified by the "automate" loader do not qualify for a public // certificate, we should initialize a default internal automation policy // (but we don't want to do this unnecessarily, since it may prompt for password!) if certmagic.SubjectQualifiesForPublicCert(n) { continue } t.Automation.defaultInternalAutomationPolicy = &AutomationPolicy{ IssuersRaw: []json.RawMessage{json.RawMessage(`{"module":"internal"}`)}, } err = t.Automation.defaultInternalAutomationPolicy.Provision(t) if err != nil { return fmt.Errorf("provisioning default internal automation policy: %v", err) } break } for i, ap := range t.Automation.Policies { err := ap.Provision(t) if err != nil { return fmt.Errorf("provisioning automation policy %d: %v", i, err) } } // session ticket ephemeral keys (STEK) service and provider if t.SessionTickets != nil { err := t.SessionTickets.provision(ctx) if err != nil { return fmt.Errorf("provisioning session tickets configuration: %v", err) } } // on-demand rate limiting if t.Automation != nil && t.Automation.OnDemand != nil && t.Automation.OnDemand.RateLimit != nil { onDemandRateLimiter.SetMaxEvents(t.Automation.OnDemand.RateLimit.Burst) onDemandRateLimiter.SetWindow(time.Duration(t.Automation.OnDemand.RateLimit.Interval)) } else { // remove any existing rate limiter onDemandRateLimiter.SetWindow(0) onDemandRateLimiter.SetMaxEvents(0) } // run replacer on ask URL (for environment variables) -- return errors to prevent surprises (#5036) if t.Automation != nil && t.Automation.OnDemand != nil && t.Automation.OnDemand.Ask != "" { t.Automation.OnDemand.Ask, err = repl.ReplaceOrErr(t.Automation.OnDemand.Ask, true, true) if err != nil { return fmt.Errorf("preparing 'ask' endpoint: %v", err) } } // load manual/static (unmanaged) certificates - we do this in // provision so that other apps (such as http) can know which // certificates have been manually loaded, and also so that // commands like validate can be a better test certCacheMu.RLock() magic := certmagic.New(certCache, certmagic.Config{ Storage: ctx.Storage(), Logger: t.logger, OnEvent: t.onEvent, OCSP: certmagic.OCSPConfig{ DisableStapling: t.DisableOCSPStapling, }, }) certCacheMu.RUnlock() for _, loader := range t.certificateLoaders { certs, err := loader.LoadCertificates() if err != nil { return fmt.Errorf("loading certificates: %v", err) } for _, cert := range certs { hash, err := magic.CacheUnmanagedTLSCertificate(ctx, cert.Certificate, cert.Tags) if err != nil { return fmt.Errorf("caching unmanaged certificate: %v", err) } t.loaded[hash] = struct{}{} } } return nil } // Validate validates t's configuration. func (t *TLS) Validate() error { if t.Automation != nil { // ensure that host aren't repeated; since only the first // automation policy is used, repeating a host in the lists // isn't useful and is probably a mistake; same for two // catch-all/default policies var hasDefault bool hostSet := make(map[string]int) for i, ap := range t.Automation.Policies { if len(ap.subjects) == 0 { if hasDefault { return fmt.Errorf("automation policy %d is the second policy that acts as default/catch-all, but will never be used", i) } hasDefault = true } for _, h := range ap.subjects { if first, ok := hostSet[h]; ok { return fmt.Errorf("automation policy %d: cannot apply more than one automation policy to host: %s (first match in policy %d)", i, h, first) } hostSet[h] = i } } } if t.Cache != nil { if t.Cache.Capacity < 0 { return fmt.Errorf("cache capacity must be >= 0") } } return nil } // Start activates the TLS module. func (t *TLS) Start() error { // warn if on-demand TLS is enabled but no restrictions are in place if t.Automation.OnDemand == nil || (t.Automation.OnDemand.Ask == "" && t.Automation.OnDemand.RateLimit == nil) { for _, ap := range t.Automation.Policies { if ap.OnDemand && ap.isWildcardOrDefault() { t.logger.Warn("YOUR SERVER MAY BE VULNERABLE TO ABUSE: on-demand TLS is enabled, but no protections are in place", zap.String("docs", "https://caddyserver.com/docs/automatic-https#on-demand-tls")) break } } } // now that we are running, and all manual certificates have // been loaded, time to load the automated/managed certificates err := t.Manage(t.automateNames) if err != nil { return fmt.Errorf("automate: managing %v: %v", t.automateNames, err) } t.keepStorageClean() return nil } // Stop stops the TLS module and cleans up any allocations. func (t *TLS) Stop() error { // stop the storage cleaner goroutine and ticker if t.storageCleanStop != nil { close(t.storageCleanStop) } if t.storageCleanTicker != nil { t.storageCleanTicker.Stop() } return nil } // Cleanup frees up resources allocated during Provision. func (t *TLS) Cleanup() error { // stop the session ticket rotation goroutine if t.SessionTickets != nil { t.SessionTickets.stop() } // if a new TLS app was loaded, remove certificates from the cache that are no longer // being managed or loaded by the new config; if there is no more TLS app running, // then stop cert maintenance and let the cert cache be GC'ed if nextTLS := caddy.ActiveContext().AppIfConfigured("tls"); nextTLS != nil { nextTLSApp := nextTLS.(*TLS) // compute which certificates were managed or loaded into the cert cache by this // app instance (which is being stopped) that are not managed or loaded by the // new app instance (which just started), and remove them from the cache var noLongerManaged, noLongerLoaded []string for subj := range t.managing { if _, ok := nextTLSApp.managing[subj]; !ok { noLongerManaged = append(noLongerManaged, subj) } } for hash := range t.loaded { if _, ok := nextTLSApp.loaded[hash]; !ok { noLongerLoaded = append(noLongerLoaded, hash) } } certCacheMu.RLock() certCache.RemoveManaged(noLongerManaged) certCache.Remove(noLongerLoaded) certCacheMu.RUnlock() } else { // no more TLS app running, so delete in-memory cert cache certCache.Stop() certCacheMu.Lock() certCache = nil certCacheMu.Unlock() } return nil } // Manage immediately begins managing names according to the // matching automation policy. func (t *TLS) Manage(names []string) error { // for a large number of names, we can be more memory-efficient // by making only one certmagic.Config for all the names that // use that config, rather than calling ManageAsync once for // every name; so first, bin names by AutomationPolicy policyToNames := make(map[*AutomationPolicy][]string) for _, name := range names { ap := t.getAutomationPolicyForName(name) policyToNames[ap] = append(policyToNames[ap], name) } // now that names are grouped by policy, we can simply make one // certmagic.Config for each (potentially large) group of names // and call ManageAsync just once for the whole batch for ap, names := range policyToNames { err := ap.magic.ManageAsync(t.ctx.Context, names) if err != nil { return fmt.Errorf("automate: manage %v: %v", names, err) } for _, name := range names { t.managing[name] = struct{}{} } } return nil } // HandleHTTPChallenge ensures that the HTTP challenge is handled for the // certificate named by r.Host, if it is an HTTP challenge request. It // requires that the automation policy for r.Host has an issuer of type // *certmagic.ACMEManager, or one that is ACME-enabled (GetACMEIssuer()). func (t *TLS) HandleHTTPChallenge(w http.ResponseWriter, r *http.Request) bool { // no-op if it's not an ACME challenge request if !certmagic.LooksLikeHTTPChallenge(r) { return false } // try all the issuers until we find the one that initiated the challenge ap := t.getAutomationPolicyForName(r.Host) type acmeCapable interface{ GetACMEIssuer() *ACMEIssuer } for _, iss := range ap.magic.Issuers { if am, ok := iss.(acmeCapable); ok { iss := am.GetACMEIssuer() if iss.issuer.HandleHTTPChallenge(w, r) { return true } } } // it's possible another server in this process initiated the challenge; // users have requested that Caddy only handle HTTP challenges it initiated, // so that users can proxy the others through to their backends; but we // might not have an automation policy for all identifiers that are trying // to get certificates (e.g. the admin endpoint), so we do this manual check if challenge, ok := certmagic.GetACMEChallenge(r.Host); ok { return certmagic.SolveHTTPChallenge(t.logger, w, r, challenge.Challenge) } return false } // AddAutomationPolicy provisions and adds ap to the list of the app's // automation policies. If an existing automation policy exists that has // fewer hosts in its list than ap does, ap will be inserted before that // other policy (this helps ensure that ap will be prioritized/chosen // over, say, a catch-all policy). func (t *TLS) AddAutomationPolicy(ap *AutomationPolicy) error { if t.Automation == nil { t.Automation = new(AutomationConfig) } err := ap.Provision(t) if err != nil { return err } // sort new automation policies just before any other which is a superset // of this one; if we find an existing policy that covers every subject in // ap but less specifically (e.g. a catch-all policy, or one with wildcards // or with fewer subjects), insert ap just before it, otherwise ap would // never be used because the first matching policy is more general for i, existing := range t.Automation.Policies { // first see if existing is superset of ap for all names var otherIsSuperset bool outer: for _, thisSubj := range ap.subjects { for _, otherSubj := range existing.subjects { if certmagic.MatchWildcard(thisSubj, otherSubj) { otherIsSuperset = true break outer } } } // if existing AP is a superset or if it contains fewer names (i.e. is // more general), then new AP is more specific, so insert before it if otherIsSuperset || len(existing.SubjectsRaw) < len(ap.SubjectsRaw) { t.Automation.Policies = append(t.Automation.Policies[:i], append([]*AutomationPolicy{ap}, t.Automation.Policies[i:]...)...) return nil } } // otherwise just append the new one t.Automation.Policies = append(t.Automation.Policies, ap) return nil } func (t *TLS) getConfigForName(name string) *certmagic.Config { ap := t.getAutomationPolicyForName(name) return ap.magic } // getAutomationPolicyForName returns the first matching automation policy // for the given subject name. If no matching policy can be found, the // default policy is used, depending on whether the name qualifies for a // public certificate or not. func (t *TLS) getAutomationPolicyForName(name string) *AutomationPolicy { for _, ap := range t.Automation.Policies { if len(ap.subjects) == 0 { return ap // no host filter is an automatic match } for _, h := range ap.subjects { if certmagic.MatchWildcard(name, h) { return ap } } } if certmagic.SubjectQualifiesForPublicCert(name) || t.Automation.defaultInternalAutomationPolicy == nil { return t.Automation.defaultPublicAutomationPolicy } return t.Automation.defaultInternalAutomationPolicy } // AllMatchingCertificates returns the list of all certificates in // the cache which could be used to satisfy the given SAN. func AllMatchingCertificates(san string) []certmagic.Certificate { return certCache.AllMatchingCertificates(san) } func (t *TLS) HasCertificateForSubject(subject string) bool { certCacheMu.RLock() allMatchingCerts := certCache.AllMatchingCertificates(subject) certCacheMu.RUnlock() for _, cert := range allMatchingCerts { // check if the cert is manually loaded by this config if _, ok := t.loaded[cert.Hash()]; ok { return true } // check if the cert is automatically managed by this config for _, name := range cert.Names { if _, ok := t.managing[name]; ok { return true } } } return false } // keepStorageClean starts a goroutine that immediately cleans up all // known storage units if it was not recently done, and then runs the // operation at every tick from t.storageCleanTicker. func (t *TLS) keepStorageClean() { t.storageCleanTicker = time.NewTicker(t.storageCleanInterval()) t.storageCleanStop = make(chan struct{}) go func() { defer func() { if err := recover(); err != nil { log.Printf("[PANIC] storage cleaner: %v\n%s", err, debug.Stack()) } }() t.cleanStorageUnits() for { select { case <-t.storageCleanStop: return case <-t.storageCleanTicker.C: t.cleanStorageUnits() } } }() } func (t *TLS) cleanStorageUnits() { storageCleanMu.Lock() defer storageCleanMu.Unlock() // If storage was cleaned recently, don't do it again for now. Although the ticker // calling this function drops missed ticks for us, config reloads discard the old // ticker and replace it with a new one, possibly invoking a cleaning to happen again // too soon. (We divide the interval by 2 because the actual cleaning takes non-zero // time, and we don't want to skip cleanings if we don't have to; whereas if a cleaning // took most of the interval, we'd probably want to skip the next one so we aren't // constantly cleaning. This allows cleanings to take up to half the interval's // duration before we decide to skip the next one.) if !storageClean.IsZero() && time.Since(storageClean) < t.storageCleanInterval()/2 { return } options := certmagic.CleanStorageOptions{ OCSPStaples: true, ExpiredCerts: true, ExpiredCertGracePeriod: 24 * time.Hour * 14, } // avoid cleaning same storage more than once per cleaning cycle storagesCleaned := make(map[string]struct{}) // start with the default/global storage storage := t.ctx.Storage() storageStr := fmt.Sprintf("%v", storage) t.logger.Info("cleaning storage unit", zap.String("description", storageStr)) certmagic.CleanStorage(t.ctx, storage, options) storagesCleaned[storageStr] = struct{}{} // then clean each storage defined in ACME automation policies if t.Automation != nil { for _, ap := range t.Automation.Policies { if ap.storage == nil { continue } storageStr := fmt.Sprintf("%v", ap.storage) if _, ok := storagesCleaned[storageStr]; ok { continue } t.logger.Info("cleaning storage unit", zap.String("description", storageStr)) certmagic.CleanStorage(t.ctx, ap.storage, options) storagesCleaned[storageStr] = struct{}{} } } // remember last time storage was finished cleaning storageClean = time.Now() t.logger.Info("finished cleaning storage units") } func (t *TLS) storageCleanInterval() time.Duration { if t.Automation != nil && t.Automation.StorageCleanInterval > 0 { return time.Duration(t.Automation.StorageCleanInterval) } return defaultStorageCleanInterval } // onEvent translates CertMagic events into Caddy events then dispatches them. func (t *TLS) onEvent(ctx context.Context, eventName string, data map[string]any) error { evt := t.events.Emit(t.ctx, eventName, data) return evt.Aborted } // CertificateLoader is a type that can load certificates. // Certificates can optionally be associated with tags. type CertificateLoader interface { LoadCertificates() ([]Certificate, error) } // Certificate is a TLS certificate, optionally // associated with arbitrary tags. type Certificate struct { tls.Certificate Tags []string } // AutomateLoader will automatically manage certificates for the names in the // list, including obtaining and renewing certificates. Automated certificates // are managed according to their matching automation policy, configured // elsewhere in this app. // // Technically, this is a no-op certificate loader module that is treated as // a special case: it uses this app's automation features to load certificates // for the list of hostnames, rather than loading certificates manually. But // the end result is the same: certificates for these subject names will be // loaded into the in-memory cache and may then be used. type AutomateLoader []string // CaddyModule returns the Caddy module information. func (AutomateLoader) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "tls.certificates.automate", New: func() caddy.Module { return new(AutomateLoader) }, } } // CertCacheOptions configures the certificate cache. type CertCacheOptions struct { // Maximum number of certificates to allow in the // cache. If reached, certificates will be randomly // evicted to make room for new ones. Default: 10,000 Capacity int `json:"capacity,omitempty"` } // Variables related to storage cleaning. var ( defaultStorageCleanInterval = 24 * time.Hour storageClean time.Time storageCleanMu sync.Mutex ) // Interface guards var ( _ caddy.App = (*TLS)(nil) _ caddy.Provisioner = (*TLS)(nil) _ caddy.Validator = (*TLS)(nil) _ caddy.CleanerUpper = (*TLS)(nil) )
Go
caddy/modules/caddytls/values.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 caddytls import ( "crypto/tls" "crypto/x509" "fmt" "github.com/caddyserver/certmagic" "github.com/klauspost/cpuid/v2" ) // CipherSuiteNameSupported returns true if name is // a supported cipher suite. func CipherSuiteNameSupported(name string) bool { return CipherSuiteID(name) != 0 } // CipherSuiteID returns the ID of the cipher suite associated with // the given name, or 0 if the name is not recognized/supported. func CipherSuiteID(name string) uint16 { for _, cs := range SupportedCipherSuites() { if cs.Name == name { return cs.ID } } return 0 } // SupportedCipherSuites returns a list of all the cipher suites // Caddy supports. The list is NOT ordered by security preference. func SupportedCipherSuites() []*tls.CipherSuite { return tls.CipherSuites() } // defaultCipherSuites is the ordered list of all the cipher // suites we want to support by default, assuming AES-NI // (hardware acceleration for AES). var defaultCipherSuitesWithAESNI = []uint16{ tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, } // defaultCipherSuites is the ordered list of all the cipher // suites we want to support by default, assuming lack of // AES-NI (NO hardware acceleration for AES). var defaultCipherSuitesWithoutAESNI = []uint16{ tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, } // getOptimalDefaultCipherSuites returns an appropriate cipher // suite to use depending on the hardware support for AES. // // See https://github.com/caddyserver/caddy/issues/1674 func getOptimalDefaultCipherSuites() []uint16 { if cpuid.CPU.Supports(cpuid.AESNI) { return defaultCipherSuitesWithAESNI } return defaultCipherSuitesWithoutAESNI } // SupportedCurves is the unordered map of supported curves. // https://golang.org/pkg/crypto/tls/#CurveID var SupportedCurves = map[string]tls.CurveID{ "x25519": tls.X25519, "secp256r1": tls.CurveP256, "secp384r1": tls.CurveP384, "secp521r1": tls.CurveP521, } // supportedCertKeyTypes is all the key types that are supported // for certificates that are obtained through ACME. var supportedCertKeyTypes = map[string]certmagic.KeyType{ "rsa2048": certmagic.RSA2048, "rsa4096": certmagic.RSA4096, "p256": certmagic.P256, "p384": certmagic.P384, "ed25519": certmagic.ED25519, } // defaultCurves is the list of only the curves we want to use // by default, in descending order of preference. // // This list should only include curves which are fast by design // (e.g. X25519) and those for which an optimized assembly // implementation exists (e.g. P256). The latter ones can be // found here: // https://github.com/golang/go/tree/master/src/crypto/elliptic var defaultCurves = []tls.CurveID{ tls.X25519, tls.CurveP256, } // SupportedProtocols is a map of supported protocols. var SupportedProtocols = map[string]uint16{ "tls1.2": tls.VersionTLS12, "tls1.3": tls.VersionTLS13, } // unsupportedProtocols is a map of unsupported protocols. // Used for logging only, not enforcement. var unsupportedProtocols = map[string]uint16{ //nolint:staticcheck "ssl3.0": tls.VersionSSL30, "tls1.0": tls.VersionTLS10, "tls1.1": tls.VersionTLS11, } // publicKeyAlgorithms is the map of supported public key algorithms. var publicKeyAlgorithms = map[string]x509.PublicKeyAlgorithm{ "rsa": x509.RSA, "dsa": x509.DSA, "ecdsa": x509.ECDSA, } // ProtocolName returns the standard name for the passed protocol version ID // (e.g. "TLS1.3") or a fallback representation of the ID value if the version // is not supported. func ProtocolName(id uint16) string { for k, v := range SupportedProtocols { if v == id { return k } } for k, v := range unsupportedProtocols { if v == id { return k } } return fmt.Sprintf("0x%04x", id) }
Go
caddy/modules/caddytls/zerosslissuer.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 caddytls import ( "context" "crypto/x509" "encoding/json" "fmt" "io" "net/http" "net/url" "strings" "sync" "github.com/caddyserver/certmagic" "github.com/mholt/acmez/acme" "go.uber.org/zap" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func init() { caddy.RegisterModule(new(ZeroSSLIssuer)) } // ZeroSSLIssuer makes an ACME issuer for getting certificates // from ZeroSSL by automatically generating EAB credentials. // Please be sure to set a valid email address in your config // so you can access/manage your domains in your ZeroSSL account. // // This issuer is only needed for automatic generation of EAB // credentials. If manually configuring/reusing EAB credentials, // the standard ACMEIssuer may be used if desired. type ZeroSSLIssuer struct { *ACMEIssuer // The API key (or "access key") for using the ZeroSSL API. // This is optional, but can be used if you have an API key // already and don't want to supply your email address. APIKey string `json:"api_key,omitempty"` mu sync.Mutex logger *zap.Logger } // CaddyModule returns the Caddy module information. func (*ZeroSSLIssuer) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "tls.issuance.zerossl", New: func() caddy.Module { return new(ZeroSSLIssuer) }, } } // Provision sets up iss. func (iss *ZeroSSLIssuer) Provision(ctx caddy.Context) error { iss.logger = ctx.Logger() if iss.ACMEIssuer == nil { iss.ACMEIssuer = new(ACMEIssuer) } if iss.ACMEIssuer.CA == "" { iss.ACMEIssuer.CA = certmagic.ZeroSSLProductionCA } return iss.ACMEIssuer.Provision(ctx) } // newAccountCallback generates EAB if not already provided. It also sets a valid default contact on the account if not set. func (iss *ZeroSSLIssuer) newAccountCallback(ctx context.Context, acmeIss *certmagic.ACMEIssuer, acct acme.Account) (acme.Account, error) { if acmeIss.ExternalAccount != nil { return acct, nil } var err error acmeIss.ExternalAccount, acct, err = iss.generateEABCredentials(ctx, acct) return acct, err } // generateEABCredentials generates EAB credentials using the API key if provided, // otherwise using the primary contact email on the issuer. If an email is not set // on the issuer, a default generic email is used. func (iss *ZeroSSLIssuer) generateEABCredentials(ctx context.Context, acct acme.Account) (*acme.EAB, acme.Account, error) { var endpoint string var body io.Reader // there are two ways to generate EAB credentials: authenticated with // their API key, or unauthenticated with their email address if iss.APIKey != "" { apiKey := caddy.NewReplacer().ReplaceAll(iss.APIKey, "") if apiKey == "" { return nil, acct, fmt.Errorf("missing API key: '%v'", iss.APIKey) } qs := url.Values{"access_key": []string{apiKey}} endpoint = fmt.Sprintf("%s/eab-credentials?%s", zerosslAPIBase, qs.Encode()) } else { email := iss.Email if email == "" { iss.logger.Warn("missing email address for ZeroSSL; it is strongly recommended to set one for next time") email = "caddy@zerossl.com" // special email address that preserves backwards-compat, but which black-holes dashboard features, oh well } if len(acct.Contact) == 0 { // we borrow the email from config or the default email, so ensure it's saved with the account acct.Contact = []string{"mailto:" + email} } endpoint = zerosslAPIBase + "/eab-credentials-email" form := url.Values{"email": []string{email}} body = strings.NewReader(form.Encode()) } req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, body) if err != nil { return nil, acct, fmt.Errorf("forming request: %v", err) } if body != nil { req.Header.Set("Content-Type", "application/x-www-form-urlencoded") } req.Header.Set("User-Agent", certmagic.UserAgent) resp, err := http.DefaultClient.Do(req) if err != nil { return nil, acct, fmt.Errorf("performing EAB credentials request: %v", err) } defer resp.Body.Close() var result struct { Success bool `json:"success"` Error struct { Code int `json:"code"` Type string `json:"type"` } `json:"error"` EABKID string `json:"eab_kid"` EABHMACKey string `json:"eab_hmac_key"` } err = json.NewDecoder(resp.Body).Decode(&result) if err != nil { return nil, acct, fmt.Errorf("decoding API response: %v", err) } if result.Error.Code != 0 { return nil, acct, fmt.Errorf("failed getting EAB credentials: HTTP %d: %s (code %d)", resp.StatusCode, result.Error.Type, result.Error.Code) } if resp.StatusCode != http.StatusOK { return nil, acct, fmt.Errorf("failed getting EAB credentials: HTTP %d", resp.StatusCode) } iss.logger.Info("generated EAB credentials", zap.String("key_id", result.EABKID)) return &acme.EAB{ KeyID: result.EABKID, MACKey: result.EABHMACKey, }, acct, nil } // initialize modifies the template for the underlying ACMEIssuer // values by setting the CA endpoint to the ZeroSSL directory and // setting the NewAccountFunc callback to one which allows us to // generate EAB credentials only if a new account is being made. // Since it modifies the stored template, its effect should only // be needed once, but it is fine to call it repeatedly. func (iss *ZeroSSLIssuer) initialize() { iss.mu.Lock() defer iss.mu.Unlock() if iss.ACMEIssuer.issuer.NewAccountFunc == nil { iss.ACMEIssuer.issuer.NewAccountFunc = iss.newAccountCallback } } // PreCheck implements the certmagic.PreChecker interface. func (iss *ZeroSSLIssuer) PreCheck(ctx context.Context, names []string, interactive bool) error { iss.initialize() return iss.ACMEIssuer.PreCheck(ctx, names, interactive) } // Issue obtains a certificate for the given csr. func (iss *ZeroSSLIssuer) Issue(ctx context.Context, csr *x509.CertificateRequest) (*certmagic.IssuedCertificate, error) { iss.initialize() return iss.ACMEIssuer.Issue(ctx, csr) } // IssuerKey returns the unique issuer key for the configured CA endpoint. func (iss *ZeroSSLIssuer) IssuerKey() string { iss.initialize() return iss.ACMEIssuer.IssuerKey() } // Revoke revokes the given certificate. func (iss *ZeroSSLIssuer) Revoke(ctx context.Context, cert certmagic.CertificateResource, reason int) error { iss.initialize() return iss.ACMEIssuer.Revoke(ctx, cert, reason) } // UnmarshalCaddyfile deserializes Caddyfile tokens into iss. // // ... zerossl [<api_key>] { // ... // } // // Any of the subdirectives for the ACME issuer can be used in the block. func (iss *ZeroSSLIssuer) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { if d.NextArg() { iss.APIKey = d.Val() if d.NextArg() { return d.ArgErr() } } if iss.ACMEIssuer == nil { iss.ACMEIssuer = new(ACMEIssuer) } err := iss.ACMEIssuer.UnmarshalCaddyfile(d.NewFromNextSegment()) if err != nil { return err } } return nil } const zerosslAPIBase = "https://api.zerossl.com/acme" // Interface guards var ( _ certmagic.PreChecker = (*ZeroSSLIssuer)(nil) _ certmagic.Issuer = (*ZeroSSLIssuer)(nil) _ certmagic.Revoker = (*ZeroSSLIssuer)(nil) _ caddy.Provisioner = (*ZeroSSLIssuer)(nil) _ ConfigSetter = (*ZeroSSLIssuer)(nil) // a type which properly embeds an ACMEIssuer should implement // this interface so it can be treated as an ACMEIssuer _ interface{ GetACMEIssuer() *ACMEIssuer } = (*ZeroSSLIssuer)(nil) )
Go
caddy/modules/caddytls/distributedstek/distributedstek.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 distributedstek provides TLS session ticket ephemeral // keys (STEKs) in a distributed fashion by utilizing configured // storage for locking and key sharing. This allows a cluster of // machines to optimally resume TLS sessions in a load-balanced // environment without any hassle. This is similar to what // Twitter does, but without needing to rely on SSH, as it is // built into the web server this way: // https://blog.twitter.com/engineering/en_us/a/2013/forward-secrecy-at-twitter.html package distributedstek import ( "bytes" "encoding/gob" "encoding/json" "errors" "fmt" "io/fs" "log" "runtime/debug" "time" "github.com/caddyserver/certmagic" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddytls" ) func init() { caddy.RegisterModule(Provider{}) } // Provider implements a distributed STEK provider. This // module will obtain STEKs from a storage module instead // of generating STEKs internally. This allows STEKs to be // coordinated, improving TLS session resumption in a cluster. type Provider struct { // The storage module wherein to store and obtain session // ticket keys. If unset, Caddy's default/global-configured // storage module will be used. Storage json.RawMessage `json:"storage,omitempty" caddy:"namespace=caddy.storage inline_key=module"` storage certmagic.Storage stekConfig *caddytls.SessionTicketService timer *time.Timer ctx caddy.Context } // CaddyModule returns the Caddy module information. func (Provider) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "tls.stek.distributed", New: func() caddy.Module { return new(Provider) }, } } // Provision provisions s. func (s *Provider) Provision(ctx caddy.Context) error { s.ctx = ctx // unpack the storage module to use, if different from the default if s.Storage != nil { val, err := ctx.LoadModule(s, "Storage") if err != nil { return fmt.Errorf("loading TLS storage module: %s", err) } cmStorage, err := val.(caddy.StorageConverter).CertMagicStorage() if err != nil { return fmt.Errorf("creating TLS storage configuration: %v", err) } s.storage = cmStorage } // otherwise, use default storage if s.storage == nil { s.storage = ctx.Storage() } return nil } // Initialize sets the configuration for s and returns the starting keys. func (s *Provider) Initialize(config *caddytls.SessionTicketService) ([][32]byte, error) { // keep a reference to the config; we'll need it when rotating keys s.stekConfig = config dstek, err := s.getSTEK() if err != nil { return nil, err } // create timer for the remaining time on the interval; // this timer is cleaned up only when rotate() returns s.timer = time.NewTimer(time.Until(dstek.NextRotation)) return dstek.Keys, nil } // Next returns a channel which transmits the latest session ticket keys. func (s *Provider) Next(doneChan <-chan struct{}) <-chan [][32]byte { keysChan := make(chan [][32]byte) go s.rotate(doneChan, keysChan) return keysChan } func (s *Provider) loadSTEK() (distributedSTEK, error) { var sg distributedSTEK gobBytes, err := s.storage.Load(s.ctx, stekFileName) if err != nil { return sg, err // don't wrap, in case error is certmagic.ErrNotExist } dec := gob.NewDecoder(bytes.NewReader(gobBytes)) err = dec.Decode(&sg) if err != nil { return sg, fmt.Errorf("STEK gob corrupted: %v", err) } return sg, nil } func (s *Provider) storeSTEK(dstek distributedSTEK) error { var buf bytes.Buffer err := gob.NewEncoder(&buf).Encode(dstek) if err != nil { return fmt.Errorf("encoding STEK gob: %v", err) } err = s.storage.Store(s.ctx, stekFileName, buf.Bytes()) if err != nil { return fmt.Errorf("storing STEK gob: %v", err) } return nil } // getSTEK locks and loads the current STEK from storage. If none // currently exists, a new STEK is created and persisted. If the // current STEK is outdated (NextRotation time is in the past), // then it is rotated and persisted. The resulting STEK is returned. func (s *Provider) getSTEK() (distributedSTEK, error) { err := s.storage.Lock(s.ctx, stekLockName) if err != nil { return distributedSTEK{}, fmt.Errorf("failed to acquire storage lock: %v", err) } //nolint:errcheck defer s.storage.Unlock(s.ctx, stekLockName) // load the current STEKs from storage dstek, err := s.loadSTEK() if errors.Is(err, fs.ErrNotExist) { // if there is none, then make some right away dstek, err = s.rotateKeys(dstek) if err != nil { return dstek, fmt.Errorf("creating new STEK: %v", err) } } else if err != nil { // some other error, that's a problem return dstek, fmt.Errorf("loading STEK: %v", err) } else if time.Now().After(dstek.NextRotation) { // if current STEKs are outdated, rotate them dstek, err = s.rotateKeys(dstek) if err != nil { return dstek, fmt.Errorf("rotating keys: %v", err) } } return dstek, nil } // rotateKeys rotates the keys of oldSTEK and returns the new distributedSTEK // with updated keys and timestamps. It stores the returned STEK in storage, // so this function must only be called in a storage-provided lock. func (s *Provider) rotateKeys(oldSTEK distributedSTEK) (distributedSTEK, error) { var newSTEK distributedSTEK var err error newSTEK.Keys, err = s.stekConfig.RotateSTEKs(oldSTEK.Keys) if err != nil { return newSTEK, err } now := time.Now() newSTEK.LastRotation = now newSTEK.NextRotation = now.Add(time.Duration(s.stekConfig.RotationInterval)) err = s.storeSTEK(newSTEK) if err != nil { return newSTEK, err } return newSTEK, nil } // rotate rotates keys on a regular basis, sending each updated set of // keys down keysChan, until doneChan is closed. func (s *Provider) rotate(doneChan <-chan struct{}, keysChan chan<- [][32]byte) { defer func() { if err := recover(); err != nil { log.Printf("[PANIC] distributed STEK rotation: %v\n%s", err, debug.Stack()) } }() for { select { case <-s.timer.C: dstek, err := s.getSTEK() if err != nil { // TODO: improve this handling log.Printf("[ERROR] Loading STEK: %v", err) continue } // send the updated keys to the service keysChan <- dstek.Keys // timer channel is already drained, so reset directly (see godoc) s.timer.Reset(time.Until(dstek.NextRotation)) case <-doneChan: // again, see godocs for why timer is stopped this way if !s.timer.Stop() { <-s.timer.C } return } } } type distributedSTEK struct { Keys [][32]byte LastRotation, NextRotation time.Time } const ( stekLockName = "stek_check" stekFileName = "stek/stek.bin" ) // Interface guard var _ caddytls.STEKProvider = (*Provider)(nil)
Go
caddy/modules/caddytls/standardstek/stek.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 standardstek import ( "log" "runtime/debug" "sync" "time" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddytls" ) func init() { caddy.RegisterModule(standardSTEKProvider{}) } type standardSTEKProvider struct { stekConfig *caddytls.SessionTicketService timer *time.Timer } // CaddyModule returns the Caddy module information. func (standardSTEKProvider) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "tls.stek.standard", New: func() caddy.Module { return new(standardSTEKProvider) }, } } // Initialize sets the configuration for s and returns the starting keys. func (s *standardSTEKProvider) Initialize(config *caddytls.SessionTicketService) ([][32]byte, error) { // keep a reference to the config; we'll need it when rotating keys s.stekConfig = config itvl := time.Duration(s.stekConfig.RotationInterval) mutex.Lock() defer mutex.Unlock() // if this is our first rotation or we are overdue // for one, perform a rotation immediately; otherwise, // we assume that the keys are non-empty and fresh since := time.Since(lastRotation) if lastRotation.IsZero() || since > itvl { var err error keys, err = s.stekConfig.RotateSTEKs(keys) if err != nil { return nil, err } since = 0 // since this is overdue or is the first rotation, use full interval lastRotation = time.Now() } // create timer for the remaining time on the interval; // this timer is cleaned up only when Next() returns s.timer = time.NewTimer(itvl - since) return keys, nil } // Next returns a channel which transmits the latest session ticket keys. func (s *standardSTEKProvider) Next(doneChan <-chan struct{}) <-chan [][32]byte { keysChan := make(chan [][32]byte) go s.rotate(doneChan, keysChan) return keysChan } // rotate rotates keys on a regular basis, sending each updated set of // keys down keysChan, until doneChan is closed. func (s *standardSTEKProvider) rotate(doneChan <-chan struct{}, keysChan chan<- [][32]byte) { defer func() { if err := recover(); err != nil { log.Printf("[PANIC] standard STEK rotation: %v\n%s", err, debug.Stack()) } }() for { select { case now := <-s.timer.C: // copy the slice header to avoid races mutex.RLock() keysCopy := keys mutex.RUnlock() // generate a new key, rotating old ones var err error keysCopy, err = s.stekConfig.RotateSTEKs(keysCopy) if err != nil { // TODO: improve this handling log.Printf("[ERROR] Generating STEK: %v", err) continue } // replace keys slice with updated value and // record the timestamp of rotation mutex.Lock() keys = keysCopy lastRotation = now mutex.Unlock() // send the updated keys to the service keysChan <- keysCopy // timer channel is already drained, so reset directly (see godoc) s.timer.Reset(time.Duration(s.stekConfig.RotationInterval)) case <-doneChan: // again, see godocs for why timer is stopped this way if !s.timer.Stop() { <-s.timer.C } return } } } var ( lastRotation time.Time keys [][32]byte mutex sync.RWMutex // protects keys and lastRotation ) // Interface guard var _ caddytls.STEKProvider = (*standardSTEKProvider)(nil)
Go
caddy/modules/filestorage/filestorage.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package filestorage import ( "github.com/caddyserver/certmagic" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func init() { caddy.RegisterModule(FileStorage{}) } // FileStorage is a certmagic.Storage wrapper for certmagic.FileStorage. type FileStorage struct { // The base path to the folder used for storage. Root string `json:"root,omitempty"` } // CaddyModule returns the Caddy module information. func (FileStorage) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "caddy.storage.file_system", New: func() caddy.Module { return new(FileStorage) }, } } // CertMagicStorage converts s to a certmagic.Storage instance. func (s FileStorage) CertMagicStorage() (certmagic.Storage, error) { return &certmagic.FileStorage{Path: s.Root}, nil } // UnmarshalCaddyfile sets up the storage module from Caddyfile tokens. func (s *FileStorage) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { if !d.Next() { return d.Err("expected tokens") } if d.NextArg() { s.Root = d.Val() } if d.NextArg() { return d.ArgErr() } for nesting := d.Nesting(); d.NextBlock(nesting); { switch d.Val() { case "root": if !d.NextArg() { return d.ArgErr() } if s.Root != "" { return d.Err("root already set") } s.Root = d.Val() if d.NextArg() { return d.ArgErr() } default: return d.Errf("unrecognized parameter '%s'", d.Val()) } } if s.Root == "" { return d.Err("missing root path (to use default, omit storage config entirely)") } return nil } // Interface guards var ( _ caddy.StorageConverter = (*FileStorage)(nil) _ caddyfile.Unmarshaler = (*FileStorage)(nil) )
Go
caddy/modules/logging/encoders.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package logging import ( "time" "go.uber.org/zap" "go.uber.org/zap/buffer" "go.uber.org/zap/zapcore" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func init() { caddy.RegisterModule(ConsoleEncoder{}) caddy.RegisterModule(JSONEncoder{}) } // ConsoleEncoder encodes log entries that are mostly human-readable. type ConsoleEncoder struct { zapcore.Encoder `json:"-"` LogEncoderConfig } // CaddyModule returns the Caddy module information. func (ConsoleEncoder) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "caddy.logging.encoders.console", New: func() caddy.Module { return new(ConsoleEncoder) }, } } // Provision sets up the encoder. func (ce *ConsoleEncoder) Provision(_ caddy.Context) error { if ce.LevelFormat == "" { ce.LevelFormat = "color" } if ce.TimeFormat == "" { ce.TimeFormat = "wall_milli" } ce.Encoder = zapcore.NewConsoleEncoder(ce.ZapcoreEncoderConfig()) return nil } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. Syntax: // // console { // <common encoder config subdirectives...> // } // // See the godoc on the LogEncoderConfig type for the syntax of // subdirectives that are common to most/all encoders. func (ce *ConsoleEncoder) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { if d.NextArg() { return d.ArgErr() } err := ce.LogEncoderConfig.UnmarshalCaddyfile(d) if err != nil { return err } } return nil } // JSONEncoder encodes entries as JSON. type JSONEncoder struct { zapcore.Encoder `json:"-"` LogEncoderConfig } // CaddyModule returns the Caddy module information. func (JSONEncoder) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "caddy.logging.encoders.json", New: func() caddy.Module { return new(JSONEncoder) }, } } // Provision sets up the encoder. func (je *JSONEncoder) Provision(_ caddy.Context) error { je.Encoder = zapcore.NewJSONEncoder(je.ZapcoreEncoderConfig()) return nil } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. Syntax: // // json { // <common encoder config subdirectives...> // } // // See the godoc on the LogEncoderConfig type for the syntax of // subdirectives that are common to most/all encoders. func (je *JSONEncoder) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { if d.NextArg() { return d.ArgErr() } err := je.LogEncoderConfig.UnmarshalCaddyfile(d) if err != nil { return err } } return nil } // LogEncoderConfig holds configuration common to most encoders. type LogEncoderConfig struct { MessageKey *string `json:"message_key,omitempty"` LevelKey *string `json:"level_key,omitempty"` TimeKey *string `json:"time_key,omitempty"` NameKey *string `json:"name_key,omitempty"` CallerKey *string `json:"caller_key,omitempty"` StacktraceKey *string `json:"stacktrace_key,omitempty"` LineEnding *string `json:"line_ending,omitempty"` TimeFormat string `json:"time_format,omitempty"` TimeLocal bool `json:"time_local,omitempty"` DurationFormat string `json:"duration_format,omitempty"` LevelFormat string `json:"level_format,omitempty"` } // UnmarshalCaddyfile populates the struct from Caddyfile tokens. Syntax: // // { // message_key <key> // level_key <key> // time_key <key> // name_key <key> // caller_key <key> // stacktrace_key <key> // line_ending <char> // time_format <format> // time_local // duration_format <format> // level_format <format> // } func (lec *LogEncoderConfig) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for nesting := d.Nesting(); d.NextBlock(nesting); { subdir := d.Val() switch subdir { case "time_local": lec.TimeLocal = true if d.NextArg() { return d.ArgErr() } continue } var arg string if !d.AllArgs(&arg) { return d.ArgErr() } switch subdir { case "message_key": lec.MessageKey = &arg case "level_key": lec.LevelKey = &arg case "time_key": lec.TimeKey = &arg case "name_key": lec.NameKey = &arg case "caller_key": lec.CallerKey = &arg case "stacktrace_key": lec.StacktraceKey = &arg case "line_ending": lec.LineEnding = &arg case "time_format": lec.TimeFormat = arg case "duration_format": lec.DurationFormat = arg case "level_format": lec.LevelFormat = arg default: return d.Errf("unrecognized subdirective %s", subdir) } } return nil } // ZapcoreEncoderConfig returns the equivalent zapcore.EncoderConfig. // If lec is nil, zap.NewProductionEncoderConfig() is returned. func (lec *LogEncoderConfig) ZapcoreEncoderConfig() zapcore.EncoderConfig { cfg := zap.NewProductionEncoderConfig() if lec == nil { lec = new(LogEncoderConfig) } if lec.MessageKey != nil { cfg.MessageKey = *lec.MessageKey } if lec.LevelKey != nil { cfg.LevelKey = *lec.LevelKey } if lec.TimeKey != nil { cfg.TimeKey = *lec.TimeKey } if lec.NameKey != nil { cfg.NameKey = *lec.NameKey } if lec.CallerKey != nil { cfg.CallerKey = *lec.CallerKey } if lec.StacktraceKey != nil { cfg.StacktraceKey = *lec.StacktraceKey } if lec.LineEnding != nil { cfg.LineEnding = *lec.LineEnding } // time format var timeFormatter zapcore.TimeEncoder switch lec.TimeFormat { case "", "unix_seconds_float": timeFormatter = zapcore.EpochTimeEncoder case "unix_milli_float": timeFormatter = zapcore.EpochMillisTimeEncoder case "unix_nano": timeFormatter = zapcore.EpochNanosTimeEncoder case "iso8601": timeFormatter = zapcore.ISO8601TimeEncoder default: timeFormat := lec.TimeFormat switch lec.TimeFormat { case "rfc3339": timeFormat = time.RFC3339 case "rfc3339_nano": timeFormat = time.RFC3339Nano case "wall": timeFormat = "2006/01/02 15:04:05" case "wall_milli": timeFormat = "2006/01/02 15:04:05.000" case "wall_nano": timeFormat = "2006/01/02 15:04:05.000000000" case "common_log": timeFormat = "02/Jan/2006:15:04:05 -0700" } timeFormatter = func(ts time.Time, encoder zapcore.PrimitiveArrayEncoder) { var time time.Time if lec.TimeLocal { time = ts.Local() } else { time = ts.UTC() } encoder.AppendString(time.Format(timeFormat)) } } cfg.EncodeTime = timeFormatter // duration format var durFormatter zapcore.DurationEncoder switch lec.DurationFormat { case "", "seconds": durFormatter = zapcore.SecondsDurationEncoder case "nano": durFormatter = zapcore.NanosDurationEncoder case "string": durFormatter = zapcore.StringDurationEncoder } cfg.EncodeDuration = durFormatter // level format var levelFormatter zapcore.LevelEncoder switch lec.LevelFormat { case "", "lower": levelFormatter = zapcore.LowercaseLevelEncoder case "upper": levelFormatter = zapcore.CapitalLevelEncoder case "color": levelFormatter = zapcore.CapitalColorLevelEncoder } cfg.EncodeLevel = levelFormatter return cfg } var bufferpool = buffer.NewPool() // Interface guards var ( _ zapcore.Encoder = (*ConsoleEncoder)(nil) _ zapcore.Encoder = (*JSONEncoder)(nil) _ caddyfile.Unmarshaler = (*ConsoleEncoder)(nil) _ caddyfile.Unmarshaler = (*JSONEncoder)(nil) )
Go
caddy/modules/logging/filewriter.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package logging import ( "fmt" "io" "math" "os" "path/filepath" "strconv" "github.com/dustin/go-humanize" "gopkg.in/natefinch/lumberjack.v2" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func init() { caddy.RegisterModule(FileWriter{}) } // FileWriter can write logs to files. By default, log files // are rotated ("rolled") when they get large, and old log // files get deleted, to ensure that the process does not // exhaust disk space. type FileWriter struct { // Filename is the name of the file to write. Filename string `json:"filename,omitempty"` // Roll toggles log rolling or rotation, which is // enabled by default. Roll *bool `json:"roll,omitempty"` // When a log file reaches approximately this size, // it will be rotated. RollSizeMB int `json:"roll_size_mb,omitempty"` // Whether to compress rolled files. Default: true RollCompress *bool `json:"roll_gzip,omitempty"` // Whether to use local timestamps in rolled filenames. // Default: false RollLocalTime bool `json:"roll_local_time,omitempty"` // The maximum number of rolled log files to keep. // Default: 10 RollKeep int `json:"roll_keep,omitempty"` // How many days to keep rolled log files. Default: 90 RollKeepDays int `json:"roll_keep_days,omitempty"` } // CaddyModule returns the Caddy module information. func (FileWriter) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "caddy.logging.writers.file", New: func() caddy.Module { return new(FileWriter) }, } } // Provision sets up the module func (fw *FileWriter) Provision(ctx caddy.Context) error { // Replace placeholder in filename repl := caddy.NewReplacer() filename, err := repl.ReplaceOrErr(fw.Filename, true, true) if err != nil { return fmt.Errorf("invalid filename for log file: %v", err) } fw.Filename = filename return nil } func (fw FileWriter) String() string { fpath, err := filepath.Abs(fw.Filename) if err == nil { return fpath } return fw.Filename } // WriterKey returns a unique key representing this fw. func (fw FileWriter) WriterKey() string { return "file:" + fw.Filename } // OpenWriter opens a new file writer. func (fw FileWriter) OpenWriter() (io.WriteCloser, error) { // roll log files by default if fw.Roll == nil || *fw.Roll { if fw.RollSizeMB == 0 { fw.RollSizeMB = 100 } if fw.RollCompress == nil { compress := true fw.RollCompress = &compress } if fw.RollKeep == 0 { fw.RollKeep = 10 } if fw.RollKeepDays == 0 { fw.RollKeepDays = 90 } return &lumberjack.Logger{ Filename: fw.Filename, MaxSize: fw.RollSizeMB, MaxAge: fw.RollKeepDays, MaxBackups: fw.RollKeep, LocalTime: fw.RollLocalTime, Compress: *fw.RollCompress, }, nil } // otherwise just open a regular file return os.OpenFile(fw.Filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o666) } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. Syntax: // // file <filename> { // roll_disabled // roll_size <size> // roll_uncompressed // roll_local_time // roll_keep <num> // roll_keep_for <days> // } // // The roll_size value has megabyte resolution. // Fractional values are rounded up to the next whole megabyte (MiB). // // By default, compression is enabled, but can be turned off by setting // the roll_uncompressed option. // // The roll_keep_for duration has day resolution. // Fractional values are rounded up to the next whole number of days. // // If any of the roll_size, roll_keep, or roll_keep_for subdirectives are // omitted or set to a zero value, then Caddy's default value for that // subdirective is used. func (fw *FileWriter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { if !d.NextArg() { return d.ArgErr() } fw.Filename = d.Val() if d.NextArg() { return d.ArgErr() } for d.NextBlock(0) { switch d.Val() { case "roll_disabled": var f bool fw.Roll = &f if d.NextArg() { return d.ArgErr() } case "roll_size": var sizeStr string if !d.AllArgs(&sizeStr) { return d.ArgErr() } size, err := humanize.ParseBytes(sizeStr) if err != nil { return d.Errf("parsing size: %v", err) } fw.RollSizeMB = int(math.Ceil(float64(size) / humanize.MiByte)) case "roll_uncompressed": var f bool fw.RollCompress = &f if d.NextArg() { return d.ArgErr() } case "roll_local_time": fw.RollLocalTime = true if d.NextArg() { return d.ArgErr() } case "roll_keep": var keepStr string if !d.AllArgs(&keepStr) { return d.ArgErr() } keep, err := strconv.Atoi(keepStr) if err != nil { return d.Errf("parsing roll_keep number: %v", err) } fw.RollKeep = keep case "roll_keep_for": var keepForStr string if !d.AllArgs(&keepForStr) { return d.ArgErr() } keepFor, err := caddy.ParseDuration(keepForStr) if err != nil { return d.Errf("parsing roll_keep_for duration: %v", err) } if keepFor < 0 { return d.Errf("negative roll_keep_for duration: %v", keepFor) } fw.RollKeepDays = int(math.Ceil(keepFor.Hours() / 24)) } } } return nil } // Interface guards var ( _ caddy.Provisioner = (*FileWriter)(nil) _ caddy.WriterOpener = (*FileWriter)(nil) _ caddyfile.Unmarshaler = (*FileWriter)(nil) )
Go
caddy/modules/logging/filterencoder.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package logging import ( "encoding/json" "fmt" "time" "go.uber.org/zap" "go.uber.org/zap/buffer" "go.uber.org/zap/zapcore" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func init() { caddy.RegisterModule(FilterEncoder{}) } // FilterEncoder can filter (manipulate) fields on // log entries before they are actually encoded by // an underlying encoder. type FilterEncoder struct { // The underlying encoder that actually // encodes the log entries. Required. WrappedRaw json.RawMessage `json:"wrap,omitempty" caddy:"namespace=caddy.logging.encoders inline_key=format"` // A map of field names to their filters. Note that this // is not a module map; the keys are field names. // // Nested fields can be referenced by representing a // layer of nesting with `>`. In other words, for an // object like `{"a":{"b":0}}`, the inner field can // be referenced as `a>b`. // // The following fields are fundamental to the log and // cannot be filtered because they are added by the // underlying logging library as special cases: ts, // level, logger, and msg. FieldsRaw map[string]json.RawMessage `json:"fields,omitempty" caddy:"namespace=caddy.logging.encoders.filter inline_key=filter"` wrapped zapcore.Encoder Fields map[string]LogFieldFilter `json:"-"` // used to keep keys unique across nested objects keyPrefix string } // CaddyModule returns the Caddy module information. func (FilterEncoder) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "caddy.logging.encoders.filter", New: func() caddy.Module { return new(FilterEncoder) }, } } // Provision sets up the encoder. func (fe *FilterEncoder) Provision(ctx caddy.Context) error { if fe.WrappedRaw == nil { return fmt.Errorf("missing \"wrap\" (must specify an underlying encoder)") } // set up wrapped encoder (required) val, err := ctx.LoadModule(fe, "WrappedRaw") if err != nil { return fmt.Errorf("loading fallback encoder module: %v", err) } fe.wrapped = val.(zapcore.Encoder) // set up each field filter if fe.Fields == nil { fe.Fields = make(map[string]LogFieldFilter) } vals, err := ctx.LoadModule(fe, "FieldsRaw") if err != nil { return fmt.Errorf("loading log filter modules: %v", err) } for fieldName, modIface := range vals.(map[string]any) { fe.Fields[fieldName] = modIface.(LogFieldFilter) } return nil } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. Syntax: // // filter { // wrap <another encoder> // fields { // <field> <filter> { // <filter options> // } // } // } func (fe *FilterEncoder) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { for d.NextBlock(0) { switch d.Val() { case "wrap": if !d.NextArg() { return d.ArgErr() } moduleName := d.Val() moduleID := "caddy.logging.encoders." + moduleName unm, err := caddyfile.UnmarshalModule(d, moduleID) if err != nil { return err } enc, ok := unm.(zapcore.Encoder) if !ok { return d.Errf("module %s (%T) is not a zapcore.Encoder", moduleID, unm) } fe.WrappedRaw = caddyconfig.JSONModuleObject(enc, "format", moduleName, nil) case "fields": for d.NextBlock(1) { field := d.Val() if !d.NextArg() { return d.ArgErr() } filterName := d.Val() moduleID := "caddy.logging.encoders.filter." + filterName unm, err := caddyfile.UnmarshalModule(d, moduleID) if err != nil { return err } filter, ok := unm.(LogFieldFilter) if !ok { return d.Errf("module %s (%T) is not a logging.LogFieldFilter", moduleID, unm) } if fe.FieldsRaw == nil { fe.FieldsRaw = make(map[string]json.RawMessage) } fe.FieldsRaw[field] = caddyconfig.JSONModuleObject(filter, "filter", filterName, nil) } default: return d.Errf("unrecognized subdirective %s", d.Val()) } } } return nil } // AddArray is part of the zapcore.ObjectEncoder interface. // Array elements do not get filtered. func (fe FilterEncoder) AddArray(key string, marshaler zapcore.ArrayMarshaler) error { if filter, ok := fe.Fields[fe.keyPrefix+key]; ok { filter.Filter(zap.Array(key, marshaler)).AddTo(fe.wrapped) return nil } return fe.wrapped.AddArray(key, marshaler) } // AddObject is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddObject(key string, marshaler zapcore.ObjectMarshaler) error { if fe.filtered(key, marshaler) { return nil } fe.keyPrefix += key + ">" return fe.wrapped.AddObject(key, logObjectMarshalerWrapper{ enc: fe, marsh: marshaler, }) } // AddBinary is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddBinary(key string, value []byte) { if !fe.filtered(key, value) { fe.wrapped.AddBinary(key, value) } } // AddByteString is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddByteString(key string, value []byte) { if !fe.filtered(key, value) { fe.wrapped.AddByteString(key, value) } } // AddBool is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddBool(key string, value bool) { if !fe.filtered(key, value) { fe.wrapped.AddBool(key, value) } } // AddComplex128 is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddComplex128(key string, value complex128) { if !fe.filtered(key, value) { fe.wrapped.AddComplex128(key, value) } } // AddComplex64 is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddComplex64(key string, value complex64) { if !fe.filtered(key, value) { fe.wrapped.AddComplex64(key, value) } } // AddDuration is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddDuration(key string, value time.Duration) { if !fe.filtered(key, value) { fe.wrapped.AddDuration(key, value) } } // AddFloat64 is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddFloat64(key string, value float64) { if !fe.filtered(key, value) { fe.wrapped.AddFloat64(key, value) } } // AddFloat32 is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddFloat32(key string, value float32) { if !fe.filtered(key, value) { fe.wrapped.AddFloat32(key, value) } } // AddInt is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddInt(key string, value int) { if !fe.filtered(key, value) { fe.wrapped.AddInt(key, value) } } // AddInt64 is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddInt64(key string, value int64) { if !fe.filtered(key, value) { fe.wrapped.AddInt64(key, value) } } // AddInt32 is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddInt32(key string, value int32) { if !fe.filtered(key, value) { fe.wrapped.AddInt32(key, value) } } // AddInt16 is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddInt16(key string, value int16) { if !fe.filtered(key, value) { fe.wrapped.AddInt16(key, value) } } // AddInt8 is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddInt8(key string, value int8) { if !fe.filtered(key, value) { fe.wrapped.AddInt8(key, value) } } // AddString is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddString(key, value string) { if !fe.filtered(key, value) { fe.wrapped.AddString(key, value) } } // AddTime is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddTime(key string, value time.Time) { if !fe.filtered(key, value) { fe.wrapped.AddTime(key, value) } } // AddUint is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddUint(key string, value uint) { if !fe.filtered(key, value) { fe.wrapped.AddUint(key, value) } } // AddUint64 is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddUint64(key string, value uint64) { if !fe.filtered(key, value) { fe.wrapped.AddUint64(key, value) } } // AddUint32 is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddUint32(key string, value uint32) { if !fe.filtered(key, value) { fe.wrapped.AddUint32(key, value) } } // AddUint16 is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddUint16(key string, value uint16) { if !fe.filtered(key, value) { fe.wrapped.AddUint16(key, value) } } // AddUint8 is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddUint8(key string, value uint8) { if !fe.filtered(key, value) { fe.wrapped.AddUint8(key, value) } } // AddUintptr is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddUintptr(key string, value uintptr) { if !fe.filtered(key, value) { fe.wrapped.AddUintptr(key, value) } } // AddReflected is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddReflected(key string, value any) error { if !fe.filtered(key, value) { return fe.wrapped.AddReflected(key, value) } return nil } // OpenNamespace is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) OpenNamespace(key string) { fe.wrapped.OpenNamespace(key) } // Clone is part of the zapcore.ObjectEncoder interface. // We don't use it as of Oct 2019 (v2 beta 7), I'm not // really sure what it'd be useful for in our case. func (fe FilterEncoder) Clone() zapcore.Encoder { return FilterEncoder{ Fields: fe.Fields, wrapped: fe.wrapped.Clone(), keyPrefix: fe.keyPrefix, } } // EncodeEntry partially implements the zapcore.Encoder interface. func (fe FilterEncoder) EncodeEntry(ent zapcore.Entry, fields []zapcore.Field) (*buffer.Buffer, error) { // without this clone and storing it to fe.wrapped, fields // from subsequent log entries get appended to previous // ones, and I'm not 100% sure why; see end of // https://github.com/uber-go/zap/issues/750 fe.wrapped = fe.wrapped.Clone() for _, field := range fields { field.AddTo(fe) } return fe.wrapped.EncodeEntry(ent, nil) } // filtered returns true if the field was filtered. // If true is returned, the field was filtered and // added to the underlying encoder (so do not do // that again). If false was returned, the field has // not yet been added to the underlying encoder. func (fe FilterEncoder) filtered(key string, value any) bool { filter, ok := fe.Fields[fe.keyPrefix+key] if !ok { return false } filter.Filter(zap.Any(key, value)).AddTo(fe.wrapped) return true } // logObjectMarshalerWrapper allows us to recursively // filter fields of objects as they get encoded. type logObjectMarshalerWrapper struct { enc FilterEncoder marsh zapcore.ObjectMarshaler } // MarshalLogObject implements the zapcore.ObjectMarshaler interface. func (mom logObjectMarshalerWrapper) MarshalLogObject(_ zapcore.ObjectEncoder) error { return mom.marsh.MarshalLogObject(mom.enc) } // Interface guards var ( _ zapcore.Encoder = (*FilterEncoder)(nil) _ zapcore.ObjectMarshaler = (*logObjectMarshalerWrapper)(nil) _ caddyfile.Unmarshaler = (*FilterEncoder)(nil) )
Go
caddy/modules/logging/filters.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package logging import ( "crypto/sha256" "errors" "fmt" "net" "net/http" "net/url" "regexp" "strconv" "strings" "go.uber.org/zap/zapcore" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func init() { caddy.RegisterModule(DeleteFilter{}) caddy.RegisterModule(HashFilter{}) caddy.RegisterModule(ReplaceFilter{}) caddy.RegisterModule(IPMaskFilter{}) caddy.RegisterModule(QueryFilter{}) caddy.RegisterModule(CookieFilter{}) caddy.RegisterModule(RegexpFilter{}) caddy.RegisterModule(RenameFilter{}) } // LogFieldFilter can filter (or manipulate) // a field in a log entry. type LogFieldFilter interface { Filter(zapcore.Field) zapcore.Field } // DeleteFilter is a Caddy log field filter that // deletes the field. type DeleteFilter struct{} // CaddyModule returns the Caddy module information. func (DeleteFilter) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "caddy.logging.encoders.filter.delete", New: func() caddy.Module { return new(DeleteFilter) }, } } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. func (DeleteFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { return nil } // Filter filters the input field. func (DeleteFilter) Filter(in zapcore.Field) zapcore.Field { in.Type = zapcore.SkipType return in } // hash returns the first 4 bytes of the SHA-256 hash of the given data as hexadecimal func hash(s string) string { return fmt.Sprintf("%.4x", sha256.Sum256([]byte(s))) } // HashFilter is a Caddy log field filter that // replaces the field with the initial 4 bytes // of the SHA-256 hash of the content. Operates // on string fields, or on arrays of strings // where each string is hashed. type HashFilter struct{} // CaddyModule returns the Caddy module information. func (HashFilter) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "caddy.logging.encoders.filter.hash", New: func() caddy.Module { return new(HashFilter) }, } } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. func (f *HashFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { return nil } // Filter filters the input field with the replacement value. func (f *HashFilter) Filter(in zapcore.Field) zapcore.Field { if array, ok := in.Interface.(caddyhttp.LoggableStringArray); ok { for i, s := range array { array[i] = hash(s) } } else { in.String = hash(in.String) } return in } // ReplaceFilter is a Caddy log field filter that // replaces the field with the indicated string. type ReplaceFilter struct { Value string `json:"value,omitempty"` } // CaddyModule returns the Caddy module information. func (ReplaceFilter) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "caddy.logging.encoders.filter.replace", New: func() caddy.Module { return new(ReplaceFilter) }, } } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. func (f *ReplaceFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { if d.NextArg() { f.Value = d.Val() } } return nil } // Filter filters the input field with the replacement value. func (f *ReplaceFilter) Filter(in zapcore.Field) zapcore.Field { in.Type = zapcore.StringType in.String = f.Value return in } // IPMaskFilter is a Caddy log field filter that // masks IP addresses in a string, or in an array // of strings. The string may be a comma separated // list of IP addresses, where all of the values // will be masked. type IPMaskFilter struct { // The IPv4 mask, as an subnet size CIDR. IPv4MaskRaw int `json:"ipv4_cidr,omitempty"` // The IPv6 mask, as an subnet size CIDR. IPv6MaskRaw int `json:"ipv6_cidr,omitempty"` v4Mask net.IPMask v6Mask net.IPMask } // CaddyModule returns the Caddy module information. func (IPMaskFilter) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "caddy.logging.encoders.filter.ip_mask", New: func() caddy.Module { return new(IPMaskFilter) }, } } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. func (m *IPMaskFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { for d.NextBlock(0) { switch d.Val() { case "ipv4": if !d.NextArg() { return d.ArgErr() } val, err := strconv.Atoi(d.Val()) if err != nil { return d.Errf("error parsing %s: %v", d.Val(), err) } m.IPv4MaskRaw = val case "ipv6": if !d.NextArg() { return d.ArgErr() } val, err := strconv.Atoi(d.Val()) if err != nil { return d.Errf("error parsing %s: %v", d.Val(), err) } m.IPv6MaskRaw = val default: return d.Errf("unrecognized subdirective %s", d.Val()) } } } return nil } // Provision parses m's IP masks, from integers. func (m *IPMaskFilter) Provision(ctx caddy.Context) error { parseRawToMask := func(rawField int, bitLen int) net.IPMask { if rawField == 0 { return nil } // we assume the int is a subnet size CIDR // e.g. "16" being equivalent to masking the last // two bytes of an ipv4 address, like "255.255.0.0" return net.CIDRMask(rawField, bitLen) } m.v4Mask = parseRawToMask(m.IPv4MaskRaw, 32) m.v6Mask = parseRawToMask(m.IPv6MaskRaw, 128) return nil } // Filter filters the input field. func (m IPMaskFilter) Filter(in zapcore.Field) zapcore.Field { if array, ok := in.Interface.(caddyhttp.LoggableStringArray); ok { for i, s := range array { array[i] = m.mask(s) } } else { in.String = m.mask(in.String) } return in } func (m IPMaskFilter) mask(s string) string { output := "" for _, value := range strings.Split(s, ",") { value = strings.TrimSpace(value) host, port, err := net.SplitHostPort(value) if err != nil { host = value // assume whole thing was IP address } ipAddr := net.ParseIP(host) if ipAddr == nil { output += value + ", " continue } mask := m.v4Mask if ipAddr.To4() == nil { mask = m.v6Mask } masked := ipAddr.Mask(mask) if port == "" { output += masked.String() + ", " continue } output += net.JoinHostPort(masked.String(), port) + ", " } return strings.TrimSuffix(output, ", ") } type filterAction string const ( // Replace value(s). replaceAction filterAction = "replace" // Hash value(s). hashAction filterAction = "hash" // Delete. deleteAction filterAction = "delete" ) func (a filterAction) IsValid() error { switch a { case replaceAction, deleteAction, hashAction: return nil } return errors.New("invalid action type") } type queryFilterAction struct { // `replace` to replace the value(s) associated with the parameter(s), `hash` to replace them with the 4 initial bytes of the SHA-256 of their content or `delete` to remove them entirely. Type filterAction `json:"type"` // The name of the query parameter. Parameter string `json:"parameter"` // The value to use as replacement if the action is `replace`. Value string `json:"value,omitempty"` } // QueryFilter is a Caddy log field filter that filters // query parameters from a URL. // // This filter updates the logged URL string to remove, replace or hash // query parameters containing sensitive data. For instance, it can be // used to redact any kind of secrets which were passed as query parameters, // such as OAuth access tokens, session IDs, magic link tokens, etc. type QueryFilter struct { // A list of actions to apply to the query parameters of the URL. Actions []queryFilterAction `json:"actions"` } // Validate checks that action types are correct. func (f *QueryFilter) Validate() error { for _, a := range f.Actions { if err := a.Type.IsValid(); err != nil { return err } } return nil } // CaddyModule returns the Caddy module information. func (QueryFilter) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "caddy.logging.encoders.filter.query", New: func() caddy.Module { return new(QueryFilter) }, } } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. func (m *QueryFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { for d.NextBlock(0) { qfa := queryFilterAction{} switch d.Val() { case "replace": if !d.NextArg() { return d.ArgErr() } qfa.Type = replaceAction qfa.Parameter = d.Val() if !d.NextArg() { return d.ArgErr() } qfa.Value = d.Val() case "hash": if !d.NextArg() { return d.ArgErr() } qfa.Type = hashAction qfa.Parameter = d.Val() case "delete": if !d.NextArg() { return d.ArgErr() } qfa.Type = deleteAction qfa.Parameter = d.Val() default: return d.Errf("unrecognized subdirective %s", d.Val()) } m.Actions = append(m.Actions, qfa) } } return nil } // Filter filters the input field. func (m QueryFilter) Filter(in zapcore.Field) zapcore.Field { u, err := url.Parse(in.String) if err != nil { return in } q := u.Query() for _, a := range m.Actions { switch a.Type { case replaceAction: for i := range q[a.Parameter] { q[a.Parameter][i] = a.Value } case hashAction: for i := range q[a.Parameter] { q[a.Parameter][i] = hash(a.Value) } case deleteAction: q.Del(a.Parameter) } } u.RawQuery = q.Encode() in.String = u.String() return in } type cookieFilterAction struct { // `replace` to replace the value of the cookie, `hash` to replace it with the 4 initial bytes of the SHA-256 of its content or `delete` to remove it entirely. Type filterAction `json:"type"` // The name of the cookie. Name string `json:"name"` // The value to use as replacement if the action is `replace`. Value string `json:"value,omitempty"` } // CookieFilter is a Caddy log field filter that filters // cookies. // // This filter updates the logged HTTP header string // to remove, replace or hash cookies containing sensitive data. For instance, // it can be used to redact any kind of secrets, such as session IDs. // // If several actions are configured for the same cookie name, only the first // will be applied. type CookieFilter struct { // A list of actions to apply to the cookies. Actions []cookieFilterAction `json:"actions"` } // Validate checks that action types are correct. func (f *CookieFilter) Validate() error { for _, a := range f.Actions { if err := a.Type.IsValid(); err != nil { return err } } return nil } // CaddyModule returns the Caddy module information. func (CookieFilter) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "caddy.logging.encoders.filter.cookie", New: func() caddy.Module { return new(CookieFilter) }, } } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. func (m *CookieFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { for d.NextBlock(0) { cfa := cookieFilterAction{} switch d.Val() { case "replace": if !d.NextArg() { return d.ArgErr() } cfa.Type = replaceAction cfa.Name = d.Val() if !d.NextArg() { return d.ArgErr() } cfa.Value = d.Val() case "hash": if !d.NextArg() { return d.ArgErr() } cfa.Type = hashAction cfa.Name = d.Val() case "delete": if !d.NextArg() { return d.ArgErr() } cfa.Type = deleteAction cfa.Name = d.Val() default: return d.Errf("unrecognized subdirective %s", d.Val()) } m.Actions = append(m.Actions, cfa) } } return nil } // Filter filters the input field. func (m CookieFilter) Filter(in zapcore.Field) zapcore.Field { cookiesSlice, ok := in.Interface.(caddyhttp.LoggableStringArray) if !ok { return in } // using a dummy Request to make use of the Cookies() function to parse it originRequest := http.Request{Header: http.Header{"Cookie": cookiesSlice}} cookies := originRequest.Cookies() transformedRequest := http.Request{Header: make(http.Header)} OUTER: for _, c := range cookies { for _, a := range m.Actions { if c.Name != a.Name { continue } switch a.Type { case replaceAction: c.Value = a.Value transformedRequest.AddCookie(c) continue OUTER case hashAction: c.Value = hash(c.Value) transformedRequest.AddCookie(c) continue OUTER case deleteAction: continue OUTER } } transformedRequest.AddCookie(c) } in.Interface = caddyhttp.LoggableStringArray(transformedRequest.Header["Cookie"]) return in } // RegexpFilter is a Caddy log field filter that // replaces the field matching the provided regexp // with the indicated string. If the field is an // array of strings, each of them will have the // regexp replacement applied. type RegexpFilter struct { // The regular expression pattern defining what to replace. RawRegexp string `json:"regexp,omitempty"` // The value to use as replacement Value string `json:"value,omitempty"` regexp *regexp.Regexp } // CaddyModule returns the Caddy module information. func (RegexpFilter) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "caddy.logging.encoders.filter.regexp", New: func() caddy.Module { return new(RegexpFilter) }, } } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. func (f *RegexpFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { if d.NextArg() { f.RawRegexp = d.Val() } if d.NextArg() { f.Value = d.Val() } } return nil } // Provision compiles m's regexp. func (m *RegexpFilter) Provision(ctx caddy.Context) error { r, err := regexp.Compile(m.RawRegexp) if err != nil { return err } m.regexp = r return nil } // Filter filters the input field with the replacement value if it matches the regexp. func (f *RegexpFilter) Filter(in zapcore.Field) zapcore.Field { if array, ok := in.Interface.(caddyhttp.LoggableStringArray); ok { for i, s := range array { array[i] = f.regexp.ReplaceAllString(s, f.Value) } } else { in.String = f.regexp.ReplaceAllString(in.String, f.Value) } return in } // RenameFilter is a Caddy log field filter that // renames the field's key with the indicated name. type RenameFilter struct { Name string `json:"name,omitempty"` } // CaddyModule returns the Caddy module information. func (RenameFilter) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "caddy.logging.encoders.filter.rename", New: func() caddy.Module { return new(RenameFilter) }, } } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. func (f *RenameFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { if d.NextArg() { f.Name = d.Val() } } return nil } // Filter renames the input field with the replacement name. func (f *RenameFilter) Filter(in zapcore.Field) zapcore.Field { in.Key = f.Name return in } // Interface guards var ( _ LogFieldFilter = (*DeleteFilter)(nil) _ LogFieldFilter = (*HashFilter)(nil) _ LogFieldFilter = (*ReplaceFilter)(nil) _ LogFieldFilter = (*IPMaskFilter)(nil) _ LogFieldFilter = (*QueryFilter)(nil) _ LogFieldFilter = (*CookieFilter)(nil) _ LogFieldFilter = (*RegexpFilter)(nil) _ LogFieldFilter = (*RenameFilter)(nil) _ caddyfile.Unmarshaler = (*DeleteFilter)(nil) _ caddyfile.Unmarshaler = (*HashFilter)(nil) _ caddyfile.Unmarshaler = (*ReplaceFilter)(nil) _ caddyfile.Unmarshaler = (*IPMaskFilter)(nil) _ caddyfile.Unmarshaler = (*QueryFilter)(nil) _ caddyfile.Unmarshaler = (*CookieFilter)(nil) _ caddyfile.Unmarshaler = (*RegexpFilter)(nil) _ caddyfile.Unmarshaler = (*RenameFilter)(nil) _ caddy.Provisioner = (*IPMaskFilter)(nil) _ caddy.Provisioner = (*RegexpFilter)(nil) _ caddy.Validator = (*QueryFilter)(nil) )
Go
caddy/modules/logging/filters_test.go
package logging import ( "testing" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" "go.uber.org/zap/zapcore" ) func TestIPMaskSingleValue(t *testing.T) { f := IPMaskFilter{IPv4MaskRaw: 16, IPv6MaskRaw: 32} f.Provision(caddy.Context{}) out := f.Filter(zapcore.Field{String: "255.255.255.255"}) if out.String != "255.255.0.0" { t.Fatalf("field has not been filtered: %s", out.String) } out = f.Filter(zapcore.Field{String: "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"}) if out.String != "ffff:ffff::" { t.Fatalf("field has not been filtered: %s", out.String) } out = f.Filter(zapcore.Field{String: "not-an-ip"}) if out.String != "not-an-ip" { t.Fatalf("field has been filtered: %s", out.String) } } func TestIPMaskCommaValue(t *testing.T) { f := IPMaskFilter{IPv4MaskRaw: 16, IPv6MaskRaw: 32} f.Provision(caddy.Context{}) out := f.Filter(zapcore.Field{String: "255.255.255.255, 244.244.244.244"}) if out.String != "255.255.0.0, 244.244.0.0" { t.Fatalf("field has not been filtered: %s", out.String) } out = f.Filter(zapcore.Field{String: "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff, ff00:ffff:ffff:ffff:ffff:ffff:ffff:ffff"}) if out.String != "ffff:ffff::, ff00:ffff::" { t.Fatalf("field has not been filtered: %s", out.String) } out = f.Filter(zapcore.Field{String: "not-an-ip, 255.255.255.255"}) if out.String != "not-an-ip, 255.255.0.0" { t.Fatalf("field has not been filtered: %s", out.String) } } func TestIPMaskMultiValue(t *testing.T) { f := IPMaskFilter{IPv4MaskRaw: 16, IPv6MaskRaw: 32} f.Provision(caddy.Context{}) out := f.Filter(zapcore.Field{Interface: caddyhttp.LoggableStringArray{ "255.255.255.255", "244.244.244.244", }}) arr, ok := out.Interface.(caddyhttp.LoggableStringArray) if !ok { t.Fatalf("field is wrong type: %T", out.Integer) } if arr[0] != "255.255.0.0" { t.Fatalf("field entry 0 has not been filtered: %s", arr[0]) } if arr[1] != "244.244.0.0" { t.Fatalf("field entry 1 has not been filtered: %s", arr[1]) } out = f.Filter(zapcore.Field{Interface: caddyhttp.LoggableStringArray{ "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", "ff00:ffff:ffff:ffff:ffff:ffff:ffff:ffff", }}) arr, ok = out.Interface.(caddyhttp.LoggableStringArray) if !ok { t.Fatalf("field is wrong type: %T", out.Integer) } if arr[0] != "ffff:ffff::" { t.Fatalf("field entry 0 has not been filtered: %s", arr[0]) } if arr[1] != "ff00:ffff::" { t.Fatalf("field entry 1 has not been filtered: %s", arr[1]) } } func TestQueryFilter(t *testing.T) { f := QueryFilter{[]queryFilterAction{ {replaceAction, "foo", "REDACTED"}, {replaceAction, "notexist", "REDACTED"}, {deleteAction, "bar", ""}, {deleteAction, "notexist", ""}, {hashAction, "hash", ""}, }} if f.Validate() != nil { t.Fatalf("the filter must be valid") } out := f.Filter(zapcore.Field{String: "/path?foo=a&foo=b&bar=c&bar=d&baz=e&hash=hashed"}) if out.String != "/path?baz=e&foo=REDACTED&foo=REDACTED&hash=e3b0c442" { t.Fatalf("query parameters have not been filtered: %s", out.String) } } func TestValidateQueryFilter(t *testing.T) { f := QueryFilter{[]queryFilterAction{ {}, }} if f.Validate() == nil { t.Fatalf("empty action type must be invalid") } f = QueryFilter{[]queryFilterAction{ {Type: "foo"}, }} if f.Validate() == nil { t.Fatalf("unknown action type must be invalid") } } func TestCookieFilter(t *testing.T) { f := CookieFilter{[]cookieFilterAction{ {replaceAction, "foo", "REDACTED"}, {deleteAction, "bar", ""}, {hashAction, "hash", ""}, }} out := f.Filter(zapcore.Field{Interface: caddyhttp.LoggableStringArray{ "foo=a; foo=b; bar=c; bar=d; baz=e; hash=hashed", }}) outval := out.Interface.(caddyhttp.LoggableStringArray) expected := caddyhttp.LoggableStringArray{ "foo=REDACTED; foo=REDACTED; baz=e; hash=1a06df82", } if outval[0] != expected[0] { t.Fatalf("cookies have not been filtered: %s", out.String) } } func TestValidateCookieFilter(t *testing.T) { f := CookieFilter{[]cookieFilterAction{ {}, }} if f.Validate() == nil { t.Fatalf("empty action type must be invalid") } f = CookieFilter{[]cookieFilterAction{ {Type: "foo"}, }} if f.Validate() == nil { t.Fatalf("unknown action type must be invalid") } } func TestRegexpFilterSingleValue(t *testing.T) { f := RegexpFilter{RawRegexp: `secret`, Value: "REDACTED"} f.Provision(caddy.Context{}) out := f.Filter(zapcore.Field{String: "foo-secret-bar"}) if out.String != "foo-REDACTED-bar" { t.Fatalf("field has not been filtered: %s", out.String) } } func TestRegexpFilterMultiValue(t *testing.T) { f := RegexpFilter{RawRegexp: `secret`, Value: "REDACTED"} f.Provision(caddy.Context{}) out := f.Filter(zapcore.Field{Interface: caddyhttp.LoggableStringArray{"foo-secret-bar", "bar-secret-foo"}}) arr, ok := out.Interface.(caddyhttp.LoggableStringArray) if !ok { t.Fatalf("field is wrong type: %T", out.Integer) } if arr[0] != "foo-REDACTED-bar" { t.Fatalf("field entry 0 has not been filtered: %s", arr[0]) } if arr[1] != "bar-REDACTED-foo" { t.Fatalf("field entry 1 has not been filtered: %s", arr[1]) } } func TestHashFilterSingleValue(t *testing.T) { f := HashFilter{} out := f.Filter(zapcore.Field{String: "foo"}) if out.String != "2c26b46b" { t.Fatalf("field has not been filtered: %s", out.String) } } func TestHashFilterMultiValue(t *testing.T) { f := HashFilter{} out := f.Filter(zapcore.Field{Interface: caddyhttp.LoggableStringArray{"foo", "bar"}}) arr, ok := out.Interface.(caddyhttp.LoggableStringArray) if !ok { t.Fatalf("field is wrong type: %T", out.Integer) } if arr[0] != "2c26b46b" { t.Fatalf("field entry 0 has not been filtered: %s", arr[0]) } if arr[1] != "fcde2b2e" { t.Fatalf("field entry 1 has not been filtered: %s", arr[1]) } }
Go
caddy/modules/logging/netwriter.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package logging import ( "fmt" "io" "net" "os" "sync" "time" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func init() { caddy.RegisterModule(NetWriter{}) } // NetWriter implements a log writer that outputs to a network socket. If // the socket goes down, it will dump logs to stderr while it attempts to // reconnect. type NetWriter struct { // The address of the network socket to which to connect. Address string `json:"address,omitempty"` // The timeout to wait while connecting to the socket. DialTimeout caddy.Duration `json:"dial_timeout,omitempty"` // If enabled, allow connections errors when first opening the // writer. The error and subsequent log entries will be reported // to stderr instead until a connection can be re-established. SoftStart bool `json:"soft_start,omitempty"` addr caddy.NetworkAddress } // CaddyModule returns the Caddy module information. func (NetWriter) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "caddy.logging.writers.net", New: func() caddy.Module { return new(NetWriter) }, } } // Provision sets up the module. func (nw *NetWriter) Provision(ctx caddy.Context) error { repl := caddy.NewReplacer() address, err := repl.ReplaceOrErr(nw.Address, true, true) if err != nil { return fmt.Errorf("invalid host in address: %v", err) } nw.addr, err = caddy.ParseNetworkAddress(address) if err != nil { return fmt.Errorf("parsing network address '%s': %v", address, err) } if nw.addr.PortRangeSize() != 1 { return fmt.Errorf("multiple ports not supported") } if nw.DialTimeout < 0 { return fmt.Errorf("timeout cannot be less than 0") } return nil } func (nw NetWriter) String() string { return nw.addr.String() } // WriterKey returns a unique key representing this nw. func (nw NetWriter) WriterKey() string { return nw.addr.String() } // OpenWriter opens a new network connection. func (nw NetWriter) OpenWriter() (io.WriteCloser, error) { reconn := &redialerConn{ nw: nw, timeout: time.Duration(nw.DialTimeout), } conn, err := reconn.dial() if err != nil { if !nw.SoftStart { return nil, err } // don't block config load if remote is down or some other external problem; // we can dump logs to stderr for now (see issue #5520) fmt.Fprintf(os.Stderr, "[ERROR] net log writer failed to connect: %v (will retry connection and print errors here in the meantime)\n", err) } reconn.connMu.Lock() reconn.Conn = conn reconn.connMu.Unlock() return reconn, nil } // UnmarshalCaddyfile sets up the handler from Caddyfile tokens. Syntax: // // net <address> { // dial_timeout <duration> // soft_start // } func (nw *NetWriter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { if !d.NextArg() { return d.ArgErr() } nw.Address = d.Val() if d.NextArg() { return d.ArgErr() } for nesting := d.Nesting(); d.NextBlock(nesting); { switch d.Val() { case "dial_timeout": if !d.NextArg() { return d.ArgErr() } timeout, err := caddy.ParseDuration(d.Val()) if err != nil { return d.Errf("invalid duration: %s", d.Val()) } if d.NextArg() { return d.ArgErr() } nw.DialTimeout = caddy.Duration(timeout) case "soft_start": if d.NextArg() { return d.ArgErr() } nw.SoftStart = true } } } return nil } // redialerConn wraps an underlying Conn so that if any // writes fail, the connection is redialed and the write // is retried. type redialerConn struct { net.Conn connMu sync.RWMutex nw NetWriter timeout time.Duration lastRedial time.Time } // Write wraps the underlying Conn.Write method, but if that fails, // it will re-dial the connection anew and try writing again. func (reconn *redialerConn) Write(b []byte) (n int, err error) { reconn.connMu.RLock() conn := reconn.Conn reconn.connMu.RUnlock() if conn != nil { if n, err = conn.Write(b); err == nil { return } } // problem with the connection - lock it and try to fix it reconn.connMu.Lock() defer reconn.connMu.Unlock() // if multiple concurrent writes failed on the same broken conn, then // one of them might have already re-dialed by now; try writing again if reconn.Conn != nil { if n, err = reconn.Conn.Write(b); err == nil { return } } // there's still a problem, so try to re-attempt dialing the socket // if some time has passed in which the issue could have potentially // been resolved - we don't want to block at every single log // emission (!) - see discussion in #4111 if time.Since(reconn.lastRedial) > 10*time.Second { reconn.lastRedial = time.Now() conn2, err2 := reconn.dial() if err2 != nil { // logger socket still offline; instead of discarding the log, dump it to stderr os.Stderr.Write(b) return } if n, err = conn2.Write(b); err == nil { if reconn.Conn != nil { reconn.Conn.Close() } reconn.Conn = conn2 } } else { // last redial attempt was too recent; just dump to stderr for now os.Stderr.Write(b) } return } func (reconn *redialerConn) dial() (net.Conn, error) { return net.DialTimeout(reconn.nw.addr.Network, reconn.nw.addr.JoinHostPort(0), reconn.timeout) } // Interface guards var ( _ caddy.Provisioner = (*NetWriter)(nil) _ caddy.WriterOpener = (*NetWriter)(nil) _ caddyfile.Unmarshaler = (*NetWriter)(nil) )
Go
caddy/modules/logging/nopencoder.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package logging import ( "time" "go.uber.org/zap/buffer" "go.uber.org/zap/zapcore" ) // nopEncoder is a zapcore.Encoder that does nothing. type nopEncoder struct{} // AddArray is part of the zapcore.ObjectEncoder interface. // Array elements do not get filtered. func (nopEncoder) AddArray(key string, marshaler zapcore.ArrayMarshaler) error { return nil } // AddObject is part of the zapcore.ObjectEncoder interface. func (nopEncoder) AddObject(key string, marshaler zapcore.ObjectMarshaler) error { return nil } // AddBinary is part of the zapcore.ObjectEncoder interface. func (nopEncoder) AddBinary(key string, value []byte) {} // AddByteString is part of the zapcore.ObjectEncoder interface. func (nopEncoder) AddByteString(key string, value []byte) {} // AddBool is part of the zapcore.ObjectEncoder interface. func (nopEncoder) AddBool(key string, value bool) {} // AddComplex128 is part of the zapcore.ObjectEncoder interface. func (nopEncoder) AddComplex128(key string, value complex128) {} // AddComplex64 is part of the zapcore.ObjectEncoder interface. func (nopEncoder) AddComplex64(key string, value complex64) {} // AddDuration is part of the zapcore.ObjectEncoder interface. func (nopEncoder) AddDuration(key string, value time.Duration) {} // AddFloat64 is part of the zapcore.ObjectEncoder interface. func (nopEncoder) AddFloat64(key string, value float64) {} // AddFloat32 is part of the zapcore.ObjectEncoder interface. func (nopEncoder) AddFloat32(key string, value float32) {} // AddInt is part of the zapcore.ObjectEncoder interface. func (nopEncoder) AddInt(key string, value int) {} // AddInt64 is part of the zapcore.ObjectEncoder interface. func (nopEncoder) AddInt64(key string, value int64) {} // AddInt32 is part of the zapcore.ObjectEncoder interface. func (nopEncoder) AddInt32(key string, value int32) {} // AddInt16 is part of the zapcore.ObjectEncoder interface. func (nopEncoder) AddInt16(key string, value int16) {} // AddInt8 is part of the zapcore.ObjectEncoder interface. func (nopEncoder) AddInt8(key string, value int8) {} // AddString is part of the zapcore.ObjectEncoder interface. func (nopEncoder) AddString(key, value string) {} // AddTime is part of the zapcore.ObjectEncoder interface. func (nopEncoder) AddTime(key string, value time.Time) {} // AddUint is part of the zapcore.ObjectEncoder interface. func (nopEncoder) AddUint(key string, value uint) {} // AddUint64 is part of the zapcore.ObjectEncoder interface. func (nopEncoder) AddUint64(key string, value uint64) {} // AddUint32 is part of the zapcore.ObjectEncoder interface. func (nopEncoder) AddUint32(key string, value uint32) {} // AddUint16 is part of the zapcore.ObjectEncoder interface. func (nopEncoder) AddUint16(key string, value uint16) {} // AddUint8 is part of the zapcore.ObjectEncoder interface. func (nopEncoder) AddUint8(key string, value uint8) {} // AddUintptr is part of the zapcore.ObjectEncoder interface. func (nopEncoder) AddUintptr(key string, value uintptr) {} // AddReflected is part of the zapcore.ObjectEncoder interface. func (nopEncoder) AddReflected(key string, value any) error { return nil } // OpenNamespace is part of the zapcore.ObjectEncoder interface. func (nopEncoder) OpenNamespace(key string) {} // Clone is part of the zapcore.ObjectEncoder interface. // We don't use it as of Oct 2019 (v2 beta 7), I'm not // really sure what it'd be useful for in our case. func (ne nopEncoder) Clone() zapcore.Encoder { return ne } // EncodeEntry partially implements the zapcore.Encoder interface. func (nopEncoder) EncodeEntry(ent zapcore.Entry, fields []zapcore.Field) (*buffer.Buffer, error) { return bufferpool.Get(), nil } // Interface guard var _ zapcore.Encoder = (*nopEncoder)(nil)
Go
caddy/modules/metrics/adminmetrics.go
// Copyright 2020 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 metrics import ( "net/http" "github.com/caddyserver/caddy/v2" ) func init() { caddy.RegisterModule(AdminMetrics{}) } // AdminMetrics is a module that serves a metrics endpoint so that any gathered // metrics can be exposed for scraping. This module is not configurable, and // is permanently mounted to the admin API endpoint at "/metrics". // See the Metrics module for a configurable endpoint that is usable if the // Admin API is disabled. type AdminMetrics struct{} // CaddyModule returns the Caddy module information. func (AdminMetrics) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "admin.api.metrics", New: func() caddy.Module { return new(AdminMetrics) }, } } // Routes returns a route for the /metrics endpoint. func (m *AdminMetrics) Routes() []caddy.AdminRoute { metricsHandler := createMetricsHandler(nil, false) h := caddy.AdminHandlerFunc(func(w http.ResponseWriter, r *http.Request) error { metricsHandler.ServeHTTP(w, r) return nil }) return []caddy.AdminRoute{{Pattern: "/metrics", Handler: h}} } // Interface guards var ( _ caddy.AdminRouter = (*AdminMetrics)(nil) )
Go
caddy/modules/metrics/metrics.go
// Copyright 2020 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 metrics import ( "net/http" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" "go.uber.org/zap" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func init() { caddy.RegisterModule(Metrics{}) httpcaddyfile.RegisterHandlerDirective("metrics", parseCaddyfile) } // Metrics is a module that serves a /metrics endpoint so that any gathered // metrics can be exposed for scraping. This module is configurable by end-users // unlike AdminMetrics. type Metrics struct { metricsHandler http.Handler // Disable OpenMetrics negotiation, enabled by default. May be necessary if // the produced metrics cannot be parsed by the service scraping metrics. DisableOpenMetrics bool `json:"disable_openmetrics,omitempty"` } // CaddyModule returns the Caddy module information. func (Metrics) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.handlers.metrics", New: func() caddy.Module { return new(Metrics) }, } } type zapLogger struct { zl *zap.Logger } func (l *zapLogger) Println(v ...any) { l.zl.Sugar().Error(v...) } // Provision sets up m. func (m *Metrics) Provision(ctx caddy.Context) error { log := ctx.Logger() m.metricsHandler = createMetricsHandler(&zapLogger{log}, !m.DisableOpenMetrics) return nil } func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) { var m Metrics err := m.UnmarshalCaddyfile(h.Dispenser) return m, err } // UnmarshalCaddyfile sets up the handler from Caddyfile tokens. Syntax: // // metrics [<matcher>] { // disable_openmetrics // } func (m *Metrics) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { args := d.RemainingArgs() if len(args) > 0 { return d.ArgErr() } for d.NextBlock(0) { switch d.Val() { case "disable_openmetrics": m.DisableOpenMetrics = true default: return d.Errf("unrecognized subdirective %q", d.Val()) } } } return nil } func (m Metrics) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { m.metricsHandler.ServeHTTP(w, r) return nil } // Interface guards var ( _ caddy.Provisioner = (*Metrics)(nil) _ caddyhttp.MiddlewareHandler = (*Metrics)(nil) _ caddyfile.Unmarshaler = (*Metrics)(nil) ) func createMetricsHandler(logger promhttp.Logger, enableOpenMetrics bool) http.Handler { return promhttp.InstrumentMetricHandler(prometheus.DefaultRegisterer, promhttp.HandlerFor(prometheus.DefaultGatherer, promhttp.HandlerOpts{ // will only log errors if logger is non-nil ErrorLog: logger, // Allow OpenMetrics format to be negotiated - largely compatible, // except quantile/le label values always have a decimal. EnableOpenMetrics: enableOpenMetrics, }), ) }
Go
caddy/modules/metrics/metrics_test.go
package metrics import ( "testing" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func TestMetricsUnmarshalCaddyfile(t *testing.T) { m := &Metrics{} d := caddyfile.NewTestDispenser(`metrics bogus`) err := m.UnmarshalCaddyfile(d) if err == nil { t.Errorf("expected error") } m = &Metrics{} d = caddyfile.NewTestDispenser(`metrics`) err = m.UnmarshalCaddyfile(d) if err != nil { t.Errorf("unexpected error: %v", err) } if m.DisableOpenMetrics { t.Errorf("DisableOpenMetrics should've been false: %v", m.DisableOpenMetrics) } m = &Metrics{} d = caddyfile.NewTestDispenser(`metrics { disable_openmetrics }`) err = m.UnmarshalCaddyfile(d) if err != nil { t.Errorf("unexpected error: %v", err) } if !m.DisableOpenMetrics { t.Errorf("DisableOpenMetrics should've been true: %v", m.DisableOpenMetrics) } m = &Metrics{} d = caddyfile.NewTestDispenser(`metrics { bogus }`) err = m.UnmarshalCaddyfile(d) if err == nil { t.Errorf("expected error: %v", err) } }
Go
caddy/modules/standard/imports.go
package standard import ( // standard Caddy modules _ "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" _ "github.com/caddyserver/caddy/v2/modules/caddyevents" _ "github.com/caddyserver/caddy/v2/modules/caddyevents/eventsconfig" _ "github.com/caddyserver/caddy/v2/modules/caddyhttp/standard" _ "github.com/caddyserver/caddy/v2/modules/caddypki" _ "github.com/caddyserver/caddy/v2/modules/caddypki/acmeserver" _ "github.com/caddyserver/caddy/v2/modules/caddytls" _ "github.com/caddyserver/caddy/v2/modules/caddytls/distributedstek" _ "github.com/caddyserver/caddy/v2/modules/caddytls/standardstek" _ "github.com/caddyserver/caddy/v2/modules/filestorage" _ "github.com/caddyserver/caddy/v2/modules/logging" _ "github.com/caddyserver/caddy/v2/modules/metrics" )
Go
caddy/notify/notify_linux.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 notify provides facilities for notifying process managers // of state changes, mainly for when running as a system service. package notify import ( "fmt" "net" "os" "strings" ) // The documentation about this IPC protocol is available here: // https://www.freedesktop.org/software/systemd/man/sd_notify.html func sdNotify(payload string) error { if socketPath == "" { return nil } socketAddr := &net.UnixAddr{ Name: socketPath, Net: "unixgram", } conn, err := net.DialUnix(socketAddr.Net, nil, socketAddr) if err != nil { return err } defer conn.Close() _, err = conn.Write([]byte(payload)) return err } // Ready notifies systemd that caddy has finished its // initialization routines. func Ready() error { return sdNotify("READY=1") } // Reloading notifies systemd that caddy is reloading its config. func Reloading() error { return sdNotify("RELOADING=1") } // Stopping notifies systemd that caddy is stopping. func Stopping() error { return sdNotify("STOPPING=1") } // Status sends systemd an updated status message. func Status(msg string) error { return sdNotify("STATUS=" + msg) } // Error is like Status, but sends systemd an error message // instead, with an optional errno-style error number. func Error(err error, errno int) error { collapsedErr := strings.ReplaceAll(err.Error(), "\n", " ") msg := fmt.Sprintf("STATUS=%s", collapsedErr) if errno > 0 { msg += fmt.Sprintf("\nERRNO=%d", errno) } return sdNotify(msg) } var socketPath, _ = os.LookupEnv("NOTIFY_SOCKET")
Go
caddy/notify/notify_other.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 !linux && !windows package notify func Ready() error { return nil } func Reloading() error { return nil } func Stopping() error { return nil } func Status(_ string) error { return nil } func Error(_ error, _ int) error { return nil }
Go
caddy/notify/notify_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 notify import "golang.org/x/sys/windows/svc" // globalStatus store windows service status, it can be // use to notify caddy status. var globalStatus chan<- svc.Status func SetGlobalStatus(status chan<- svc.Status) { globalStatus = status } func Ready() error { if globalStatus != nil { globalStatus <- svc.Status{ State: svc.Running, Accepts: svc.AcceptStop | svc.AcceptShutdown, } } return nil } func Reloading() error { if globalStatus != nil { globalStatus <- svc.Status{State: svc.StartPending} } return nil } func Stopping() error { if globalStatus != nil { globalStatus <- svc.Status{State: svc.StopPending} } return nil } // TODO: not implemented func Status(_ string) error { return nil } // TODO: not implemented func Error(_ error, _ int) error { return nil }